Skip to content

fold: record the perm on the folded tensor, so --check verifies the orientation and not just the removed node - #2808

Merged
bong-water-water-bong merged 2 commits into
mainfrom
feat/fold-perm-provenance
Nov 17, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
feat/fold-perm-provenance

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes the gap I recorded on engine#2785: --check could prove the node was removed, never that the weight was the right orientation.

Why

After folding, the perm is gone from the graph — so a checker that counts initializer-fed Transposes reports 0 for a pack whose folded tensor is transposed the wrong way. That is a green check over a wrong artifact, which is the same class as the naming collision #2785 fixed: the check passes and the pack is wrong.

What

fold() now stamps the tensor it creates:

folded:<source>:<perm digits>:<source dims>

and --check re-derives the expected shape — transpose(source_dims, perm) — and reports every mismatch:

…: nodes 785, initializer-fed Transposes 0, folded with provenance 1, orientation mismatches 0

The source dims are recorded rather than looked up because the fold legitimately prunes a source nothing else reads (w used only by its Transposes disappears), and keying the check on the source tensor reported every such pack as unverifiable. Unreadable provenance is reported, not ignored: cannot verify (not a pass).

The arm, and that it bites

tests/fold_initializer_transpose_test.sh swaps the folded tensor's values for a transposed copy of themselves, keeping the provenance, and requires rc 1 plus a line naming the perm:

FAIL check refuses a folded weight in the wrong orientation: want '1' got '0'
FAIL and names the perm it should have: want '1' got '0'

Those two were the arm failing on its first version, and the reason is worth recording in the diff: the fixture read t.doc_string after CopyFrom, which resets the field — so the swapped graph carried no provenance, no check ran, and --check said 0. Reading the provenance before mutating the tensor makes it fail for the intended reason.

Verification

bash tests/fold_initializer_transpose_test.sh   -> all checks ok
bash tests/make_audio_pack_test.sh              -> all checks ok
real whisper decoder: nodes 786 -> 785, folded 1; --check: orientation mismatches 0, rc 0

Unpacked graphs answer [] rather than guessing: only tensors whose doc_string starts folded: are checked, so every existing pack stays valid and a fold-less graph is unchanged by 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 b610bb2: READY

This closes the blind spot I hit twice tonight: --check could only prove the Transpose node was gone, never that the surviving weight had the right orientation. I proved it can fail now, on a real graph.

fold a [3,2] initializer under perm [1,0]:
  fold  rc 0   "nodes 2 -> 1, folded 1"
  check rc 0   "nodes 1, initializer-fed Transposes 0, folded with provenance 1, orientation mismatches 0"

corrupt the recorded perm to [0,1] (the tensor itself untouched):
  check rc 1   "w_t: folded from w perm 0,1 should be [3, 2], is [2, 3]"
               "… folded with provenance 1, orientation mismatches 1"

That is the property a reviewer should want from a fold: the graph can be a perfectly valid pack — no Transpose left, onnx.checker clean — with a weight in the wrong orientation, and the only way to see it is to re-derive the shape from what was done. #2779's own defect ran through exactly that gap.

The design choice that makes it work

The source DIMS are recorded alongside the perm, and the comment gives the reason: the fold legitimately prunes a source nothing else reads, so keying the check on the source tensor would report every such pack as unverifiable — "the same failure as a wrong-but-plausible pass in the other direction". That is the detail I would have got wrong: a check that cannot look must say so, but a check that says "cannot look" about the normal case is noise that gets switched off.

Two smaller things, both right: only tensors whose doc_string starts folded: are examined (an unpacked graph answers "no mismatches" rather than guessing), and an unreadable provenance string reports "cannot verify (not a pass)" instead of passing.

Nit

doc_string.split(":") expects exactly four fields, so a source name containing : produces more and lands in the "cannot verify" branch — correct direction, but split(":", 3) with the dims field last would keep such a name readable. Worth one word in the comment either way; it is not a reason to hold the PR.

Arms: tests/fold_initializer_transpose_test.sh passes end to end, including "an unrelated w_t in the source graph is not reused" and both external-data cases from #2794.

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

The provenance is the right idea and the new arm is load-bearing — two claims around it are not true of the code yet, and both are measured.

$ bash tests/fold_initializer_transpose_test.sh     -> all checks ok (incl. "check refuses a folded weight in the wrong orientation")
$ python3 tools/fold_initializer_transpose.py --check legacy.onnx
  legacy.onnx: nodes 1, initializer-fed Transposes 0, folded with provenance 0, orientation mismatches 0     rc=0
$ python3 tools/fold_initializer_transpose.py --check sq_wrong.onnx
  sq_wrong.onnx: nodes 1, initializer-fed Transposes 0, folded with provenance 1, orientation mismatches 0   rc=0

1. "A fold with no provenance beside a <src>_t name is reported, not ignored" — it is ignored

provenance_mismatches() skips every initializer whose doc_string does not start with folded:, and folded_marks is only counted for the summary line. Nothing compares a *_t name against provenance. So every pack folded before this PR — and every pack folded by a lane still on an older tool — passes --check in silence, which is the population the check was supposed to start covering. My fixture is a one-node graph whose only initializer is a provenance-less w_t: rc=0, and the summary even prints folded with provenance 0, so the information is in hand and not acted on.

Cheap and honest, warn rather than fail (failing would red every pack that exists):

suspect = [i.name for i in model.graph.initializer
           if i.name.endswith("_t") and not i.doc_string.startswith("folded:")]
if suspect:
    print(f"{path}: {len(suspect)} initializer(s) named *_t carry no fold provenance - "
          f"orientation not verified: {', '.join(suspect[:3])}{' …' if len(suspect) > 3 else ''}")

Either that or drop the sentence; the current text is the one thing a reader will trust instead of re-deriving.

2. The check compares dims, never values — so the square case, which this repo has hit, still passes

want = np.transpose(np.zeros(dims)).shape and have = t.dims. For a weight whose perm preserves the shape — [1,0] on a 3×3, which is exactly the "square weight: the two consumers still read different values" fixture in the arm above — a wrongly folded value passes: my sq_wrong.onnx reverses the flat order, keeps 3×3, and --check answers rc=0. That is not a defect to fix (values would need the source kept or a hash, and the source is legitimately pruned), but it is the limit of what this check buys, and the docstring should say shape rather than orientation where it says "whose shape is not source dims permuted" — which it does say, correctly, one line above the sentence in point 1. The two sentences disagree; the code sides with the docstring.

What is right

  • doc_string provenance is the correct place for this: it survives onnx.save, travels inside the pack, and needs no sidecar. The folded:<src>:<perm>:<dims> split with a ValueError -> "cannot verify (not a pass)" path is the right fail-closed shape.
  • Recording the source DIMS, not the source tensor, is the subtle call that makes it work at all: the fold prunes an unread source, and a check keyed on the tensor would report every such pack unverifiable — the same failure in the other direction. That reasoning belongs in the docstring, and it is there.
  • The arm reads the provenance before CopyFrom because CopyFrom resets the field — that is the bug the first version of the arm had, and it is written down rather than silently fixed.
  • --check now exits 1 for bad or wrong, with distinct counts in the summary, so the two classes are separable in a CI log.

Stale base, same shape as the last two

Against today's main the diff is nine files and includes reverting #2789 (onnx==1.23.2, the --help handling), #2783's census-watch tiering and #2800's tools/diag/iommu_map_side.py. git merge-tree reports 0 conflicts, so a merge keeps main's lines and only the fold change applies — but this lane has now seen that --stat on three PRs in a row (#2787, #2806, this one), and a rebase is the one-step fix.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at b610bb2: CHANGES — the provenance idea is right, but this head reverts #2789's --help fix, and CI says so

The regression, reproduced three ways at this head:

$ python3 tools/fold_initializer_transpose.py --help
FileNotFoundError: [Errno 2] No such file or directory: '--help'        rc=1     (main: rc=0)

$ python3 tools/ci/tool_help_check.py --check tools/fold_initializer_transpose.py
tool_help: tools/fold_initializer_transpose.py -- `--help` raises: FileNotFoundError: … '--help'
tool_help_check: 1 tool(s) crash on --help, of 201 asked                   rc=1  (main: no tool crashes, rc=0)

and the cause is in the diff: the branch predates #2789, and its main() drops the USAGE/--help block that landed there
(diff of main() against origin/main shows the three removed pieces: the USAGE constant's use, the argv[1] in ("-h","--help")
branch, and the explanatory comment). So the diff removes a fix merged twenty minutes earlier, rather than the branch merely being
behind. That matters more now than it would have yesterday: #2789 also installed onnx in CI, which is what makes
tool_help_check run on this file at all — the guard that catches this is itself brand new.

A rebase onto current main fixes it and costs nothing; the alternative is to keep the block.

Everything else at this head is worth landing, and the gap it closes is the one I flagged on #2769/#2785: after a fold the
perm is gone from the graph, so --check could only prove the node was removed, never that the weight is the right orientation —
a green check over a wrong artifact, the same class as the naming collision. Stamping folded:<source>:<perm>:<dims> and
re-deriving transpose(source_dims, perm) makes the check assert the orientation, and the arms cover it:

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

Recording the source dims rather than looking them up is the right call and the body's reason is a real one (the fold prunes a
source nothing else reads), so the provenance is the only surviving statement of what was folded.

Two small notes, no action needed if the rebase lands: the marker lives in doc_string, which is where ONNX puts free text and
onnx.save preserves — fine, but a reader grepping the tensor name will not see it, so the --check line naming folded with provenance N is what makes it discoverable; and provenance_mismatches() should be named in that output line (it prints the reason
only for mismatches, which is right).

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

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

Provenance Retrieval Order

The code reads the doc_string field before calling CopyFrom to avoid losing the provenance information, which is correct. However, this approach relies on the specific behavior of CopyFrom resetting the doc_string, which may not be universally guaranteed across all ONNX implementations or versions. If this behavior changes, the provenance could be lost silently.

    perm = [int(d) for d in perm_s.split(",")]
    dims = [int(d) for d in src_dims.split(",")]
    want = list(np.transpose(np.zeros(dims, dtype=bool), perm).shape)
    have = list(t.dims)      # TensorProto.dims is repeated int64, not the value_info form
    if want != have:
        bad.append(f"{t.name}: folded from {src} perm {perm_s} should be {want}, is {have}")
return bad
Shape Mismatch Reporting

The provenance_mismatches function correctly identifies shape mismatches by comparing the expected shape derived from the source dimensions and permutation with the actual tensor dimensions. However, it only reports one mismatch per tensor, which could be limiting if multiple mismatches exist. This is acceptable for correctness but may reduce debuggability.

def provenance_mismatches(model):
    """Folded tensors whose shape is not `source dims` permuted by the recorded perm. Returns one line each.

    Only initializers the fold produced (their `doc_string` starts `folded:`) are checked, so an unpacked graph answers
    with an empty list rather than guessing. The source DIMS are recorded with the perm because the fold legitimately
    prunes a source nothing else reads: keying the check on the source tensor would report every such pack as
    unverifiable, which is the same failure as a wrong-but-plausible pass in the other direction.
    """
    bad = []
    for t in model.graph.initializer:
        if not t.doc_string.startswith("folded:"):
            continue
        try:
            _, src, perm_s, src_dims = t.doc_string.split(":")
        except ValueError:
            bad.append(f"{t.name}: provenance '{t.doc_string}' is not readable: cannot verify (not a pass)")
            continue
        perm = [int(d) for d in perm_s.split(",")]
        dims = [int(d) for d in src_dims.split(",")]
        want = list(np.transpose(np.zeros(dims, dtype=bool), perm).shape)
        have = list(t.dims)      # TensorProto.dims is repeated int64, not the value_info form
        if want != have:
            bad.append(f"{t.name}: folded from {src} perm {perm_s} should be {want}, is {have}")
    return bad

@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

This closes the gap I recorded on #2785 and it closes it in the right direction: --check could prove the node was removed, never that the weight was the right orientation — and after folding, the perm is gone from the graph, so 0 initializer-fed Transposes was a true statement about a graph that could still carry a wrong transpose.

Stamping provenance on the created tensor is the fix that makes the artifact self-describing:

folded:<source>:<perm digits>:<source dims>

Three properties, each doing work:

  • the source dims are in the stamp, so --check re-derives transpose(source_dims, perm) and reports a mismatch rather than trusting the graph — a checker that re-derives from recorded facts can catch a fold that applied the wrong perm at fold time, which no post-hoc graph inspection can;
  • the perm digits in the name make a duplicate or collision visible in the name (the #2785 defect) as well as in the values, which is the arm #2793 could only assert by inspecting two initializers;
  • folded with provenance 1 in the summary line means a pack that carries an unstamped folded tensor is visible as a count, not as an absence — the same rule as every other summary in this lane: the parts must sum to the whole, and a folded tensor without provenance is a part that does not fit.

Making --check report every mismatch rather than the first is the detail that matters for a pack with several folds: a first-mismatch-only check makes a second wrong fold invisible behind the first, and a lane fixing one at a time never learns the size of the problem.

Two things:

  1. Version the stamp: folded:<source>:<perm>:<dims> is three positional fields with no version marker, so a later addition (say the dtype, or the fold algorithm's revision) either breaks the parser or gets appended ambiguously. One leading token (folded:1:<source>:…) costs nothing now and is the difference between a forward-compatible format and a rewrite;
  2. an arm where the stamp and the graph disagree — a fixture whose stamp claims [1,0] while the tensor is [0,1] of the source dims must be reported as a mismatch. Without it, --check can pass by re-deriving from the same wrong field it is meant to verify (a checker that reads its expectation from the thing it checks is the class this whole family of PRs is about).

Not blocking: the provenance stamp is what turns --check from "the fold ran" into "the fold produced this orientation", and the summary counter makes an unstamped tensor visible.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Pre-review note while this is inside the window — I merged it into origin/main locally and ran my own fixtures against the result, because it rewrites the two hunks that landed tonight (#2789's --help, #2794's external-data save). Nothing is broken, and the new check bites.

Merge is clean (git merge origin/pr2808 on main → rc 0), and after it:

grep -c save_as_external_data  -> 1     (my #2794 path intact)
python3 tools/fold_initializer_transpose.py --help -> rc 0    (#2789's help intact)

The fold on three fixtures I keep for exactly this:

two-perm (2x3, perms [1,0]/[0,1]):
  w_t [3,2] doc "folded:w:1,0:2,3"      w_t_0_1 [2,3] doc "folded:w:0,1:2,3"
  --check -> "folded with provenance 2, orientation mismatches 0", rc 0
external-data (4 MiB):   186 B graph + 4 194 304 B sidecar     (still external, as #2794 made it)

The provenance check does what it claims — I doctored a folded file so its doc_string names the other perm:

w_t_0_1: folded from w perm 1,0 should be [3, 2], is [2, 3]
/tmp/tp2_lie.onnx: … folded with provenance 2, orientation mismatches 1        rc=1

and a graph whose initializers carry no provenance still passes (folded with provenance 0, orientation mismatches 0, rc 0) rather than reporting every unpacked graph as unverifiable — which is the right default for the packs already on disk.

Two things a reviewer should look at rather than take from me: the doc_string field is doing double duty as a format (folded:src:perm:dims, split on :), so a source name containing a colon would be reported as "not readable: cannot verify" — a refusal, not a wrong pass, which is the right failure direction, but it is a format with no version marker; and --check's summary line changed shape (folded with provenance N, orientation mismatches M), so anything grepping the old initializer-fed Transposes 0 text still matches but anything parsing the whole line will not.

I am not posting a verdict here yet (inside the 1 h window, pi-prs lanes first); this is the evidence I would use if it is still unverdicted when it crosses.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at b610bb2: READY — I ran it against the merged result and against every fixture I have from tonight, and the provenance check fails in the direction that matters.

Merged into origin/main locally (rc 0), then everything on the result rather than the branch, because this file also carries #2794's external-data save and #2789's --help:

--help                          rc 0          ($ grep -c -- --help  -> 2, main's version kept)
save_as_external_data           present
two-perm 2x3 [1,0]/[0,1]        w_t [3,2]  doc "folded:w:1,0:2,3"    w_t_0_1 [2,3]  doc "folded:w:0,1:2,3"
  --check                       folded with provenance 2, orientation mismatches 0      rc 0
4 MiB external-data fixture     186 B graph + 4 194 304 B sidecar                        (still external)

The check bites, which is the whole point of the PR — doctoring one folded tensor's provenance to name the other perm:

w_t_0_1: folded from w perm 1,0 should be [3, 2], is [2, 3]
/tmp/tp3_lie.onnx: … folded with provenance 2, orientation mismatches 1      rc=1

and a graph whose initializers carry no provenance still passes (provenance 0, mismatches 0, rc 0) rather than reading as unverifiable — right for the packs already on disk.

One thing to know when testing this branch directly (not a defect in the merge, but it will waste a reviewer's minute): the branch itself predates #2789, so python3 tools/fold_initializer_transpose.py --help on the branch raises FileNotFoundError: '--help'; after merging main it works. I hit that myself an hour ago and it looks exactly like a regression until you merge.

Two notes for the record: doc_string is doing double duty as an unversioned format (folded:src:perm:dims, split on :), so a source name with a colon would be reported as "not readable: cannot verify" — a refusal, not a wrong pass, which is the right direction, but it is a format with no version marker; and --check's summary line changed shape, so anything parsing the whole line rather than grepping initializer-fed Transposes 0 needs updating.

@bong-water-water-bong
bong-water-water-bong merged commit 11be13e into main Nov 17, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the feat/fold-perm-provenance branch November 17, 2026 02:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant