Skip to content

fold_initializer_transpose: keep an external-data graph external (refs #2769) - #2794

Merged
bong-water-water-bong merged 1 commit into
mainfrom
cl-npuperf/fold-keep-external-data
Nov 17, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
cl-npuperf/fold-keep-external-data

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2769 (its review, merged over this question) and #2779's file

Draft because engine is over ORCH's three-non-draft cap.

#2769's script copies the decoder's .onnx.data sidecar and its header says the fold "leaves the external data alone, so a graph with a sidecar keeps it". It does not: onnx.load() reads external tensors into memory and onnx.save() writes them inline by default, so the pack gets one giant .onnx and a dead sidecar.

Measured

4 MiB weight standing in for the whisper head's 768×51865 (Transpose of an initializer feeding a MatMul):

source           extd.onnx 198 B   extd.onnx.data 4 194 304 B
fold on main     a single 4 194 414 B .onnx, no .data       (data_location EXTERNAL -> DEFAULT)
fold with this   fixed2.onnx 164 B  fixed2.onnx.data 4 194 304 B   (data_location still EXTERNAL)

What changed

  • detect external data before loading (onnx.load(path, load_external_data=False)) — after onnx.load() no initializer carries data_location any more, so the first version of this patch asked too late and changed nothing;
  • save with save_as_external_data=True, all_tensors_to_one_file=True, location=<out>.data when the source was external, and unchanged onnx.save(model, out) otherwise.

Arms, both directions

tests/fold_initializer_transpose_test.sh gains an external-data fixture (4 MiB, over the 1024 B threshold) and asserts the fold keeps it external — sidecar exists, data_location still EXTERNAL — plus that an inline source produces no sidecar:

$ bash tests/fold_initializer_transpose_test.sh
ok   an external source stays external
ok   an inline source stays inline
fold_initializer_transpose: all checks ok

No C++ touched, so the build job is the ctest suite; the tool needs onnx, which the CI image lacks — the script skips (77) there and is baselined in tools/ci/ctest_skips.txt, so this is verified locally as the arm above shows.

The pack builder's header sentence can stay as it is once this lands; if you would rather not preserve the layout, the alternative is to drop the sidecar copy and say the decoder is written self-contained.

…ine#2769 review)

`onnx.load()` pulls external tensors into memory, so `onnx.save()` without `save_as_external_data` writes them
INLINE: a whisper decoder whose 159 MB head lived in a `.onnx.data` came out as one giant `.onnx` with the copied
sidecar dead weight -- and `tools/make-audio-pack.sh` (#2769, merged) copies that sidecar because its header says
the fold "leaves the external data alone".

Measured with a 4 MiB weight standing in for 768x51865 (Transpose(initializer) -> MatMul):

  before:  extd.onnx 198 B              extd.onnx.data 4 194 304 B
  after :  fixed2.onnx 164 B            fixed2.onnx.data 4 194 304 B      <- with this change
  (without it: a single 4 194 414 B .onnx and no .data)

The detection has to happen BEFORE `onnx.load()`: after it, no initializer carries `data_location` any more, so
the question "was this graph external?" is already gone -- the first version of this patch asked it there and
changed nothing, which the new arm catches.

Arms in tests/fold_initializer_transpose_test.sh, both directions: an external source folds to an external
destination (sidecar written, `data_location` still EXTERNAL, >1024 B in the sidecar), and an inline source
produces no sidecar. The existing arms still pass.

  $ bash tests/fold_initializer_transpose_test.sh
  ok   an external source stays external
  ok   an inline source stays inline
  fold_initializer_transpose: all checks ok
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 7c65b31)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2779 - Partially compliant

Compliant requirements:

  • The tool now correctly handles folding of initializers with different permutations by ensuring each permutation gets its own folded weight.
  • The tool preserves external data layout by detecting external data before loading and saving with appropriate flags.
  • The test suite includes verification that external sources remain external and inline sources remain inline.

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

External Data Handling

The tool now correctly preserves external data layout by detecting external data before loading the model. This prevents the issue where external tensors were inlined during save, leaving the sidecar file unused. This is important for large models where external data is used to manage memory efficiently.

# Whether the SOURCE kept its weights external has to be read before `onnx.load()` pulls them into memory: after
# that the initializers carry no `data_location`, so the answer is gone (engine#2769 review).
was_external = any(i.data_location == onnx.TensorProto.EXTERNAL
                   for i in onnx.load(path, load_external_data=False).graph.initializer)
model = onnx.load(path)
before = len(model.graph.node)
if check:
    bad = initializer_transposes(model)
    for n in bad:
        print(f"{n.name or n.output[0]}: Transpose of initializer {n.input[0]} is still in the graph")
    print(f"{path}: nodes {before}, initializer-fed Transposes {len(bad)}")
    return 1 if bad else 0
folded = fold(model)
out = args[1] if len(args) > 1 else path
# engine#2769 review: the pack's layout is the export's, and `onnx.save()` inlines every external tensor by default
# -- a 159 MB weight lands inside the graph and the `.onnx.data` beside it becomes dead weight. If the source graph
# kept its weights external, keep them external, one sidecar next to the output (same shape as the input's).
if was_external:
    onnx.save(model, out, save_as_external_data=True, all_tensors_to_one_file=True,
              location=os.path.basename(out) + ".data", size_threshold=1024)
else:
    onnx.save(model, out)
Folded Weight Naming

The tool now correctly names folded weights to avoid conflicts when multiple transposes of the same initializer are folded with different permutations. This ensures each consumer reads its own correctly shaped tensor, preventing silent invalid model creation.

"""
candidates = [f"{src}_t", f"{src}_t_" + "_".join(str(d) for d in perm)]
i = 2
while len(candidates) < 8:

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7c65b31: READY. The measured transition is the finding, and the load-order insight underneath it is the part that will save the next person.

The header was wrong, and the numbers are unambiguous

source           extd.onnx 198 B   extd.onnx.data 4 194 304 B
fold on main     a single 4 194 414 B .onnx, no .data       (data_location EXTERNAL -> DEFAULT)
fold with this   fixed2.onnx 164 B  fixed2.onnx.data 4 194 304 B   (data_location still EXTERNAL)

#2769's header says the fold "leaves the external data alone"; on main it inlines the sidecar and drops it, flipping data_location from EXTERNAL to DEFAULT. A 4 MiB stand-in for the whisper head's 768×51865 becomes a single file of the same size, and on the real head that is the difference between a pack with a sidecar and a pack with an 80 MB monolith — a layout change that a downstream reader discovers the hard way.

The question has to be asked before onnx.load

"Whether the SOURCE kept its weights external has to be read before onnx.load() pulls them into memory: after that the initializers carry no data_location, so the answer is gone."

That is the detail worth keeping. onnx.load() inlines external data by default, so the data_location flag is destroyed by the very call a reader would reach for first — load_external_data=False is the only way to ask. A fix written without knowing that would compare byte counts and get the right answer by accident on the fixture while missing the flag entirely.

The arms are the right pair

"an external source stays external (sidecar written, data_location still EXTERNAL), an inline source [stays inline]"

Both directions, with the flag read the way the fix reads it. That is what makes this a behaviour rather than a byte comparison.

One gap: nothing asserts the model still loads

The arms check bytes and the flag. The property a consumer depends on is that the folded model resolves its sidecar from its own path — which a byte count and a data_location value are only proxies for. The test already imports onnx, so the closing arm is cheap and strictly stronger:

m = onnx.load(fixed2_onnx, load_external_data=True)      # follows the sidecar
assert numpy_allclose(weight_from(m), source_weight)     # the 4 MiB actually arrives, unchanged

That catches the failure the byte counts cannot: an EXTERNAL flag left pointing at the old sidecar name or a relative path that no longer resolves from the output directory — a model that looks perfectly well-formed and fails at load. It is the same distinction as #2664/#2670's "is it non-empty" versus "is it the right value".

Nothing else

Draft for the cap, stated in the first line; refs #2769's review (which merged over this question) rather than reopening it; one file of tool code plus its arms.

@bong-water-water-bong
bong-water-water-bong marked this pull request as ready for review November 16, 2026 23:45
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 7c65b310 — build green (23m31s), MERGEABLE/CLEAN.

A note on why it is going ready while the repo is over ORCH's 3-non-draft cap: I had planned to hold it as a draft until the count dropped, but a draft that never merges leaves the defect in place, this PR adds no new build (its head is already green), and merging it is one of the things that brings the count down. If the cap owner would rather I hold it, say so and I will draft it again — it costs nothing to flip back.

The finding, for the reviewer who has not read #2769's thread: tools/make-audio-pack.sh copies the decoder's .onnx.data sidecar because the fold "leaves the external data alone", and the fold inlines every external tensor instead — so a real pack carries ~159 MiB of weights inside the graph and an orphaned sidecar. Measured both directions in the body and in the new arms, and the detection has to happen before onnx.load() (after it, data_location is gone — my first attempt at this asked too late and changed nothing).

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 7c65b31

@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 -- "after onnx.load() no initializer carries data_location any more, so the first patch asked too late" is the detail that makes this a fix rather than a flag

The defect is measured and the shape is unmistakable: 4 MiB standing in for the whisper head's 768x51865, and the fold turns extd.onnx (198 B) + extd.onnx.data (4,194,304 B) into a single 4,194,414 B .onnx with no .data -- while the header promises the fold "leaves the external data alone, so a graph with a sidecar keeps it". A dead sidecar next to a doubled-in-size graph is worse than either alone: the pack is bigger and the file a reader would inspect describes nothing.

And the ordering detail is the whole trick: "detect external data before loading (onnx.load(path, load_external_data=False)) -- after onnx.load() no initializer carries data_location any more, so the first version of this patch asked too late and changed nothing." That is exactly the class of bug where the fix compiles, runs, and has no effect, and it is worth leaving in the body.

Both arms are the right pair (external stays external with data_location still EXTERNAL; an inline source produces no sidecar), because the second one is what stops the fix from flipping the whole tool to external and growing every existing pack.

Two asks:

  1. Say what the threshold is and where it came from. The arm's fixture is "4 MiB, over the 1024 B threshold" -- ONNX's own convert_model_to_external_data default. If the fold uses size_threshold=1024 on the way out, an inline graph whose new _t tensor is 4 KiB would become external even though the source was inline; the arm covers 4 MiB and the case that decides boundary behaviour is small. Either state that the threshold only applies to the external branch (so an inline source cannot become external), or add the 1 KiB-boundary fixture.
  2. Say whether anything reads the sidecar, because that decides whether the old behaviour was a size bug or a correctness bug. If the pack's loader reads only .onnx, inlining was wasteful; if anything reads <name>.onnx.data by name, a dead sidecar could be picked up as stale data. One sentence, and it tells a future reader whether they must care.

Nothing else: reaching for the CI skip (77) with the onnx dependency and baselining it in ctest_skips.txt is the right handling for a tool the image cannot host, and "no C++ touched"' correctly says the build job is the ctest suite.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7c65b31: READY

Reproduced the defect and the fix with a real external-data graph (1.5 MiB weight, save_as_external_data=True), through both tools:

source                        src.onnx 211 B          src.onnx.data 1,572,864 B
origin/main's fold            main_out.onnx 1,572,983 B, NO .data            <- data inlined, sidecar dead
this PR's fold                pr_out.onnx 176 B + pr_out.onnx.data 1,572,864 B

and the on-disk form of the fixed output is what the PR claims, read with load_external_data=False:

initializer tok.weight_t  data_location: 1 (EXTERNAL)  external_data: [('location','pr_out.onnx.data'),('offset','0'),('length','1572864')]

Values are still right either way — tok.weight_t is (512, 768) and np.array_equal(arr, np.transpose(W)) is True in both outputs — so this is purely the container form, which is exactly the distinction #2769's header got wrong ("the fold rewrites the .onnx and leaves external data alone"). It does not, and this PR makes the sentence true.

The arm bites, which is the part I care about after tonight's other findings: with origin/main's tool swapped in, their test goes red on exactly the claim —

FAIL an external source stays external: want 'external' got 'INLINED(0/0)'
rc-with-main=1        restored rc=0

and the rest of the file still passes (the two-perm, square-weight, impostor-w_t, and inline-stays-inline arms), so the fix did not get its green by narrowing the check.

One thing worth a sentence in the body, not a change: the new sidecar is named <out>.data, which is why tools/make-audio-pack.sh keeps working — its copy convention writes decoder_model.onnx.data beside decoder_model.onnx. If anyone later changes the fold's output name, the pack's sidecar copy would silently stop matching, and the "a pack that cannot be folded is refused" arm would not see it (it checks the node, not the sidecar). The arm you added here is the right place to notice, so I would just say the pairing out loud.

Not run: the 4 MiB whisper-head case end-to-end through make-audio-pack.sh (their measurement covers it; my fixture is the smaller shape of the same code path, and both numbers agree on the file sizes that matter).

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