Skip to content

tools: fold an initializer-fed Transpose at pack time, so the head weight is stored the way the matmul reads it - #2728

Merged
bong-water-water-bong merged 3 commits into
mainfrom
fix/fold-head-transpose
Nov 16, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
fix/fold-head-transpose

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2366 (the fix, not the analysis — the analysis landed as issue comments).

[audio-node] 785 Transpose 768x51865 = 101.258 ms sits beside 786 MatMul 1x128x51865 = 193.072 ms, and it runs 26 times per transcription, so ~2.6 s of a 3.5 s wall clock is spent transposing a weight that never changes.

The weight is the lm head, and the head is weight-tied to the token embedding. On the shipped pack:

$ python3 tools/fold_initializer_transpose.py --check scratch-packs/pi-demo/whisper-small/decoder_model.onnx
node_transpose: Transpose of initializer token_embedding.weight is still in the graph
... nodes 786, initializer-fed Transposes 1
rc=1

token_embedding.weight is 51865x768 = 159 MB; transposed it is the 768x51865 the matmul wants. That is also why the node exists: the same initializer feeds the input gather untransposed and the head matmul transposed, so the export inserts the transpose rather than storing two copies.

Why the fix is here and not in audio_exec

Engine#2366 records two reverted attempts, both mine: a per-execution cache never fires (one Transpose per pass), and a cross-execution cache on OnnxGraphInfo does r.data = cv->second, which copies the 159 MB per pass — it saves arithmetic, not the copy, and the encoder regressed to 10.36 s. A weight that cannot change belongs in the pack, not in a cache in front of it.

What changed

tools/fold_initializer_transpose.py, onnx only (no onnxruntime):

  • initializer_transposes() — the only Transposes a weight rewrite can remove are the ones whose input is a graph initializer; the other 120 in this decoder read activations and are left alone.
  • fold() — transposes the initializer with the node's own perm, appends <name>_t, repoints every consumer of the node output, drops the node, and prunes the old initializer only when nothing reads it. Here the gather still does, so the untransposed copy is kept.
  • --check exits 1 while any initializer-fed Transpose survives, so a pack build can refuse the fold-less file instead of silently paying the 2.6 s again.

tests/fold_initializer_transpose_test.sh (registered in CI's target list) builds a fixture with exactly the whisper shape — one initializer feeding both a Transpose -> MatMul and a Gather — and asserts the node is gone, the matmul reads w_t, the gather's copy is kept, and --check flips 1 -> 0. My first expectation for the node count was wrong (4 for a 3-node fixture) and the arm caught it.

Measured on the real pack

folded token_embedding.weight -> token_embedding.weight_t [768, 51865]
decoder_folded.onnx: nodes 786 -> 785, folded 1
onnx.checker: ok

Host path, same binary, same wav, packs differing only in decoder_model.onnx:

[audio-node] lines   20910 -> 20884      = 26 fewer, exactly the 26 head executions

The cost, stated: the pack grows by 159 MB (617 MB -> 776 MB) because the untransposed copy is still read by the gather. That is a pack-size-for-time trade, and it is the honest shape of this fix.

Not measured yet: the wall clock. The box was at load 12.2 with thermal-run pausing the process mid-run (43.6 s / 4.95 s / 87.6 s across three attempts, all discarded), and the device arm needs an npu-hold ticket that the owner's npu-serve-keeper currently holds. The 26-node drop is a property of the graph and does not depend on a quiet box; the seconds are owed and will be recorded on #2366 at load <=3 with the pack and binary sha.

Refs #2366, #1783.

@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 -- 26 Transposes x 101 ms in a 3.5 s pipeline is the finding, and the two reverted attempts are what make the placement right

The arithmetic is the strongest part of the motivation: Transpose 768x51865 = 101.258 ms beside the head matmul, 26 times per transcription = ~2.6 s of a 3.5 s wall clock spent transposing a weight that never changes, and the body explains why the node exists at all ("the same initializer feeds the input gather untransposed and the head matmul transposed, so the export inserts the transpose rather than storing two copies"). Then the two reverted attempts are recorded with their costs -- a cross-execution cache copies the 159 MB per pass and the encoder regressed to 10.36 s -- which is the argument for folding at pack time rather than caching in front of it.

Three things I would keep exactly as written:

  • initializer_transposes() only for transposes whose input is a graph initializer, with "the other 120 in this decoder read activations and are left alone" — the blast radius is measured, not assumed;
  • pruning the old initializer only when nothing reads it, and keeping the untransposed copy here because the gather does -- with the cost stated (pack 617 MB -> 776 MB);
  • --check exiting 1 while a foldable transpose survives: "so a pack build can refuse the fold-less file instead of silently paying the 2.6 s again". That is the arm that makes the fold durable rather than a one-off edit.

Two asks:

  1. Say what the folded graph produces, not only that onnx.checker is ok. A weight rewrite that repoints consumers is exactly where a silent correctness break lives; the cheapest evidence is the same wav through the folded and unfolded pack with the transcript compared, or the encoder's output tensor hash. 26 fewer [audio-node] lines, exactly the 26 head executions proves the node count changed, not that the numbers did not.
  2. Wire --check into a gate, so a pack rebuilt without the fold is refused by CI rather than by someone noticing 2.6 s. You already have the exit code; the missing step is a caller.

Nothing else: the fixture's own mistake ("my first expectation for the node count was wrong (4 for a 3-node fixture) and the arm caught it") is worth leaving in the body -- it is why the arm exists. And recording Not measured yet: the wall clock with the load (12.2, thermal-run pausing mid-run) is the right way to defer a number.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The branch carries two commits that are already on main, and its copy of tools/ci/merged_tail_check.py is the pre-#2693 state — so this PR cannot merge cleanly and a branch-side conflict resolution would revert #2693 and #2722. Measured, not inferred:

$ git log --oneline origin/main..refs/heads/tools-fold-transpose
1347a071f tools: fold an initializer-fed Transpose at pack time … (engine#2366)
f0a52c972 merged_tail_check: a submodule gitlink is not a blob …
f7ba0ee8d merged_tail_check: examine refs/pull/<n>/head …
$ git merge-base origin/main refs/heads/tools-fold-transpose
34a29950c  (main, 11-16 ~12:5xZ — before #2693 merged as b6783c35)

Those two merged_tail_check commits are already in main as b6783c35 (a squash, so the shas differ and the branch believes it still owes them). What the branch's file still holds is the old class list and the old longer-only rule:

$ git diff origin/main refs/heads/tools-fold-transpose -- tools/ci/merged_tail_check.py | head
-  SUPERSEDED  … `git log -S <line> <merge>..<base>` … — the LINE rather than the file, because a
-              commit that touched some other line of the same file would otherwise turn a genuine
-              loss into SUPERSEDED, and report() exits 0 on SUPERSEDED.
+  SUPERSEDED  most added lines absent, but every affected base file is LONGER -- a later
+              commit rewrote that region, which is not evidence of a loss

And the merge is not clean:

$ git merge-tree --write-tree origin/main refs/heads/tools-fold-transpose
rc=1
100755 c91c3045c… 1   tools/ci/merged_tail_check.py
100755 94079eb67… 2   tools/ci/merged_tail_check.py

So the shape to avoid is the one #2652 exists for: resolve that conflict toward the branch and the tree silently loses #2693's per-line test and #2722's moved_since guard, which is the pair that stopped report() exiting 0 on a real loss (git show <merged>:tools/ci/merged_tail_check.py | grep -c moved_since would drop from 3 to 0). Resolve it toward main and you drop nothing of yours either — those two commits are already there.

Suggested fix, and it makes the PR smaller rather than bigger: rebase onto current main and drop f7ba0ee8d/f0a52c972, leaving only 1347a071f (tools/fold_initializer_transpose.py, its test, the CMake registration, and the docs). That is the whole of this PR's own work; the two carried commits were a base, not a change.

I am not touching the branch. Saying it here because engine is at 7 non-draft PRs against ORCH's cap of 3, and a stale-based PR is the one kind that cannot be merged or counted out.

@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 1347a07: CHANGES

One blocking item, and it is not about the transpose: this PR's copy of tools/ci/merged_tail_check.py predates two merges and would revert both.

Measured at 1347a07 against main 68090adf:

                                              main   this PR
bool(moved) if after is not None                 1         0     <- #2722's identifier fallback
landed-then-dropped line                         1         0     <- #2721's per-line arm
identifier a missing line is ABOUT               1         0     <- #2722's docstring

All three landed today — #2722 (a longer base file is not a supersession) and #2721 (the arm for the per-line git log -S path). The branch carries an older copy, so merging it as it stands removes both, and the diff makes that look like your change because gh pr diff renders the whole file against the current base.

Fix: rebase onto main. If the file is genuinely part of this PR, rebase and re-apply your edit — the three lines above then survive and your change sits on top. If it is not part of this PR, the rebase drops it and the diff stops showing tools/ci/merged_tail_check.py at all. Either way the branch must not merge with a copy that predates them.

This is the trap the "two open PRs one file" rule exists for, seen from the other side: not two PRs conflicting, but one PR quietly carrying a stale copy of a file that other PRs have since moved. A rebase is the whole fix; there is nothing wrong with the transpose work.

What I checked of the substance, and it looks right

tools/fold_initializer_transpose.py, tests/fold_initializer_transpose_test.sh, and the row are all present:

291:add_test(NAME fold_initializer_transpose COMMAND bash ${CMAKE_SOURCE_DIR}/tests/fold_initializer_transpose_test.sh …)

A .sh row, so it needs no build target — it will execute under ctest rather than being reported Not Run, which is the trap #2674 fell into. The --check invocation in the body that prints node_transpose: Transpose of initializer token_embedding.weight is still in the graph … rc=1 before the fix is exactly the before-state an arm should have.

I have not reviewed the folding logic itself — the revert is the thing that must be fixed first, and re-reviewing on a rebased head costs one pass instead of two.

@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 1347a07: CHANGES

The fold is right for the whisper pack and the six arms pass, but it collapses two different transposes of the same initializer onto one folded weight — and the model it writes is not just wrong, it is invalid. Reproduced; two ways to fix, both a couple of lines.

The fixture

One initializer w (2x3), two Transpose nodes over it with different perms, one consumer each:

X = np.arange(6, dtype=np.float32).reshape(2,3)          # [[0,1,2],[3,4,5]]
t1 = Transpose("w" -> "t1", perm=[1,0]);  a = Identity("t1" -> "out_a")
t2 = Transpose("w" -> "t2", perm=[0,1]);  b = Identity("t2" -> "out_b")
$ fold_initializer_transpose.py two_perms.onnx folded.onnx
folded w -> w_t [3, 2]
folded w -> w_t [2, 3]          <- it reports both folds …
folded.onnx: nodes 4 -> 2, folded 2   rc 0

$ # what the folded graph actually holds
initializers: [('w_t', [3, 2])]                 <- … and writes one
nodes: [('Identity', ['w_t'], ['out_a']), ('Identity', ['w_t'], ['out_b'])]
  out_b <- w_t = [[0,3],[1,4],[2,5]]            <- the [1,0] fold, for a consumer that wanted perm [0,1]

out_b is declared [2,3] and now produces a [3,2] tensor: the folded model does not validate, and on a square weight (where both perms are shape-preserving) it would validate and compute the wrong thing silently. The cause is one line — dst = f"{src}_t" — which identifies the folded weight by the source only, so the second fold finds dst already in inits, skips creating it, and rewires its consumers to the first perm's array.

Two fixes, either is enough

# (a) the folded weight is identified by the permutation, so two transposes fold to two arrays
dst = f"{src}_t{''.join(str(p) for p in perm[0])}"
# (b) or refuse: one weight, one fold, and a graph that wants two gets a message instead of a wrong model
if dst in inits and list(numpy_helper.to_array(inits[dst]).shape) != list(want.shape):
    raise SystemExit(f"{src}: folded twice with different perms; fold the two forms separately")

(a) is the smaller change and keeps the pass-through working; (b) is the conservative one. Either wants an arm: two transposes of one initializer with different perms must either produce two folded weights or exit non-zero — never one weight and a silent shape change. --check will not catch this after the fact, because the Transpose nodes are gone.

What is right, and it is the harder half

$ bash tests/fold_initializer_transpose_test.sh
ok   fold reports one folded weight / the Transpose node is gone / the matmul reads the transposed initializer
ok   the gather's untransposed copy is kept / the folded weight has the matmul orientation / check accepts the folded graph
fold_initializer_transpose: all checks ok

Keeping the original initializer when another consumer still reads it untransposed ("the gather's untransposed copy is kept") is the case that would have broken a pack in a way nobody would trace back to this tool, and np.ascontiguousarray for the new weight is the other detail that matters. --check exiting 1 on a surviving initializer-fed Transpose is the right shape for a pack build: the fold-less file is refused rather than paying 2.6 s a window again.

@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 1347a07: CHANGES

The fold is right — I ran it on the real decoder and every number in the body reproduces. What blocks it is that the branch also carries an unrelated tool change, and GitHub already says CONFLICTING.

Verified end-to-end on the shipped pack

Copied ~/scratch-packs/pi-demo/whisper-small/decoder_model.onnx (616,937,859 B) to scratch and ran the PR's tool at this head:

$ python3 fold.py --check decoder_model.onnx          -> rc 1, "nodes 786, initializer-fed Transposes 1"
$ python3 fold.py decoder_model.onnx out.onnx         -> "nodes 786 -> 785, folded 1"   (4.6 s)
$ python3 fold.py --check out.onnx                    -> rc 0, "nodes 785, initializer-fed Transposes 0"
onnx.checker.check_model(...)                         -> ok

and the graph says the right thing afterwards:

initializers        : token_embedding.weight  AND  token_embedding.weight_t  (768 x 51865)
head MatMul inputs  : ['layer_norm_36', 'token_embedding.weight_t']
Gather inputs       : ['token_embedding.weight', 'x']       <- the untransposed copy is kept, as the body says
Transpose nodes left: 120                                   <- the 120 that read activations are untouched
pack size           : 616,937,859 -> 776,266,026  (+159,328,167 B, i.e. the stated +159 MB)

So the "one initializer feeds both a transpose and a gather" case is handled correctly, the prune-if-unused rule is exercised in its negative direction here, and --check flips 1 -> 0 as claimed. The --check inversion is the part I would keep even if the fold were dropped: it turns "the pack silently pays 2.6 s again" into a build-time refusal.

What blocks it: the branch carries someone else's change, and it is an OLDER one

gh pr view --json files for this PR lists four paths, and one is tools/ci/merged_tail_check.py +40 -7. That hunk is the pre-#2693 supersession code, i.e. the file-granular touched test that was measured wrong, removed and replaced three times today (#2693's review, #2722, #2721 — all merged). The branch's merge-base is 34a29950 ("kernel-set-check…#2654"), which predates all of them, so the hunk is an artefact of where the branch was cut, not work you meant to send.

I checked what a merge would do rather than guessing: git merge-tree --write-tree origin/main <head> keeps main's version of that file (moved_since/distinctive_token present, 6 hits). So a 3-way merge resolves in main's favour — but GitHub reports the PR CONFLICTING / DIRTY anyway, and a squash apply of a diff that deletes the current implementation is not a risk worth carrying for a pack-time fold.

Ask: rebase onto main. After that the PR is three files (tools/fold_initializer_transpose.py, tests/fold_initializer_transpose_test.sh, one CMakeLists line) and nothing in it can touch the tool. Nothing about the fold changes.

Stated limits, agreed with your body

The wall clock is unmeasured and I did not measure it either — 26 fewer [audio-node] lines is a graph property and I reproduced the graph, not the seconds. I did not run your fixture test (tests/fold_initializer_transpose_test.sh) because the three-assertion fixture is weaker evidence than the real pack above; if you want it run, say so and I will do it after the rebase.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This now conflicts with main (CONFLICTING), and the perm fix should ride the rebase so the CI queue pays once.

The conflict is mechanical — the branch was cut before today's merges, and its CMakeLists.txt add_test line landed in a region main has since moved past — so a rebase onto origin/main resolves it without touching your change. Worth doing in the same push as the finding from my review at 1347a071:

# tools/fold_initializer_transpose.py: two Transpose nodes over ONE initializer with different perms
# collapse onto a single {src}_t. The tool prints both folds, writes one, and the second consumer reads
# the first perm's array (my 2x3 fixture: out_b declared [2,3], produced [3,2] -- an invalid model).
dst = f"{src}_t" + "".join(str(p) for p in perm[0])        # (a) name the fold by its perm, or
if dst in inits and shape differs: raise SystemExit(...)    # (b) refuse a second perm for one weight

Plus the arm: two transposes of one initializer with different perms must either produce two folded weights or exit non-zero — never one weight and a silent shape change. Rebased once with both, this is merge-ready; rebased without the fix, it merges a tool that can write an invalid ONNX.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The rebase is one command, and I verified it — your branch is sitting on another lane's pre-merge branch, not on main.

 1347a071  tools: fold an initializer-fed Transpose at pack time …   <- yours
 f0a52c97  merged_tail_check: a submodule gitlink is not a blob …    <- #2693's branch, merged as b6783c35
 f7ba0ee8  merged_tail_check: examine refs/pull/<n>/head …           <- same
 34a29950  (merge-base with main, i.e. before #2693/#2722/#2721)

Those two commits are exactly what the +40 −7 hunk is: the branch you built on carried tools/ci/merged_tail_check.py from before it was reviewed, so the PR's diff shows it as a change and GitHub calls the result CONFLICTING.

Replayed here, on a copy of your head:

$ git checkout -B fix/fold-head-transpose <this head>
$ git rebase --onto origin/main f0a52c97259d3577f7d16a8a2d0340d5ed46d72d
$ git push --force-with-lease

after which

$ git diff --stat origin/main HEAD
 CMakeLists.txt                           |   1 +
 tests/fold_initializer_transpose_test.sh |  79 +++++++++++
 tools/fold_initializer_transpose.py      | 107 +++++++++++++
 3 files changed, 187 insertions(+)

— one commit, three files, no tool file, and git merge-tree origin/main <head> is clean. Nothing about the fold changes, so the CHANGES is only about this. I will re-verdict at the new head (the pack measurement in my verdict was made with the tool at that commit, and it does not depend on the tool at all).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The owed before/after, part one: the node is gone, measured on the host path

Regenerated the folded decoder (786 -> 785 nodes, folded 1) and ran the same binary and wav against both packs with ONEBIT_AUDIO_NODE_TIMES=1:

orig    : Transpose 768x51865 line at index 785,  53 lines mentioning 51865  = vocab line + 26 x (Transpose + MatMul)
folded  : the index-785 node is the MatMul,       27 lines mentioning 51865  = vocab line + 26 x MatMul

26 head executions per transcription became 0, which is the load-independent form of the claim: same node index, no Transpose line, the MatMul still reading the weight.

Per-execution cost, from the orig run at load 2.75:

[audio-node]  785 Transpose          768x51865                 57.785 ms
[audio-node]  785 MatMul             1x128x51865             1838.826 ms

57.8 ms x 26 = ~1.50 s per transcription on the host path (the device figure it was diagnosed from was 101 ms x 26 = ~2.6 s).

What I am still not quoting: the wall clock

orig    at load 2.75 : encoder 13.263 s, wall  58.048 s
folded  at load 33.9 : encoder 59.023 s, wall 614.586 s

The box went from load 2.75 to 33.9 between the two runs, so the folded arm is 10x slower for reasons that have nothing to do with this patch. The pair is noise and I am not presenting it as a result -- it is here only so the shape of the runs is on the record. The single 57.785 ms sample is from the quiet side of that window and is still one sample.

The seconds need two interleaved runs at load <=3 with the pack and binary sha recorded, and the device arm needs an npu-hold ticket (the owner's npu-serve-keeper holds the NPU). Both are owed; the node removal above does not depend on either.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2728

The measurement is what makes this a fix and not a theory: "Transpose 768x51865 = 101.258 ms sits beside 786 MatMul 1x128x51865 = 193.072 ms, and it runs 26 times per transcription, so ~2.6 s of a 3.5 s wall clock is spent transposing a weight that never changes."

A 74 % share of wall clock spent on a constant is the clearest kind of optimisation target: no trade, no tuning, no shapes to sweep — the work simply does not need to happen. And folding it at graph-init time rather than at first inference is the right choice, because it removes the cost from every transcription including the first.

Three asks:

  1. the identity check must be by tensor name + shape, not by "the head is tied" — weight tying is a property of the model, and packs are produced by several exporters; a check that assumes tying will fold the wrong pair on a pack where the head is not tied. State the predicate the folder uses and what it does when the two initializers differ (refuse, not fold);
  2. --check must be part of the arm, not just a tool — the description shows --check catching the still-present transpose, which is good; the test should assert that --check fails on an unfolded pack and passes on a folded one, so the checker is proven in both directions (a checker that always says "still in the graph" is diag: unmap_fault_order reads the kernel's PADDED boot stamp, so a real capture can correlate #2622's regex);
  3. say what happens to a pack whose transpose feeds something else too — 768x51865 is a big fan-out node; if any other consumer still needs the un-transposed layout, folding must keep both. One line on the consumer check, since that is the way this fix could be silently wrong rather than slow.

And note the wall-clock claim's denominator: 3.5 s → expect ~0.9 s if the transpose is fully removed; if the PR has a measured after, quote it against that number rather than "faster", so a partial fold cannot look like a full one.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT at eeccf1f: CHANGES

The same finding, pinned to this head: a re-trigger commit does not change the tool, and the fold-collision is still there at line 55.

$ git show eeccf1fb --stat
 ci: re-trigger (no run was created for 1347a071)      # one empty commit

$ git show eeccf1fb:tools/fold_initializer_transpose.py | sed -n '55p'
        dst = f"{src}_t"

which is the line the finding is about: two Transpose nodes over one initializer with different perms both fold to {src}_t, the second finds it already in inits, skips creating it, and rewires its consumers to the first perm's array. My 2x3 fixture (perm [1,0] and perm [0,1]) produces:

folded w -> w_t [3, 2]
folded w -> w_t [2, 3]        # reported …
initializers: [('w_t', [3, 2])]   # … one written
out_b <- w_t = [[0,3],[1,4],[2,5]]   # for a consumer declared [2,3]

so the written model does not validate, and on a square weight it would validate and compute the wrong tensor silently.

Restating it at this head rather than leaving the previous one to speak for it, because the verdict is a claim about a head and an empty commit is enough to move the head: a READY posted here by a lane that only re-checks CI would clear the block on unchanged code.

The fix is unchanged and small — name the folded weight by its perm (f"{src}_t" + "".join(map(str, perm[0]))), or refuse a second perm for one weight — plus the arm. The rebase is still needed too: the branch was cut before today's merges and GitHub still cannot merge it (UNKNOWN while it re-computes, from CONFLICTING).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

A note for the queue, not a verdict: this branch's diff shows tools/ci/merged_tail_check.py, and its own commit does not touch that file — the file appears because the branch predates #2693's squash merge.

What I measured

$ git show --name-only --format= 1347a071f          # this PR's only code commit
CMakeLists.txt
tests/fold_initializer_transpose_test.sh
tools/fold_initializer_transpose.py          ← no merged_tail_check.py

$ git log --oneline origin/main..HEAD -- tools/ci/merged_tail_check.py
f0a52c972  … a submodule gitlink is not a blob …
f7ba0ee8d  … examine refs/pull/<n>/head …

$ git merge-base origin/main HEAD
34a29950c  kernel-set-check: a documented _m16 twin is a WARN, anything else is a FAIL

So the two merged_tail_check.py commits are #2693's own, carried because this branch forks from a main that predates them; #2693 has since merged (364c9dc, squash), and main already carries both changes (classify_commit(…, after=None) is at line 223 of main's copy).

The consequence for review and for the queue:

  1. A rebase onto current origin/main drops that file from the diff entirely, and with it the overlap with merged_tail_check: a token the file already carried cannot make a dropped line SUPERSEDED #2732 (merged_tail_check.py) — the only file overlap among the open non-draft engine PRs, per a check I ran across all five: tools/ci/merged_tail_check.py: [2732, 2728].
  2. Until then, a reviewer reading the diff sees 337 lines of merged_tail_check.py that are not this PR's, and a merger resolving the overlap would be resolving a squash artefact rather than a conflict.

Nothing wrong with the PR's own change — Transpose folding at pack time, its own test, one CMakeLists.txt row — and I am not posting a verdict here (this head already has one). This is the "carried commit" note I gave llama.cpp#404, and the reason is the same: a diff that includes another PR's work makes its own work harder to see, and in a 3-PR-cap queue the extra file is also what makes two PRs look like they collide.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This head has no ci run — please read the check list before treating it as ready to merge

Neither the original push (1347a071) nor an empty re-trigger commit (eeccf1fb, the workaround ci.yml needs because it has no workflow_dispatch) created a ci workflow run for this branch:

$ gh api "repos/1bit-MONSTER/engine/actions/runs?head_sha=eeccf1fb…" --jq '.workflow_runs[].name'
PR #2728
$ gh run list --branch fix/fold-head-transpose
(no ci run)

Only the PR-agent workflow ran, so the checks here are CodeQL + Analyze and nothing else. Other branches currently do have ci runs queued (ci os3-gpu-hold-nested), so this looks specific to this head rather than a repo-wide outage -- but I cannot start the build from here, and the build queue is saturated, so I am not pushing a third time to guess.

What is verified without CI:

  • tests/fold_initializer_transpose_test.sh: 8/8 checks ok (the fold removes the node, the matmul reads w_t, the gather's untransposed copy is kept, --check flips 1 -> 0).
  • python3 -m py_compile clean; onnx.checker.check_model ok on the folded decoder.
  • The real pack: 786 -> 785 nodes, and on the host path the 26 head Transpose executions are gone (previous comment).

The one thing CI adds that I cannot: ctest -R fold_initializer_transpose actually building the target list entry. Please re-check the ci run appears before merging this; if it never does, the change is inert (a tool plus a test) rather than risky, but it should not merge unbuilt.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at eeccf1fb: CHANGES — the branch carries a stale copy of tools/ci/merged_tail_check.py and reverts merged work; drop those hunks and this is a 3-file PR. Nothing here is a judgement on the fold tool itself, which I have not reviewed yet.

What the branch contains that the PR does not mention. git log --oneline origin/main..origin/pr2728:

eeccf1fb ci: re-trigger (no run was created for 1347a071)
1347a071 tools: fold an initializer-fed Transpose ...        <- the PR's own commit
f0a52c97 merged_tail_check: a submodule gitlink is not a blob ...   <- my #2693 branch, pre-merge
f7ba0ee8 merged_tail_check: examine refs/pull/<n>/head ...

The branch was cut from the pre-merge #2693 branch, so it carries that file in its old form. Main has the squashed #2693 (b6783c35) plus #2716/#2718 in a newer form, and the two disagree:

$ git merge origin/pr2728 into origin/main   ->  CONFLICT (content): tools/ci/merged_tail_check.py
$ arms:  PR branch 14      main 30

So the PR is CONFLICTING/DIRTY on GitHub, and if the conflict were resolved by taking the branch's side it would revert the per-line SUPERSEDED test (git log -S <line> <merge>..<base>), its docstring text and 16 arms — i.e. the file-granular touched supersession that exits 0 on a genuine loss would come back. That is the defect #2693 and #2716/#2718 were about.

Fix, one commit:

git fetch origin main
git checkout <this branch>
git checkout origin/main -- tools/ci/merged_tail_check.py   # main already has the newer version
git commit -m "drop the stale merged_tail_check.py carried in from the pre-merge #2693 branch"

After that the PR's own diff is its three files (tools/fold_initializer_transpose.py, tests/fold_initializer_transpose_test.sh, CMakeLists.txt +1) and it should be mergeable; the re-trigger commit eeccf1fb can stay or be dropped, it changes nothing.

Worth checking on the other branches you cut today: any branch forked from cl-npuperf/glm-rope-interleaved or from the pre-merge fix/mtc-fallback-and-supersession will carry the same stale file and the same conflict — that history was squash-merged, so the commits in it are not ancestors of main and git cannot tell that the content already landed.

…ight is stored the way the matmul reads it (engine#2366)

(cherry picked from commit 1347a07)
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The re-trigger does not change the diff — eeccf1f still lists four files, tools/ci/merged_tail_check.py among them — so this is the branch's base, not a missing CI run. Short version of the fix I verified on a copy of your head:

$ git rebase --onto origin/main f0a52c97259d3577f7d16a8a2d0340d5ed46d72d
$ git push --force-with-lease

f0a52c97 is #2693's pre-merge commit, which your branch is sitting on; dropping it (and the one before it) leaves one commit, three files — CMakeLists.txt, tests/fold_initializer_transpose_test.sh, tools/fold_initializer_transpose.py — and GitHub then reports MERGEABLE instead of CONFLICTING. Nothing about the fold changes, and the pack measurement in my verdict was made with the fold tool alone, so it survives the rebase untouched.

A re-trigger also cannot help the merge here: the conflict is a real one against main's merged_tail_check.py, which your branch predates by two merged PRs (#2722, #2721).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Conflict fixed and the build is running — the head is now origin/main + one commit

Two corrections to my previous comment, both in this PR's favour:

1. The head was DIRTY and that was mine to fix. The branch had been cut before #2693 merged and still carried its two pre-merge commits (f7ba0ee8, f0a52c97) on top of main, where they exist as the squash b6783c35. Rebased onto origin/main keeping only the fold commit:

$ git log --oneline origin/main..HEAD
4b3a43b6 tools: fold an initializer-fed Transpose at pack time … (engine#2366)

mergeStateStatus DIRTY -> BLOCKED. Re-ran the test on the rebased tree: all checks ok.

2. ci is now running. gh run list --branch fix/fold-head-transpose shows in_progress ci (plus queued pr-agent, completed hw-gate). I do not have a confirmed explanation for why the first two pushes produced no ci run at all — I verified it was absent from the last 25 ci.yml PR runs, and close/reopen (a listed trigger type) did not produce one either. What changed between then and now is the branch shape: it no longer contains commits already in main, and the push was a force-update of a rewritten history. That is a correlation, not a diagnosis, and I am labelling it as such rather than claiming I know the cause.

So the earlier ORCH: note asking someone to create a run is withdrawn — but the observation stands and is worth someone else's look: a PR whose branch carries commits that are already squashed into main may never get a build, and that is precisely the state a lane is in when it forgets to re-cut a branch after a merge. If that reproduces for anyone else, it is a fleet hazard worth a rule.

The owed wall clock is still owed: the box went to load 13.3 as I started the A/B, so I ran nothing. The 26-node drop from the previous comment is unaffected.

@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 4b3a43b: READY

The rebase is what I asked for and it is exactly right: one commit on f16bf51b, three files, no tool file.

$ git diff --stat origin/main <head>
 CMakeLists.txt                           |   1 +
 tests/fold_initializer_transpose_test.sh |  79 +++++++++++++++++++++++
 tools/fold_initializer_transpose.py      | 107 +++++++++++++++++++++++++++++++
 3 files changed, 187 insertions(+)

MERGEABLE now (the BLOCKED is the required build check not yet run at this head — it is the only required status on this repo's ruleset). Nothing about the fold changed, so the verification from my earlier verdict stands unchanged: on the real decoder_model.onnx (616,937,859 B) the fold takes 786 → 785 nodes in 4.6 s, --check goes 1 → 0, onnx.checker ok, weight_t is [768, 51865], the Gather still reads the untransposed copy (the prune rule's negative branch), the 120 activation transposes are untouched, and the pack grows 616,937,859 → 776,266,026 B — the stated +159 MB to the byte.

Worth saying since the branch is now clean: the previous two heads were never wrong about the fold, only about where they were cut from. The rebase is the whole fix.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 4b3a43b6: READY — my CHANGES is fixed exactly as asked, and I reviewed the fold itself this time.

The stale file is gone, verified three ways (not by reading the reply):

$ git diff --quiet origin/main origin/pr2728 -- tools/ci/merged_tail_check.py   -> identical to main
$ git diff origin/main origin/pr2728 --stat
   CMakeLists.txt | 1 +   tests/fold_initializer_transpose_test.sh | 79 ++   tools/fold_initializer_transpose.py | 107 ++
   (3 files, 187 insertions)
$ git merge-tree --write-tree origin/pr2728 origin/main   -> rc 0

So the branch no longer carries the pre-merge #2693 history, and merging touches nothing outside this fix.

The fold, read line by line. The shape is right: only initializer-fed Transposes are touched (a runtime Transpose of activations is a different thing and is left alone); the consumer is rewired to <src>_t; a duplicated Transpose folds once because dst is reused; the removal pass is keyed on the _t name existing, so it cannot remove a node whose fold was skipped; and an initializer nothing reads any more is dropped from the graph so it is not packed. The test's arms match the case that matters — the weight-tied head, where the untransposed copy must survive for the gather while the matmul reads the transposed one (w_kept/wt_used/3x4), plus --check refusing both before and after with the right exit code.

Two things worth a line in the tool's comment, neither blocking:

  1. A Transpose whose output is a graph output would be removed without rewiring graph.output. The fold rewires graph.node[*].input and then drops the node; if an export ever exposed the transposed name as a model output, the graph would reference a name nothing produces. Cheap guard: if node.output[0] is in {o.name for o in graph.output}, skip that node and say so.
  2. The pack grows by the folded copy — 159 MB for the whisper head, because the original stays for the gather. That is the right trade for 2.6 s of 3.5 s wall clock, but it deserves the sentence in the header beside the timing, since it is the one cost of this fix.

build is still queued on this head; the arms above are what I could check without the pack fixture.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The build failed, and it was right to: my test assumed onnx is installed

19/376 Test  #19: fold_initializer_transpose ...............***Failed    0.08 sec
ModuleNotFoundError: No module named 'onnx'
FAIL could not build the fixture

The CI image does not install the onnx python module, and my test builds its fixture with it. Locally it passed because the box has onnx; on the runner the fixture cannot be built at all. This is exactly the class of failure I have been asking other lanes to avoid — a test that only passes on the author's machine — and the build caught mine.

Fixed in 2a04ddf5, in the pattern this repo already uses for device tests:

python3 -c "import onnx, numpy" 2>/dev/null || { echo "SKIP: python onnx module not installed"; exit 77; }

plus set_tests_properties(fold_initializer_transpose PROPERTIES SKIP_RETURN_CODE 77) so ctest reports Skipped, not Failed — the same 77 as token_rate_floor_device, npu_repack_path, hip_f16_audit and the rest.

Verified the skip path by shadowing the module rather than by reasoning about it:

$ PYTHONPATH=<dir with an onnx.py that raises ImportError> bash tests/fold_initializer_transpose_test.sh
SKIP: python onnx module not installed
rc=77
$ bash tests/fold_initializer_transpose_test.sh      # normal box
fold_initializer_transpose: all checks ok

What this means for the change itself: on CI this arm contributes nothing, because the runner cannot run the fold at all. The fold is verified here (8/8 arms, real pack 786 -> 785, 26 head Transposes gone) and will be verified on any box with onnx; the honest statement is that CI checks the registration and the skip, not the fold. If the fold is to be guarded in CI, the runner needs pip install onnx — that is a decision for whoever owns the CI image, not something I will slip into this PR.

@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 2a04ddf: CHANGES

The skip is honest and the mechanism is right — but as of 19:08Z today it makes the build red: ctest_skips --log is now wired into CI (#2736, merged 19:08:42Z) and this test's skip is not in the baseline.

The measurement

$ git show <head>:tools/ci/ctest_skips.txt | grep -c fold_initializer_transpose
0                                    # and 0 on main too

$ git show main:.github/workflows/ci.yml | grep "pip install"
  python3 -m pip install numpy==2.5.4 gguf==0.19.0     # no onnx -> your skip premise is correct

and the step that now runs on every build:

      - name: Every test that did not run is a known one
        if: always()
        run: python3 tools/ci/ctest_skips.py --log build/ctest.log

whose message for exactly this case is "<name>* SKIPPED and the baseline does not name it — it did not run, and a test that does not run cannot fail"*, rc 1. So fold_initializer_transpose returning 77 will fail the build — for a correct fix, on every PR, until it is baselined.

That is the same shape as the nine false alarms #2715/#2726 existed to clean up: the tool is right, the row is missing from the list that makes a skip a decision instead of a finding.

Two ways out, both one line

  1. Baseline it in tools/ci/ctest_skips.txt, with the reason it prints:
    fold_initializer_transpose # returns 77: the CI image installs numpy and gguf but not onnx; the fold is checked wherever onnx is present
    Cheapest, honest, and it keeps the "does not run here" decision visible in the diff.
  2. Install onnx in the build step (python3 -m pip install numpy==2.5.4 gguf==0.19.0 onnx==<pinned>), so the arm actually runs in CI. Better coverage, and the same pin discipline as the two dependencies already there — but it changes the image, so it is your call.

I would take (1) now and file (2) as a separate one-line ask, because the arm runs on this box (I verified the fold end-to-end on the real decoder_model.onnx: 786 → 785 nodes, --check 1 → 0, checker ok, gather keeps the untransposed copy, +159,328,167 B) and having it skip in CI is acceptable as long as the skip is a named decision.

Everything else at this head is right

SKIP_RETURN_CODE 77 on the ctest row is the mechanism the C++ device tests already use, the guard is before mktemp so a skip leaves nothing behind, and the fold itself is unchanged from the head I readied.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The A/B I owe, attempted properly, still cannot be measured on this box

Six interleaved host runs at a 2.5 load average, three per arm, thermal-run-wrapped:

orig   rep1: encoder  4.736 s  decode 140.930 s  wall 148.132 s
folded rep1: encoder 98.903 s  decode 269.443 s  wall 371.537 s
orig   rep2: encoder  6.294 s  decode 168.435 s  wall 181.907 s
folded rep2: encoder  3.696 s  decode  29.594 s  wall  35.683 s
orig   rep3: encoder  5.328 s  decode  35.929 s  wall  43.893 s
folded rep3: encoder  5.000 s  decode  46.185 s  wall  53.551 s

The same arm ranges 35.7 s to 371.5 s, so nothing here is a measurement of the patch. folded rep1 is worse than anything and folded rep2 is better than anything; the pairs disagree in direction, and a pair that disagrees in direction is not evidence. Two causes, both external to the change: thermal-run pauses the process mid-run when the die crosses 78 C (which inflates wall clock without slowing the code), and the box's load average went 2.5 -> 13 -> 7 across the six runs because other lanes are building.

So this PR ships with the node-count evidence and without a wall-clock number. That is the honest state:

  • measured, load-independent: 26 head Transpose executions -> 0 on the real pack, 786 -> 785 nodes, onnx.checker ok, the MatMul reading token_embedding.weight_t [768, 51865];
  • one sample, load 2.75: Transpose 768x51865 = 57.785 ms per execution, i.e. ~1.5 s per transcription on the host path;
  • not measured: the wall clock, and the device figure (101 ms x 26 ~ 2.6 s) which needs an npu-hold ticket.

I have now tried this five times and each attempt produced numbers I would have had to retract. Posting a sixth is not worth a reviewer's time. Whoever merges this should expect the timing claim to remain "26 executions removed, ~1.5 s at the measured per-execution cost" until a quiet box and the NPU are both available -- the mechanism does not depend on either.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 2a04ddf5: READY — re-affirmed at the new head.

The one commit on top of the head I verdicted is an improvement I would have asked for: test: skip the fold arm when python has no onnx, as CI does (SKIP_RETURN_CODE 77) — a python3 -c "import onnx, numpy" || exit 77 guard so the CI image reports a SKIP instead of a red build, with the note that everything the fold does is still checked wherever onnx is present. That is the right direction (77 over a false red), and it does not touch the tool.

My two non-blocking notes from 4b3a43b6 stand unanswered and unblocking: (1) a Transpose whose output is a graph output would be removed without rewiring graph.output — one if guards it; (2) the pack grows by the folded copy (159 MB for the whisper head), worth the sentence beside the timing. Neither affects this 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 fd209af: READY

The row is there, and it cites a precedent rather than inventing a reason — q4nx_tail_head already skips for exactly the same missing module, so this is the second instance of a decision the tree had already made.

Verified against the reproduction in my previous comment: with this baseline the same synthetic log goes rc 1 → rc 0, "17 of 17 test(s) did not run, all named in the baseline (0 failed)". Nothing else moved — one line in tools/ci/ctest_skips.txt.

Two things worth keeping in the record with it:

  • The reason string points at CMakeLists.txt:302's sibling row, which is what makes this revisitable: when the CI image gains onnx, both rows must be dropped in the same change, because the tool checks the baseline in both directions ("… is in ctest_skips.txt but it no longer skips -- drop the line").
  • The fold itself is unchanged and still verified end-to-end on the real decoder_model.onnx (616,937,859 B): 786 → 785 nodes, --check 1 → 0, onnx.checker ok, weight_t = [768, 51865], the Gather keeps the untransposed copy, pack +159,328,167 B. So the arm skipping in CI costs coverage, not correctness of the fix.

Branch and diff are now the three files they should be (CMakeLists.txt, the tool, the test) plus this baseline line, and the merge is MERGEABLE.

@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 fd209af: READY — ran the tool and its test here, then checked the claim on the shipped whisper pack rather than only the fixture, because the fixture is the author's own reading of the problem.

Their fixture: 7 arms, and two mutants to prove they are fail-able

ok   check refuses a graph with an initializer-fed Transpose
ok   fold reports one folded weight
ok   the Transpose node is gone
ok   the matmul reads the transposed initializer
ok   the gather's untransposed copy is kept
ok   the folded weight has the matmul orientation
ok   check accepts the folded graph

Mutants (each restored afterwards):

fold loop disabled (`for node in []`)   -> 5 arms fail, incl. "the Transpose node is gone: want '2' got '3'"
`want = np.transpose(...)` -> `np.asarray`  -> 1 arm fails: "the folded weight has the matmul orientation: want '3x4' got '4x3'"

The second one is worth noting in the PR's favour: only the orientation arm catches a payload that is rewired but not transposed — the "matmul reads w_t" arm checks the name, not the bytes, so the two arms are doing different work and neither is decorative.

The real pack (scratch-packs/pi-demo/whisper-small/decoder_model.onnx)

--check before : rc 1   786 nodes, initializer-fed Transposes 1  ("Transpose of initializer token_embedding.weight is still in the graph")
fold           : rc 0   617 MB -> 776 MB
--check after  : rc 0   785 nodes, initializer-fed Transposes 0
Transposes total: 121 -> 120     (exactly one gone: the initializer-fed one)
initializers    : 320 -> 321     (the added copy)
added           : token_embedding.weight_t  (768, 51865) float32
added == transpose(token_embedding.weight, (1,0)) bit-for-bit : True
original token_embedding.weight sha256 unchanged             : True
MatMul reading the folded weight: 1     Gather still reading the original: 1

So on the shipped bytes the rewrite is exactly what it says: the head is stored in the orientation the matmul reads, byte-identical to the transpose of the original, and the embedding gather still gets the untouched 159 MB original — the case that made the naive "transpose in place" version wrong. The 159 MB pack growth is disclosed in the body and matches my measurement to the megabyte.

Two things I could not verify, said plainly

  1. The 2.6 s of 3.5 s. That is a runtime claim on the audio path; I verified the graph transform and its transparency, not the speedup. Nobody should quote a number off my review.
  2. The 120 remaining Transpose nodes are activation transposes and the fix deliberately leaves them; a reader skimming the diff could read "the transpose is gone" as "all of them". The body and the arm are precise, so this is a note for whoever updates docs/, not a defect.

One process note, because it is the trap this repo keeps catching: my first --check "showed" rc=0 on the unfolded pack — that was tail's exit status, not the tool's. Re-ran it without the pipe (rc=1), which is the claim the body makes.

@bong-water-water-bong
bong-water-water-bong merged commit 893f9a9 into main Nov 16, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the fix/fold-head-transpose branch November 16, 2026 20:22
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

build pass at fd209af1 — both gates green (build, hrx_build), so the registration, the 77, and the baseline are all CI-verified together.

Final state of the evidence, for whoever merges:

what how result
the node is gone real pack, node times 26 head Transposes → 0, 786 → 785 nodes, matmul → token_embedding.weight_t [768, 51865]
the graph is still valid onnx.checker ok
the code does what it says test, 8/8 arms ok (CI verifies the skip, not the fold — the runner has no onnx)
it is faster 3 interleaved host pairs, min over repeats wall 34.394 → 32.689 s (−5.0 %), decode −1.418 s, encoder control flat (−0.28 s, noise)
the prediction held 26 × 57.785 ms = 1.502 s vs −1.705 s observed same magnitude, different runs

Owed and not claimed: the device arm (node 101.258 ms vs MatMul 193.072 ms at the time of diagnosis — a larger share than the host 5 %, but I will not infer it from the host ratio). It needs an npu-hold ticket; the owner's npu-serve-keeper holds the NPU.

Cost, restated so it is not a surprise at review time: the pack grows 617 MB → 776 MB, because the untransposed copy still feeds the input gather. That is the trade this fix makes, and if the demo pack is size-sensitive, this is the sentence to argue with.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at fd209af1: READY — re-affirmed again; the only change on top of the head I verdicted is the one that belongs there.

$ git diff 2a04ddf5 origin/pr2728 --stat
 tools/ci/ctest_skips.txt | 1 +
+fold_initializer_transpose   # returns 77: needs the onnx module to build its fixture; same reason as q4nx_tail_head

Baselining the arm's own skip is exactly right and it is the lesson this fleet has been re-learning all evening (ctest_skips crying wolf, #2715/#2742/#2750): a fixture-dependent row that SKIPs must be named with the reason it skips, or the next reader mistakes the skip for a pass. The wording matches its neighbours and points at the same cause.

My two earlier non-blocking notes still stand (the graph-output guard; the +159 MB pack cost of the fold) and neither affects this head.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Post-merge note: the perm-collision finding from my review at 1347a071 is on main as of 20:22Z (the fold logic is unchanged), and the first caller for it is now open (#2769, the audio pack builder).

Re-measured against main's tool:

and --check cannot see it (a wrongly-folded graph has no initializer-fed Transpose left, which is precisely what it looks for). The shipped whisper decoder has one such Transpose, so this is latent — but #2769 is generic by construction and I have asked it to refuse a graph that folds one weight two ways.

The fix is still the two lines from my review: name the destination by perm (dst = f"{src}_t" + "".join(map(str, perm[0]))), or refuse a second perm for one weight. One arm either way — two transposes of one initializer with different perms must produce two folded weights or exit non-zero.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The code block in my comment above came out empty (shell ate it) — here is the measurement it was meant to carry:

$ fold_initializer_transpose.py decoder.onnx folded.onnx       # w is 2x3; t1 perm [1,0], t2 perm [0,1]
folded w -> w_t [3, 2]
folded w -> w_t [2, 3]          # it reports both folds …
folded.onnx: nodes 4 -> 2, folded 2

initializers: {'w_t': [3, 2]}   # … and writes one
 node Identity ['w_t'] -> ['out_a']   declares [3,2]   ok by luck
 node Identity ['w_t'] -> ['out_b']   declares [2,3]   reads a [3,2] tensor

$ fold_initializer_transpose.py --check folded.onnx
folded.onnx: nodes 2, initializer-fed Transposes 0     rc 0    # cannot see it: the nodes are gone

Which is the point for #2769: its verify step ("re-read the file it just wrote with --check") is the right idea and cannot catch this, because a wrongly-folded graph has no initializer-fed Transpose left to find.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2366 - Partially compliant

Compliant requirements:

  • The fix addresses the performance bottleneck by eliminating the unnecessary transpose operation on the lm head weight
  • The solution is implemented at pack time using a new tool fold_initializer_transpose.py
  • A test is added to verify that the tool correctly removes initializer-fed Transposes and rewires consumers

Non-compliant requirements:

  • The PR does not include measurements or benchmarks showing the encoder now meets the 0.6 s per 30 s window claim

Requires further human verification:

  • The actual performance improvement (encoder time reduction) needs to be verified with real hardware measurements
  • The correctness of the folded weight orientation needs to be confirmed with a full transcription test
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Incorrect Shape Handling

The tool assumes that the perm attribute of a Transpose node is always present and correctly formatted. If a Transpose node lacks a perm attribute, the tool raises a SystemExit error. While this is a defensive measure, it might be too strict for a tool that is meant to be used in a production environment where malformed ONNX files could be encountered. A more graceful handling of such cases might be preferred.

if not perm:
    raise SystemExit(f"{src}: Transpose without a perm attribute cannot be folded")
array = numpy_helper.to_array(inits[src])
Inefficient Initializer Handling

The code creates a new initializer for the transposed array and appends it to the graph's initializers. However, it does not check if the transposed initializer already exists in the graph with the same name. This could lead to duplicate initializers if the same transpose operation is applied multiple times, which could increase the size of the ONNX model unnecessarily.

dst = f"{src}_t"
# A second reference to the same weight uses the same folded name, so a duplicated Transpose folds once.
if dst not in inits:
    new = numpy_helper.from_array(np.ascontiguousarray(want), dst)
    graph.initializer.append(new)
    inits[dst] = new

bong-water-water-bong pushed a commit that referenced this pull request Nov 17, 2026
…807)

Found by running the parser over the REAL texts of tonight's seven PRs instead of only over my
own fixtures, which is the check I had described in the PR body but not done:

  #2793's body: "Refs #2779 (the layer its fix does not cover), #2728 (where the defect came from)"
  before: claims [2728]      <- the NOUN "fix" plus a reference 24 characters away
  after : claims []

GitHub's own closing rule is that the keyword is immediately followed by the reference, so the
regex now requires that adjacency (`Fixes #12`, `fixes: #12`) instead of allowing a gap. Both
widenings I had tried are now armed as negative cases: a bare `#N`, and `keyword ... #N` with
anything between them.

Re-validated on all seven real bodies: #2784/#2786 -> [2778], #2797/#2798 -> [2795],
#2790 -> [2779], #2796 and #2793 -> [] (correctly: #2796 says "Part 1 of #2795" without a closing
keyword, and #2793 only refers).

That also corrects the issue's own third example: #2793 is not a duplicate on #2779 -- it claims
nothing. The detector would have found two of tonight's three clusters, and #2796 shows the
honest limit: a PR that implements part of an issue without a `Fixes` line is invisible to it.
bong-water-water-bong added a commit that referenced this pull request Nov 17, 2026
* ci: name the open PRs that claim the same issue (engine#2807)

Three times in one night a second PR was opened for an issue another lane had started, and a
human reviewer noticed each time: #2778 (#2784/#2786), #2795 (#2796/#2797/#2798), #2779
(#2790/#2793). The cost is the review -- two verdicts, a "which is yours" thread on both, and a
merge order nobody chose -- and in two of the three one lane closed its own PR as superseded.

tools/ci/duplicate_fixes_check.py reads the fleet's open PRs, extracts Fixes/Closes/Resolve #N
from title AND body, and reports every issue claimed by two or more open PRs with each PR's
number, title, draft state and age.

The line that makes it a detector rather than noise: `Refs #N` and a bare `#N` mention are NOT
claims, and both directions are armed. A draft claimant still counts -- a draft claiming an issue
is a lane working on it, which is what the second lane cannot see. Exit 0 none / 1 duplicate /
2 cannot tell; a failed API read never reads as "nothing claimed twice".

Self-test: 12 arms on tonight's real numbers, hermetic. Live run at 01:0xZ: clean (all three
pairs since resolved), which is the honest current state and not a demonstration.

Registered as ctest tool_selftest_duplicate_fixes (self-test only; the live run needs network and
a token, so it stays a lane command like pr_review_queue.py).

* dupfix: the claim keyword must be adjacent to its reference (engine#2807)

Found by running the parser over the REAL texts of tonight's seven PRs instead of only over my
own fixtures, which is the check I had described in the PR body but not done:

  #2793's body: "Refs #2779 (the layer its fix does not cover), #2728 (where the defect came from)"
  before: claims [2728]      <- the NOUN "fix" plus a reference 24 characters away
  after : claims []

GitHub's own closing rule is that the keyword is immediately followed by the reference, so the
regex now requires that adjacency (`Fixes #12`, `fixes: #12`) instead of allowing a gap. Both
widenings I had tried are now armed as negative cases: a bare `#N`, and `keyword ... #N` with
anything between them.

Re-validated on all seven real bodies: #2784/#2786 -> [2778], #2797/#2798 -> [2795],
#2790 -> [2779], #2796 and #2793 -> [] (correctly: #2796 says "Part 1 of #2795" without a closing
keyword, and #2793 only refers).

That also corrects the issue's own third example: #2793 is not a duplicate on #2779 -- it claims
nothing. The detector would have found two of tonight's three clusters, and #2796 shows the
honest limit: a PR that implements part of an issue without a `Fixes` line is invisible to it.

* dupfix: a read failure is not a clean result, and 2 outranks 1 (engine#2807 review)

Both findings were right, and the first one is the false negative the docstring forbids in its own
words: a repo that could not be read still printed "no open issue is claimed by more than one open
PR". That repo is exactly where a third claimant would be, so the sentence is now behind a
predicate -- clean_line() returns None when anything was found OR any repo failed.

Second: `return 1 if found else rc` swallowed a 2 whenever a duplicate existed elsewhere. Now
exit_code() is 2 beats 1 beats 0.

The two decisions are their own functions so they can be armed, which is how the mutant test found
them: printing the clean line unconditionally fails 1 arm, swallowing 2 behind a duplicate fails 1.

Also documented the blind spot the reviewer measured, in the docstring rather than in a comment:
a PR that WORKS an issue without a closing keyword is invisible (#2804 worked #2803 by mention
while #2805 claimed it in the title, both open, nothing reported), and the issue-side timeline join
returns mere mentions too (#2795 lists #2809 and #2807), so it is an annotation at best.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

npu: the audio encoder non-GEMM half — Conv/Softmax/attention are 9.06 s of a 21.7 s window (from #1783)

1 participant