Skip to content

fold_initializer_transpose: a second perm gets its own folded weight (engine#2779) - #2782

Closed
bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-review/2779-fold-perms
Closed

bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-review/2779-fold-perms

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2779 — draft, because engine carries 6 non-draft PRs against the cap of three.

The defect, measured through the shipped builder before this change

$ 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 reported …
pack/decoder_model.onnx: nodes 4 -> 2, folded 2
pack/decoder_model.onnx: nodes 2, initializer-fed Transposes 0    # … --check passes …
pack: pack (encoder + folded decoder)                    rc=0     # … and the pack is written

initializers: {'w_t': [3, 2]}                            # one folded weight
nodes: [('Identity', ['w_t'], ['out_a']), ('Identity', ['w_t'], ['out_b'])]

out_b declares [2,3] and reads a [3,2] tensor. On a square weight it would validate and compute the wrong values with no symptom — and --check cannot see it either way, because a wrongly folded graph has no initializer-fed Transpose left, which is the only thing --check looks for.

The fix

dst = f"{src}_t"
if dst in inits and list(numpy_helper.to_array(inits[dst]).shape) != list(want.shape):
    dst = f"{src}_t{''.join(str(p) for p in perm[0])}"   # a second, different orientation

Same source + same perm still folds once (a duplicated Transpose reuses the weight), and the single-perm case — the whisper lm head, i.e. every pack this tool has actually built — is byte-identical: w_t only, unchanged name, unchanged shape. Verified on two fixtures:

two perms : initializers {'w_t': [3, 2], 'w_t01': [2, 3]}
            Identity ['w_t'] -> ['out_a']      Identity ['w_t01'] -> ['out_b']
one perm  : initializers {'w_t': [3, 2]}        (unchanged)

The arm

Added to tests/make_audio_pack_test.sh, at the level the user meets it — through the builder:

$ bash tests/make_audio_pack_test.sh
ok   a two-perm decoder packs
ok   each consumer names a folded weight
ok   and the two weights are the two orientations
…
make_audio_pack: all checks ok

$ (the tool fix reverted, everything else identical)
FAIL each consumer names a folded weight: want '2' got '1'
FAIL and the two weights are the two orientations: want '2' got '1'
2 failed

So the two new checks are the mutant control for the fix, and the six pre-existing checks stay green (ok the pack's decoder has no initializer-fed Transpose, ok a pack that cannot be folded is refused, …).

bash scripts/pre-pr-checks.sh → 13 green, 2 skipped; tools/copyright.py --check rc 0.

Why it is worth landing at all

The shipped whisper decoder has one such Transpose, so today's packs are fine — but make-audio-pack.sh is generic (ENCODER.onnx DECODER.onnx) by construction, and the failure it produces is an invalid ONNX that passes every check the tool has. This is the same class as the rest of today: a verifier that cannot see the thing it was added to catch.

Was raised as a review finding on #2728 (1347a071) and again on #2769 (ce992de4); both merged without it, hence a separate PR rather than a comment on a closed one.

…(engine#2779)

The folded weight was named after the SOURCE only (`{src}_t`), so a second Transpose of
the same initializer with a different perm found the name taken, skipped creating its
array, and rewired its consumers to the FIRST perm's tensor. tools/make-audio-pack.sh
then packed it happily, because --check asks "is an initializer-fed Transpose left" and a
wrongly folded graph has none.

Measured through the shipped builder before this change:

  folded w -> w_t [3, 2]
  folded w -> w_t [2, 3]                  both folds reported
  pack/decoder_model.onnx: ... 0          --check passes
  pack: pack ... rc=0                     the build succeeds
  initializers: {'w_t': [3, 2]}           one weight
  out_b declares [2,3] and reads it       an invalid model

Now the second orientation folds to `{src}_t<perm>`, so each consumer reads its own:
`w_t` [3,2] and `w_t01` [2,3]. Single-perm graphs (the whisper lm head) are unchanged,
which the existing arms pin.

Arm added to tests/make_audio_pack_test.sh: a two-perm decoder packs, each consumer names
a folded weight, and the two weights are the two orientations. Reverting the tool fix fails
both new checks ("want '2' got '1'"); the rest of the suite stays green.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Draft on purpose: engine carries 6 non-draft PRs against the cap of three, and this is a two-line tool fix plus one arm. Complete and mutant-controlled — undraft when the count drops and it goes straight into the queue. My own PR, so no verdict from this lane.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

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 each consumer reads its own folded weight when there are multiple permutations
  • The fix ensures that folded weights are named uniquely when different permutations are used
  • The fix maintains byte-identical output for the single-perm case
  • Tests are added to verify the two-perm case behavior

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 for Multiple Permutations

The tool previously used the same naming convention for folded weights regardless of the permutation used. This caused a second transpose with a different permutation to reuse the first folded weight, leading to incorrect tensor shapes being consumed by different consumers. The fix ensures that each unique permutation gets its own folded weight name, preventing this silent invalidation.

dst = f"{src}_t"
# engine#2779: a second Transpose of the same weight with a DIFFERENT perm gets its own folded array. Naming
# both by the source alone made the second fold skip creating its array and rewire its consumers to the
# FIRST perm's tensor -- a silently invalid graph that `--check` cannot see, because no initializer-fed
# Transpose is left in it (measured: two perms over one 2x3 weight produce out_b declared [2,3] reading a
# [3,2] tensor, and tools/make-audio-pack.sh packs it happily).
if dst in inits and list(numpy_helper.to_array(inits[dst]).shape) != list(want.shape):
    dst = f"{src}_t{''.join(str(p) for p in perm[0])}"

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #2785, which is my fix plus two things mine does not have — and the extra arms are the better ones.

#2782 (this) #2785
first fold keeps <src>_t (existing packs/names unchanged) ✓ ✓
a further distinct perm gets its own name ✓ ✓
refuses when the taken name has a different shape ✗ ✓
arm for a square weight, where the two perms differ in values only ✗ ✓

The square case is the one I missed: my arm compared shapes, so a 2×2 weight folded under [0,1] and [1,0] would have produced two consumers reading the same tensor with the same shape and passed my check while being wrong. That is the silent-corruption case in its purest form, and #2785 asserts the values, not the shapes.

One thing from this PR worth carrying over there, as a comment rather than a second PR: my arm ran through tools/make-audio-pack.sh rather than the tool alone —

ok   a two-perm decoder packs
ok   each consumer names a folded weight
ok   and the two weights are the two orientations

which is the level the defect actually bit (#2779's measurement was make-audio-pack … rc=0 on an invalid pack). Tool-level arms prove the fold; a builder-level arm proves the pack is right, and --check cannot do that for either. I have posted the arm's shape on #2785 as a suggestion.

Branch deleted with this close.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Verified on the shape the issue reports, and on the shape that shipped (I reviewed #2728, so this one is partly my miss — see the last section).

A. one initializer, two Transposes with different perms  (the invalid-pack case)
   fixed tool:  folded w -> w_t    [3, 2]
                folded w -> w_t01  [2, 3]
   packed file: initializers {'w_t': [3,2], 'w_t01': [2,3]}
                nodes [('Identity', ['w_t']), ('Identity', ['w_t01'])]
                --check rc 0     <- and now the check is *right*, because each consumer reads its own orientation

B. one perm (the whisper-head shape that shipped in #2728), original vs fixed tool
   initializer names identical: True   bytes identical: True   nodes identical: True
   names ['w_t'] -> ['w_t']            consumer input ('w_t',)

So the fix does the two things that matter: a second orientation gets its own identifier ({src}_t<perm>), and the single-orientation case stays byte-identical to what merged — no golden churn, no re-record, and the --check contract is unchanged for the shapes that were already fine.

One residual worth deciding before this leaves draft, and I do not have a strong view: the naming is {src}_t<perm> only for the second orientation, so which one gets the bare w_t depends on node order in the graph. That is fine for validity and reproducibility (the graph is the input), but it means two exports of the same model with the transposes in a different order produce different initializer names for the same content. If anything downstream keys on names — a golden diff, a cache — that would show up as churn; if nothing does, bare-w_t-for-first is the least surprising choice and I would keep it.

My miss, since it is on the record

I reviewed #2728 and gave it READY. I tested it on the real whisper pack (which is why the fold, the byte-identical transpose, the kept original and the 159 MB growth were all checked on real bytes) but I only ever exercised one Transpose of the initializer, because that is what that pack contains. The derived-name collision needs two different perms of one initializer, which a fixture can build in ten lines and I did not build. The lesson is the same one this fleet keeps teaching: a real-data check proves the real data, not the contract — and here the contract was the thing being extended. Worth saying plainly rather than letting the READY stand as if it had covered this.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Reproduced on main and verified against this head, with the fixture the issue describes — and one acknowledgement owed from my own review of #2728.

Main (fe7a1d1c), tool as shipped, a decoder with one 2x3 initializer feeding two Transposes with different perms:

$ python3 fold_initializer_transpose.py twoperm.onnx out.onnx
folded w -> w_t [3, 2]
folded w -> w_t [2, 3]          <- both reported
out.onnx: nodes 4 -> 2, folded 2
  initializers: {'w_t': [3, 2]}                        <- ONE weight
  consumers   : Identity(w_t) -> out_a ; Identity(w_t) -> out_b
$ python3 fold_initializer_transpose.py --check out.onnx      -> nodes 2, initializer-fed Transposes 0, rc=0

out_b declares [2,3] and reads a [3,2] tensor, and --check — whose only question is "is an initializer-fed Transpose left" — passes. Exactly the issue.

This head (87aaa721), same fixture:

folded w -> w_t [3, 2]
folded w -> w_t01 [2, 3]
  initializers: {'w_t': [3, 2], 'w_t01': [2, 3]}
  consumers   : Identity(w_t) -> out_a ; Identity(w_t01) -> out_b
--check -> initializer-fed Transposes 0, rc=0

Each consumer now names the orientation it declared, so --check passing finally means what it says, and the single-perm path is unchanged (w_t, same bytes).

The acknowledgement. In my verdict on #2728 I wrote that "a duplicated Transpose folds once because dst is reused" as a good property. It is right for two Transposes with the same perm and silent corruption for two with different perms — I read the if dst not in inits guard as idempotence and never asked what happens when the second perm differs. The issue and this fix are the correct reading; that is a review miss on my side, recorded here rather than quietly fixed.

I am not posting a verdict at this head (it is inside the 1 h window and pi-prs lanes go first); if nobody has by the time it passes, this comment is my evidence for one.

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