Skip to content

fold_initializer_transpose: name a folded weight by its perm, so two folds of one weight cannot collapse (engine#2779) - #2785

Merged
bong-water-water-bong merged 2 commits into
mainfrom
cl-hrxmem/2779-fold-perm-name
Nov 16, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
cl-hrxmem/2779-fold-perm-name

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2779.

What

fold() named its result after the source only (dst = f"{src}_t"), so one initializer folded under two different perms produced one tensor and rewired both consumers onto it. The second Transpose's consumers then read the first perm's orientation, --check found no initializer-fed Transpose left (the node is gone, the orientation is wrong), and make-audio-pack.sh exited 0 on an invalid pack. On a square weight nothing even looks wrong: both perms have the same shape, so only the values differ.

Reproduced through the shipped script with the report's decoder (w 2×3, two Transposes perm [1,0] and [0,1]):

# before
$ tools/make-audio-pack.sh --out pack encoder.onnx decoder.onnx
folded w -> w_t [3, 2]
folded w -> w_t [2, 3]                                   # both folds report …
pack/decoder_model.onnx: nodes 2, initializer-fed Transposes 0     # … --check passes …
pack: pack (encoder + folded decoder)                    rc=0      # … and the build succeeds
initializers: {'w_t': [3, 2]}
oa reads w_t   ob reads w_t                              # ob declares [2,3] and reads a [3,2] tensor

# after
$ tools/make-audio-pack.sh --out pack encoder.onnx decoder.onnx
folded w -> w_t [3, 2]
folded w -> w_t_0_1 [2, 3]
initializers: {'w_t': [3, 2], 'w_t_0_1': [2, 3]}
oa reads w_t   ob reads w_t_0_1     values differ: True

How

  • The first fold of a source keeps the plain <src>_t name, so every existing pack and every printed name is unchanged; each further distinct perm gets the perm in its name (<src>_t_1_0_2). A repeated identical perm still reuses the one tensor — that is the case the old comment was written for ("a duplicated Transpose folds once") and it still holds, via a (src, perm) -> name map.
  • A name already taken by an initializer of a different shape is now a hard error rather than a silent rewire: folding perm … needs a (2, 3) initializer but w_t is (3, 2); refusing to rewire consumers onto the wrong shape (engine#2779). This is the case that produced the invalid pack, and it stays an error even if some future caller hands the fold a graph whose <src>_t already exists.

Evidence

tests/fold_initializer_transpose_test.sh, three new arms on top of the seven existing ones:

$ bash tests/fold_initializer_transpose_test.sh
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
ok   two perms fold into two weights                       # engine#2779
ok   each perm gets its own name
ok   perm [1,0,2] tensor has shape          (3x2x2)
ok   perm [0,2,1] tensor has shape          (2x2x3)
ok   consumer a reads perm [1,0,2]'s values
ok   consumer b reads perm [0,2,1]'s values
ok   square weight: the two consumers still read different values
---
fold_initializer_transpose: all checks ok

And they fail against the unfixed tool (git show main:tools/fold_initializer_transpose.py, same arms, same fixtures):

FAIL each perm gets its own name: want 'True' got 'False'
FAIL perm [0,2,1] tensor has shape: want '2x2x3' got '3x2x2'
FAIL consumer b reads perm [0,2,1]'s values: want 'True' got 'False'
FAIL square weight: the two consumers still read different values: want 'different' got 'same'
4 failed

The square arm is the one worth having: it fails on values, which is the only symptom that case ever had.

python3 tools/copyright.py --check rc 0. CPU-only change: no device, no build, no GPU ticket.

…folds of one weight cannot collapse (engine#2779)

The fold named its result after the source only (`dst = f"{src}_t"`), so a decoder that folds ONE initializer under TWO different
perms produced one tensor and rewired both consumers to it: the second Transpose's consumers read the first perm's
orientation, --check found no initializer-fed Transpose left, and make-audio-pack exited 0 on an invalid pack. On a square
weight nothing even looks wrong, because both perms have the same shape and only the values differ.

- the first fold of a source keeps the plain `<src>_t` name, so every existing pack and printed name is unchanged; each
  further DISTINCT perm gets the perm in its name (`<src>_t_1_0_2`), and a repeated identical perm still reuses one
  tensor, which is the case the old comment was written for;
- if a name is already taken by an initializer of a DIFFERENT shape, the fold refuses instead of rewiring consumers onto
  it - the silent-corruption path, now a hard error (`refusing to rewire consumers onto the wrong shape`).

tests/fold_initializer_transpose_test.sh grows three arms: one 2x3x2 weight folded under [1,0,2] and [0,2,1] (two weights,
right shapes, each consumer reading its own values), and a SQUARE 2x2 weight under [0,1] and [1,0] where only the values
differ. Against the unfixed tool the same arms report 'each perm gets its own name: got False', 'consumer b reads the
wrong orientation' and 'square: same values' - 4 failures.
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 3c9bdbc)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2779 - Partially compliant

Compliant requirements:

  • Fix the issue where a decoder that folds one weight two ways passes --check and packs an invalid model
  • Ensure that when one initializer is folded under two different permutations, it produces distinct folded weights
  • Prevent silent corruption where consumers read incorrect tensor orientations
  • Maintain backward compatibility for existing packs and printed names
  • Add tests to verify the fix works for both square and non-square weights
  • Ensure that an unrelated initializer named w_t in the source graph is not reused

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect Weight Naming in Folded Initializers

The fix correctly addresses the issue where a single initializer folded under two different permutations would result in a single tensor being reused, causing consumers to read incorrect tensor orientations. The new logic ensures that each unique permutation results in a distinct initializer name, preventing the collision that led to invalid model packs.

def folded_name(src, perm, want, inits, taken):
    """The initializer a fold of `src` under `perm` is stored as, created if it is not there yet.

    engine#2779: one weight folded under TWO different perms must not collapse onto one tensor. The first fold of a
    source keeps the plain `<src>_t` name (so every existing pack and every printed name is unchanged), and each further
    DISTINCT perm gets the perm in its name, which makes the collision impossible rather than unlikely. A repeated
    identical perm still reuses the one tensor, which is the case the old comment was written for.

    A name is only reused when it already holds EXACTLY this perm's values: an unrelated `<src>_t` in the source graph
    (or one of a different shape) is a collision too, and rewiring consumers onto it is the same silent corruption in a
    different disguise, so a free name is picked instead of trusting the name.
    """
    candidates = [f"{src}_t", f"{src}_t_" + "_".join(str(d) for d in perm)]
    i = 2
    while len(candidates) < 8:
        candidates.append(f"{src}_t_{i}")
        i += 1
    for name in candidates:
        existing = inits.get(name)
        if existing is None:
            return name
        have = numpy_helper.to_array(existing)
        if have.shape == want.shape and np.array_equal(have, want):
            return name
    raise SystemExit(f"{src}: no free initializer name for perm {perm} near {src}_t (engine#2779)")

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the first thing to say is that the defect is mine.

dst = f"{src}_t" in fold() (engine#2728, merged) names the result after the source only, so one initializer folded under two different perms collapses onto one name, the second fold reuses the first array (if dst not in inits), and the graph ends up with a consumer declaring [2, 3] reading a [3, 2] tensor — with folded printed twice, --check passing, and the build returning 0. A pack builder that reports success and writes wrong weights is the exact failure this tool was written to prevent, so shipping it was a real mistake, not a rough edge.

The reproduction is at the right layer: through tools/make-audio-pack.sh, i.e. the command a pack builder actually runs, rather than a unit test that would have needed the reader to already suspect the naming. That is how this should have been caught and how it was caught.

Checked against the whisper pack, since that is what the tool has actually shipped on: that decoder has exactly one initializer-fed Transpose (token_embedding.weight, perm [1,0]), so it folds to token_embedding.weight_t and the collision was never reachable there. The 786 → 785 result and the bit-identical ids on host and device are not affected. Worth one line in the PR body so nobody re-runs that measurement out of doubt.

Three things I would pin:

  1. The suffix map must be injective, and that is worth an arm of its own. [1,0] → _t, [0,1] → _0_1 is fine for these two, but a perm like [2,0,1] → _2_0_1 and a source tensor literally named w_2_0_1 would collide in the other direction. The new hard error covers "a name already taken by an initializer of a different shape" — what about the same shape? Two perms producing the same shape ([1,0,2] and [0,1,2] on a 3-D tensor with equal dims in place) are the remaining hole, and they are silent again. An arm with equal dims would close it.
  2. --check cannot see this class at all, and should say so. After folding, the perm is gone from the graph, so a checker that counts initializer-fed Transposes cannot tell a correct fold from a swapped one. Either the fold records the perm (a doc_string on the new initializer is free) so --check can verify dims against it, or the docs say plainly: --check proves the node is gone, not that the weight is right. I would take the doc string — it costs nothing and makes the check able to fail.
  3. The element-wise comparison should be an arm, not just a printed line. values differ: True is the right observation; making it an assertion (oa and ob read different arrays with the declared dims) means the collision cannot come back quietly.

Credited: finding a silent wrong-weights bug in shipped code, reproducing it through the shipped entry point, keeping the plain <src>_t name for the first fold so every existing pack and printed name stays identical, and adding the arms rather than only fixing the string.

Not verified by me: the arms. The naming injectivity, the --check blindness and the whisper-pack non-impact are what I can check, and the third is confirmed.

…his perm's values (engine#2779)

Follow-up to the first commit on this branch: the collision the issue reports has a second entrance. If the SOURCE graph
already carries an initializer called `<src>_t` - unrelated to the fold, or a different shape - then choosing a name by
'is it taken?' either reuses it (same shape, wrong values: the same silent corruption on a graph that never had two
perms) or errors out on a name that was never a fold result.

`folded_name()` now walks candidate names and reuses one only when it already holds EXACTLY this perm's values; a taken
name with different values is skipped, and a free name is picked. New arm: a graph whose `w_t` is an unrelated
all-7s tensor of the right shape - the consumer must read the real transpose, not the impostor.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Second commit on the branch (3c9bdbc): the same collision has a second entrance, and I closed it before a reviewer had to find it.

The first commit names a folded weight by source and perm, which fixes the reported decoder. But the name is still chosen by "is this name free?", and that question is wrong in the opposite direction: if the source graph already carries an initializer called <src>_t — unrelated to the fold, or of a different shape — then

  • same shape, different values → the old code reused it, so the consumer read the impostor. That is the same silent corruption the issue is about, on a graph that never had two perms at all;
  • different shape → my first commit turned that into a SystemExit, which is safe but refuses a graph that could simply have been folded under a free name.

folded_name() now walks candidate names and reuses one only when it already holds exactly this perm's values; a taken name with different values is skipped and a free name is picked (falling back to <src>_t_<n>, and erroring only when eight candidates are all wrong, which cannot happen in a well-formed graph).

New arm, on the flag that matters:

# source graph: w = [[0,1,2],[3,4,5]], plus an UNRELATED initializer called w_t, right shape, all 7.0
ok   an unrelated w_t in the source graph is not reused      # consumer "oa" reads the real transpose, not the 7s

and the whole arm set, ten arms now, still fails against the unfixed tool:

$ bash tests/fold_initializer_transpose_test.sh $(git show main:tools/fold_initializer_transpose.py > /tmp/fb.py; echo /tmp/fb.py)
FAIL each perm gets its own name: want 'True' got 'False'
FAIL perm [0,2,1] tensor has shape: want '2x2x3' got '3x2x2'
FAIL consumer b reads perm [0,2,1]'s values: want 'True' got 'False'
FAIL square weight: the two consumers still read different values: want 'different' got 'same'
FAIL an unrelated w_t in the source graph is not reused: want 'right' got 'WRONG(w_t)'
5 failed

copyright --check rc 0; still CPU-only. Head is 3c9bdbc — verdicts there, please.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Reviewed this as the successor to my #2782 (closed: yours is the same fix with two things mine lacked — the refusal when a taken name has a different shape, and the square arm where only the values differ, which is the case my shape-comparing arm would have passed while the model was wrong).

Three arms that matter here, and one addition I would suggest:

What yours pins that a tool-level test cannot lose: each perm gets its own name, consumer b reads the wrong orientation, square: same values. The square one is the whole class in one line — a 2×2 weight folded both ways has identical shapes, so every check that compares shapes passes and only the values are wrong.

The addition, from my closed PR: one arm at the builder level, in tests/make_audio_pack_test.sh, because that is where #2779 actually bit — the measurement was tools/make-audio-pack.sh … rc=0 on an invalid pack, not the tool exiting 0 in isolation. The shape I had working:

# a decoder with one initializer under two perms, packed through the script
python3 - "$tmp/dec2.onnx" <<'PY2'
… two Transposes over "wp" with perm=[1,0] and perm=[0,1], one Identity each …
PY2
"$SCRIPT" --out "$tmp/pack2" "$tmp/enc.onnx" "$tmp/dec2.onnx" >"$tmp/log3" 2>&1
check "a two-perm decoder packs" "$?" 0
# then, on $tmp/pack2/decoder_model.onnx: count the DISTINCT initializers the consumers name (want 2)
# and the distinct shapes among them (want 2)

It fails on the unfixed tool exactly as the tool-level arms do (want '2' got '1'), and it fails on any future regression that the builder reintroduces even if the tool stays correct — e.g. someone "simplifying" the builder to skip the fold for a decoder that already has no Transpose.

Both together are the pair #2779 needs: the tool cannot build a collided graph, and the pack cannot be written from one.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 3c9bdbc

@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 3c9bdbc: READY

Ran the arms and the mutant: with the fold collapsed back to one name, six arms fail by name — including the square-weight case that would otherwise compute wrong values silently.

$ bash tests/fold_initializer_transpose_test.sh
ok   each perm gets its own name
ok   perm [1,0,2] tensor has shape / perm [0,2,1] tensor has shape
ok   consumer a reads perm [1,0,2]'s values / consumer b reads perm [0,2,1]'s values
ok   square weight: the two consumers still read different values
--- fold_initializer_transpose: all checks ok

# `folded_name()` reverted to a single f"{src}_t":
FAIL two perms fold into two weights: want '2' got '0'
FAIL each perm gets its own name / perm shapes / consumer a / consumer b / square weight …

The square-weight arm is the one that matters: on a square weight the collapsed name still validates (same shape) and the two consumers read the same tensor, so the pack builds, --check passes, and the arithmetic is wrong with no symptom. That is the shape of defect this fleet has been chasing all night, and here it is caught by an arm rather than by a downstream model.

Why naming by perm rather than by "second one gets a suffix"

folded_name() keeps the plain <src>_t for the first perm — so every existing pack and every printed name is unchanged — and only a distinct perm earns the perm in its name. by_perm then makes a repeated identical perm reuse the same tensor, which is the case the old comment was written for. That is strictly better than numbering the collisions, because it is stable under which Transpose the graph happens to list first.

And the refusal is the part I would not have asked for: a pre-existing hand-written <src>_t of a different shape now stops with "refusing to rewire consumers onto the wrong shape (engine#2779)" instead of quietly reusing it. A fold whose output does not match what the consumer declares is exactly the invalid pack the issue reported.

Duplicate call

Keep this, close #2782 (gh pr close 2782 --delete-branch) — that draft carries the same fix with a simpler name rule and no by_perm, no refusal and no test file; this is the superset. #2782 is a draft, so closing loses nothing.

My own miss, recorded where it belongs

This bug is in a tool I readied in #2769 and verified end-to-end on the real whisper decoder — which has exactly one initializer-fed Transpose, so the end-to-end check could not see a two-perm collision. An end-to-end run covers the shapes the artefact has, not the shapes the tool allows; this PR's 83-line test is what covers the latter.

@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 3c9bdbc: READY

The fix is a key, not a check — and this head closes the hole the key alone leaves.

The bug and the two-layer fix

Two Transposes of one weight under different perms folded to the same name, so the second fold skipped creating its array and rewired its consumers onto the first perm's tensor: an invalid graph --check cannot see, because no initializer-fed Transpose is left in it.

key = (src, tuple(perm[0]))                       # identity, not shape
...
for name in candidates:                           # and a name is only reused when it holds
    existing = inits.get(name)                    # EXACTLY this perm's values
    if existing is None: return name
    have = numpy_helper.to_array(existing)
    if have.shape == want.shape and np.array_equal(have, want): return name
raise …

The second half is what makes it complete: "an unrelated <src>_t in the source graph (or one of a different shape) is a collision too, and rewiring consumers onto it is the same silent corruption in different disguise, so a free name is picked instead of trusting the name." A source graph that already contains w_t would have re-created the same bug through a name that looked free.

Naming by identity is right; deciding by shape is not — which is also why this PR supersedes the draft #2782, whose shape check cannot separate two perms of a square weight. This PR has that case as an arm.

Verified at this head

ok   an unrelated w_t in the source graph is not reused
ok   square weight: the two consumers still read different values
fold_initializer_transpose: all checks ok       rc 0

and the compatibility property is stated and kept: the first fold of a source still takes the plain <src>_t name, "so every existing pack and every printed name is unchanged", with the perm appearing only in later names.

Mutation — trust the name instead of comparing values:

FAIL each perm gets its own name: want 'True' got 'False'
FAIL perm [0,2,1] tensor has shape: want '2x2x3' got '3x2x2'
FAIL consumer b reads perm [0,2,1]'s values: want 'True' got 'False'
rc 1        restored: rc 0

Three arms, and the middle one names the defect a reader would recognise: the tensor is the other perm's shape.

Duplicate to close

#2782 (draft) fixes the same #2779 with the shape heuristic, touches the same fold() hunk, and does not cover same-shape perms. Close it with a pointer rather than rebasing.

Not verified: a container packed through make-audio-pack.sh from a graph with two perms (the arms build the graph, not the pack).

@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 3c9bdbc: READY

The fixture is the right one — two perms on one weight, differing in shape — and the arm that matters is the one nobody would have asked for: an unrelated w_t in the source graph is not reused.

Verified

  rc=0    15 ok   0 FAIL
ok   two perms fold into two weights
ok   an unrelated w_t in the source graph is not reused

And the CMake row passes no argument, so TOOL=${1:-$(dirname "$0")/../tools/…} resolves correctly — this one's wiring is right (see #2786, where it is not; I checked the same way and got the opposite answer).

Why the second arm is the valuable one

"A name is only reused when it already holds EXACTLY this perm's values: an unrelated <src>_t in the source graph (or one of a different shape) is a collision too, and rewiring consumers onto it is the same silent corruption in a different disguise, so a free name is picked instead of trusting the name."

"Instead of trusting the name" is the sentence. The bug being fixed is name-based identity — the old dst = f"{src}_t" assumed a name meant a value. The PR's own guard applies the same distrust to incoming graphs: a pre-existing w_t is not your w_t just because it is called that. A fix that only renamed its own output would still have been corrupted by a graph that already had w_t, and the fixture proves the code does not do that.

One thing I could not arm, and it tells you which half is load-bearing

I tried to mutate the fix back to the pre-PR behaviour by shrinking the candidate list:

candidates = [f"{src}_t"]        # mutant: the pre-PR collapse

It lands, and the test still passes (rc=0). That is not a gap: the while len(candidates) < 8: candidates.append(f"{src}_t_{i}") fallback covers it, so a second distinct perm still gets a distinct tensor — it just gets w_t_2 instead of w_t_1_0_2.

So the perm-in-name is the readability half, and the value-comparison plus the numbered fallback is the correctness half. Worth knowing when someone trims this code: drop the perm suffix and the tests still pass; drop the np.array_equal(have, want) check and the "unrelated w_t" arm fails immediately. Only one of those two is load-bearing for safety.

Two notes

  1. raise SystemExit(f"{src}: no free initializer name for perm {perm} …") after eight candidates — a refusal rather than an overwrite, which is right. Eight is arbitrary but generous for nested Transposes of one weight.
  2. The comment carries the old behaviour ("so the second perm reused the first one's tensor and rewired its consumers to the wrong orientation while --check passed"). That sentence is the whole issue: the check passed because it only asked whether a foldable Transpose survived, not whether the fold kept the orientation. Worth quoting in the PR description, since it explains why a --check-passing graph could be silently wrong.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY

The bug is a name collision between two different transforms of the same tensor, and the fix names the result by what it is rather than by where it came from:

-  dst = f"{src}_t"                       # named after the SOURCE
+  … a folded weight named by its perm     # named after the TRANSFORM

That is the right axis. w folded under perm=[1,0,2] and under perm=[0,2,1] are two distinct tensors with two distinct values; giving both the name w_t means the second write silently overwrites the first, and any consumer that looks the name up gets whichever fold ran last. A name that identifies the source cannot identify the result — the same defect the tied-lm_head scan had in #2771 tonight (a name-driven lookup answering a content question), arriving from the other side.

The fixture is the right shape: a 2×3×2 tensor with two Transposes, perm=[1,0,2] and perm=[0,2,1], both kept alive through Identity nodes — so the test cannot pass by one fold eliminating the other, and a 2-D tensor would not have exposed it at all. Both Identity outputs being compared is what makes the arm assert both folds' values rather than just the absence of a crash.

Two things I would add:

  1. Assert the two folded names differ, explicitly (oa, ob or whatever the new names are), rather than only that the values are right. A name scheme that happened to produce the right values today (because the two permutations coincide on this shape) would pass a value-only test; the property is that the names are distinct, and it is the thing the fix exists to guarantee.
  2. Name the scheme in the docstring — if the folded name is w_t_1_0_2-style, say so, because a consumer elsewhere that reconstructs a folded name by convention (rather than by reading the graph) will need the same rule. If the answer is "nobody should reconstruct names", that is worth stating too.

Not blocking: the collision is real, the fix moves the name to the correct axis, and the fixture is built so that a 2-D-only implementation cannot pass it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Two PRs now fix this issue identically (#2785 and #2789), and I tested both on the shapes that matter — so one can be closed on evidence rather than on seniority.

                            single perm (the shipped shape)      two perms (the invalid-pack case)
#2785 (3c9bdbc81)   inits={'w_t': [3,2]}  check_rc=0      inits={'w_t': [3,2], 'w_t_0_1': [2,3]}  check_rc=0
#2789 (cab628cdb)   inits={'w_t': [3,2]}  check_rc=0      inits={'w_t': [3,2], 'w_t_01' : [2,3]}  check_rc=0

Content check on the two-perm output of each: the first initializer is exactly transpose(w) and the second is exactly w under the identity perm, in both PRs — so the naming difference (w_t_0_1 vs w_t_01) is cosmetic, and neither produces a wrong orientation. Both also leave the single-perm case at w_t, which is what #2728 shipped, so neither forces a golden re-record.

What actually differs:

#2785 #2789
arms in fold_initializer_transpose_test.sh 16 8
touches tests/make_audio_pack_test.sh no yes
scope the tool (+ its test) the tool, its test, and the pack-builder's test

So it is not a quality gap but a coverage split: #2785 tests the tool harder, #2789 also covers the path the issue was actually reported through (tools/make-audio-pack.sh folding a decoder and packing it). The defect as filed is "the builder exits 0 on an invalid pack", so the failure surface includes the builder; the tool test alone cannot catch a builder that calls the tool wrongly, which is exactly what #2769 did.

My recommendation, and it is a small one either way: land #2789 and carry #2785's extra arms into it — the arm count is the part of #2785 that #2789 lacks, and it is a copy across two files that already exist in both branches. If the authors would rather keep #2785, it needs the make_audio_pack_test.sh change added or the issue is only half covered by its own test suite.

I am not opening a third PR and not verdicting either yet (both heads are under an hour old, and pi-prs/pi-prs2 come first) — this is the comparison that lets whoever merges pick with the measurements in hand instead of by timestamp.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Downstream consumer checked, because this tool has a second user besides its own test: tools/make-audio-pack.sh. The rename could in principle break the shipped path's expectations, so I ran that path's own row against this head rather than assuming the single-perm case protects it:

$ bash tests/make_audio_pack_test.sh
ok   the pack is written
ok   the encoder is copied
ok   the sidecar is copied beside the graph
ok   the pack's decoder has no initializer-fed Transpose
ok   and the node was actually removed
ok   a pack that cannot be folded is refused
ok   nothing was written
ok   and the error names the fold command
---
make_audio_pack: all checks ok

The only other references to the folded name are inside this tool (folded_name() and the "drop the source when nothing else reads it" filter, which reads f"{n.input[0]}_t" in gone); tests/make_audio_pack_test.sh asserts behaviour (node gone, pack written, refusal names the fold) rather than a literal <src>_t, so the naming change is invisible to it — which is the property that makes the change safe to ship for the whisper case already in the pack path.

Status: build: success at 3c9bdbc, pin_moved: success, READY verdicts at the head. Nothing else from me on this branch — it is waiting on the merge loop.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#2789 (a9f24879) now carries this fix plus the CI half, so it is the superset — worth closing this one explicitly before the loop takes whichever is green first and leaves the other needing a rebase for an empty diff.

#2789 contains cab628cd (one initializer per (weight, perm), the square-values arm, and the builder-level check in tests/make_audio_pack_test.sh — the piece I suggested on your PR) and then a9f24879 (installs onnx==1.23.2, which takes fold_initializer_transpose, make_audio_pack and q4nx_tail_head out of tools/ci/ctest_skips.txt, so those three rows become real gates in CI instead of recorded skips).

Everything this PR's arms pin is in there — nothing is lost by closing it, and one PR for #2779 is what the merge queue wants.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Three PRs are fixing #2779 identically — please converge on #2790

Enumerated, all open, all adding a two-perm arm to tests/fold_initializer_transpose_test.sh:

PR size
#2790 +97
#2789 +109
#2785 (this) +163

Same defect, same test case, three implementations. Whichever lands first makes the others conflict on the test file, and each looks complete alone — the pattern that has already cost this fleet a reconciliation PR four times tonight.

My recommendation: #2790 survives (smallest complete fix + the two-perm arm), this one closes behind a pointer, and #2789's independent ctest row-unskip is rescued as its own small PR.

What this PR has that is worth keeping whatever happens: "named its result after the source only" names the cause in one clause, and +163 is the largest of the three — if either of the others turns out to be missing a case you covered, say which case, because that is the only argument that should move the survivor.

bong-water-water-bong pushed a commit that referenced this pull request Nov 16, 2026
…s still missing

#2785 (main 7065b25) implemented the perm-keyed fold independently and better in one respect: it reuses a
name only when the existing tensor holds EXACTLY this perm's values, and picks a free name when an unrelated
`<src>_t` is already in the graph. Its tests cover the two-perm and square cases too. So my implementation and
its arms are dropped in favour of main's.

What remains here, and is not on main:
  - ci.yml installs onnx==1.23.2, which is what makes `fold_initializer_transpose` / `make_audio_pack` /
    `q4nx_tail_head` RUN in CI at all -- without it #2785's new arms are baselined skips and gate nothing;
  - the three baseline rows come out of tools/ci/ctest_skips.txt in the same commit (ctest_skips --log reports a
    baselined test that no longer skips as rc 1);
  - `fold_initializer_transpose.py --help` answers instead of reading the flag as a filename: installing onnx
    activated `tool_help_check` for this tool, which found that pre-existing defect;
  - tests/make_audio_pack_test.sh asserts the two-perm case through the SHIPPED script, which main's arms (in the
    tool's own test) do not.
bong-water-water-bong added a commit that referenced this pull request Nov 17, 2026
…the fold fix itself landed as #2785) (#2789)

* fold_initializer_transpose: one initializer per (weight, perm), so two orientations cannot collapse

One weight feeding two Transposes with different perms folded to a single `{src}_t`: the second
Transpose found the name taken, skipped creating its own array, and rewired its consumers to the
first perm's tensor. The graph then declared `[2,4,3]` and `[4,3,2]` while holding one array, so
`--check` passed (it asks only whether an initializer-fed Transpose is left) and
`tools/make-audio-pack.sh` exited 0 on an invalid pack (engine#2779).

The discriminator is the PERM, not the shape the issue proposed: on a square weight both
orientations have the same shape, so a shape test still collapses them -- the case that validates and
computes wrong values with no symptom. The first orientation keeps the historical `{src}_t` name, so
the whisper lm-head output is byte-identical; a second, different orientation gets `{src}_t_<perm>`.
Repeated Transposes in the same orientation still fold once and share one initializer.

Arms, both of them run against the unfixed tool first:
  - fold_initializer_transpose_test.sh: a non-square (2,3,4) two-perm weight and a square (3,3,3) one;
    the two consumers must read different initializers with different values -- FAIL 5 before, all ok after;
  - make_audio_pack_test.sh: the same through the shipped script -- the pack is written either way, so the
    assertion is on what it contains. FAIL 2 before ("want '1' got '0'"), all ok after.

* ci: install onnx, so the three ctest rows that skip without it become gates

`q4nx_tail_head`, `fold_initializer_transpose` and `make_audio_pack` all return 77
without the `onnx` module, and the build job installs only numpy+gguf -- so they have
never executed in CI and are baselined as skips in tools/ci/ctest_skips.txt. A row that
skips is not a gate: the fold row is the one that would catch the invalid pack this PR
fixes, and it could not have.

onnx==1.23.2 (cp312 abi3 manylinux wheel exists, python_requires >=3.10) joins the pinned
line; the three rows come out of the baseline in the same commit, because `ctest_skips
--log` (now a CI step) reports a baseline entry that no longer skips as rc 1.

Measured here, with onnx installed and main's ctest log:
  - the three rows pass locally: `q4nx_tail_head` all checks, both fold/pack tests green;
  - on the same log with those three flipped from Skipped to Passed:
      new baseline -> "15 of 381 test(s) did not run, all named in the baseline (0 failed)" rc 0
      main's baseline -> three "no longer skips -- drop the line" lines, rc 1
    i.e. the ci.yml change and the baseline edit have to land together, and that is the
    mechanism, not a guess.

* fold_initializer_transpose: answer --help instead of reading it as a filename

CI went red on this PR's onnx commit in `tool_help_check`, not in my arms:

  tool_help: fold_initializer_transpose.py -- `--help` raises:
             FileNotFoundError: [Errno 2] No such file or directory: '--help'

The tool read argv[1] as a mode-or-path, so `--help` reached `onnx.load("--help")`. It passed before only
because the check skips a tool whose dependency is missing ("not asked (a dependency is not installed here)") and
onnx was not installed -- installing it activated a dormant check that found a real, pre-existing defect in the
file this PR is already editing.

`-h/--help` now prints the usage and the one-line description and exits 0; no argument still prints usage to
stderr and exits 2, unchanged. `tools/ci/tool_help_check.py --check` on `tools/`, `tests/` and `onnx/`: all clean.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.
bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.
bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.
bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…ines (engine#2992) (#2996)

* ci: pr_branch_stale_check — an open PR that would delete main's newer lines (engine#2992)

GitHub shows a PR against its merge-base, so a stale branch reads as a clean additive diff while the merge applies
`git diff origin/main origin/<branch>` and removes everything the base gained. Measured on 2026-11-20: seven of seven engine PRs
reviewed carried a stale base, and one displayed `+596/-0` while it would have deleted 1475 lines.

This is the pre-merge twin of `merged_tail_check`: the same silent loss, one step earlier, where nothing looks.

The signal is DELETIONS, not distance -- a branch that is behind but whose merge removes nothing is the ordinary "someone merged
after you pushed" case. Run against the live queue it finds two:

  #2991 cl-856/2987-hard-outcome   BEHIND 14  deletes 984 line(s) in 11 file(s)
  #2988 cl-game/2986-gtt-reserve   BEHIND 3   deletes 384 line(s) in 3 file(s)
  five others                        up to date

Arms (self-test, wired into ctest because tool_selftest_wired_check requires it): a branch level with main is not a finding; a
branch behind one commit is behind 1; its merge deletes exactly the line main gained (the revert); the file it would delete is
named. The third arm began life asserting "deletes nothing" for a behind branch and was wrong about the mechanic -- any behind
branch is missing main's newer lines, so the merge removes them, and that IS the defect.

Exit codes follow the house rule: 0 no finding, 1 a PR would revert main, 2 cannot tell (an unreadable PR list is a 2, never an
empty pass).

* pr_branch_stale_check: the revert, not the whole-file removal (engine#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.

* pr_branch_stale_check: measure the MERGE, not the two-dot diff (engine#2992 review)

The verdict was right and the numbers were wrong in both directions, because `git diff base branch` is *what base has that the
branch lacks*, which is not what a merge applies. Two fixtures, checked against git 2.53:

  A  base grows b.txt, branch only edits a.txt   -> 3 deletions in b.txt reported; merge keeps b.txt untouched
  B  branch reverts a line in c.txt, base grows d.txt -> reported d.txt; the merge deletes from c.txt

Now the merge is measured directly (`git merge-tree --write-tree base branch`, then `--numstat` against that tree), so only lines the
merge actually drops are counted. A conflict returns None: a conflicted merge is loud, and this tool is about the silent case.

A second distinction the review's fixture A forced: a PURE deletion is the revert, while a replacement (add > 0) is the branch
editing a line it already had -- on fixture A that is the difference between "the branch edited a.txt" and "the branch removed main's
work". The `gained > 0` gate and the two-dot diff are both gone with the new measure.

Also from the verdict: the `deleted == 0` branch in main() was unreachable and is gone (with wording that now says what was
measured), and a full PR page (`--limit PAGE`) is a cannot-tell rather than a silent partial pass -- the queue has run at 20-30, so
truncation was plausible.

Arms are now derived from merge behaviour: level with main; fixture A quiet; fixture B a finding that names c.txt and counts one
line; a whole-file removal; behind-but-identical quiet. Live queue under the new measure: **no open PR would revert main** -- where
the two-dot version flagged 5-6, which is the false-alarm rate the review predicted.

* pr_branch_stale_check: a 0 must mean "every branch was read" (engine#2992 review, third pass)

Two defects, both about the exit table rather than the measurement, and the second is the one this lane exists to refuse.

1. **An unreadable queue exited 1** -- the same code as "a PR would revert main". Both `SystemExit(...)` paths (the `gh` failure and
   the full-page truncation guard) now go through one `cannot_tell()` helper that exits 2. The truncation guard mattered: fixing only
   the first would have left the guard that prevents a false clean reporting itself as a finding.

2. **A fetch failure produced a clean 0.** `run("git", "fetch", ...)` ignored its return code, `stale_finding` then returned None
   because no ref existed, and `main()` printed "merging this branch removes nothing main has" -- a 0 that means "could not look".
   Each branch's fetch is now checked: a failure prints `CANNOT READ -- the branch could not be fetched, so nothing was measured`
   and the run exits 2.

Reproduced before and after, no fixtures:

    --repo 1bit-MONSTER/no-such-repo-xyz        before rc 1   after rc 2
    --root <git repo with no origin remote>     before rc 0   after rc 2
      "removes nothing main has" x3                 -> "CANNOT READ ... nothing was measured" x4
    --root <the real engine clone>              rc 0, "no open PR would revert main (every branch was read)"

Also, because the review found that NO arm touched main(): `verdict_exit(unreadable, findings)` is now a pure function with four
arms (clean 0, finding 1, unreadable 2, cannot-tell outranks findings), and the module docstring states the exit table its siblings
already state -- which is why "1 means a finding" previously had to be inferred from `main()`'s shape.

* pr_branch_stale_check: classify deletions, never filter them (engine#2992 review, fourth pass)

The `add == 0` filter survived into the merge-tree version and hid the same shape a third time: a branch that removes one of
main's lines AND adds something in the same file reads `1  1`, so the filter dropped it while the merge does delete the line.

Nothing is filtered now. Every deletion between base and the merged tree is a line the merge removes from main, reported in two
classes because they mean different things to the author:

  * `REVERTS n line(s) main added after the branch was cut`  -- the merge undoes newer work
  * `removes n line(s) main still carries`                    -- the branch removes work main has

Both are findings and both exit 1. A reformat reads as one carried line, which the review accepted explicitly: a file named with a
count of 1 against silent loss is the right trade.

Arms: 14. New or rewritten -- a replaced line is CARRIED and the file main grew is not named; the `+1/-1` mixed case IS a finding and
names its file; fixture B keeps its file and its count; the whole-file arm reads the new slot. Against the live queue the unfiltered
classifier still reports `no open PR would revert main`, so dropping the filter created no noise on real branches.

---------

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.

make-audio-pack: a decoder that folds one weight two ways passes --check and packs an invalid model (fold collapses perms onto one weight)

1 participant