Skip to content

docs(skill): stop recommending onnx.save into an existing external-data blob - #489

Merged
justinchuby merged 1 commit into
onnxruntime:mainfrom
justinchuby:fix/skill-external-data-append
Aug 14, 2026
Merged

justinchuby merged 1 commit into
onnxruntime:mainfrom
justinchuby:fix/skill-external-data-append

Conversation

@justinchuby

Copy link
Copy Markdown
Member

The salvage recipe in the ONNX export gotchas skill re-saves with onnx.save(..., save_as_external_data=True, location="model.onnx.data"). When that file already exists, onnx.save_model reaches onnx.external_data_helper.save_external_data, which does:

with os.fdopen(fd, "r+b") as data_file:
    data_file.seek(0, 2)          # seek to END, then write

It appends. The previous copy of the weights is never truncated, the offsets in model.onnx are rewritten to point at the newly appended copy, and the original copy stays on disk referenced by nothing.

Nothing fails when this happens — the model loads and produces byte-identical output. The file is simply twice the size it should be, which is exactly why it survives review.

Measured

A 512×512 fixture, saved fp32 with external data, then put through each recipe (cast FLOAT32 → fp16, re-save into the same location):

onnx.save: blob 1,050,624 -> 1,575,936   referenced 525,312   orphaned 1,050,624 (66.7%)
   ir.save: blob 1,050,624 ->   525,312   referenced 525,312   orphaned         0 ( 0.0%)

Both produce FLOAT16 initializers, so the recipes are equivalent in outcome; only one of them leaves a dead copy behind.

Why ir.save

save_as_external_data appears in exactly one place in this repository — this skill file. Everything under src/ already uses ir.save, which writes the blob with "wb" and overwrites unconditionally. The skill was last touched 2026-06-12 (#351) and appears to predate that convergence, so this brings it in line with the rest of the codebase rather than introducing a new dependency.

The added note about ir.save invalidating existing external tensors that reference the path it is writing comes from its own docstring, and matters here because the recipe loads from the file it then saves over.

The assert

A silent failure deserves an assertion rather than a reader remembering to look at a file size, so the fix adds the post-condition:

referenced = sum(
    int(dict((kv.key, kv.value) for kv in t.external_data)["length"])
    for t in m.graph.initializer
    if t.data_location == onnx.TensorProto.EXTERNAL
)
assert referenced >= 0.99 * pathlib.Path("model.onnx.data").stat().st_size

Scope

Context in #488. To be explicit about what this PR does not claim: I hit a real mobius-produced artifact with a 50.02% orphaned blob (16.652 GB, of which 8.330 GB referenced), and I do not know that this recipe produced it — the arithmetic actually argues against it, since the two generations in that file are the same size to within 0.088% and this recipe involves an fp32→fp16 cast that would shrink the second one. That investigation is still open in #488. This PR fixes a documented recipe that is unsafe on its own terms.

Docs only.

…ta blob

The salvage recipe in the ONNX export gotchas skill re-saves with
onnx.save(..., save_as_external_data=True, location='model.onnx.data').
When that file already exists, onnx.save_model reaches
onnx.external_data_helper.save_external_data, which opens the target 'r+b'
and then seek(0, 2) -- it appends. The previous copy of the weights is
never truncated, the offsets in model.onnx are rewritten to point at the
newly appended copy, and the original copy stays on disk referenced by
nothing.

Nothing fails when this happens. The model loads and produces
byte-identical output; the file is just twice the size it should be, which
is why it survives review.

Measured on a 512x512 fixture, saving fp32 then re-saving as fp16 into the
same location:

  onnx.save: blob 1,050,624 -> 1,575,936   referenced 525,312   orphaned 66.7%
     ir.save: blob 1,050,624 ->   525,312   referenced 525,312   orphaned  0.0%

save_as_external_data appears in exactly one place in this repository --
this skill. Everything under src/ already uses ir.save, which writes 'wb'
and overwrites unconditionally. The skill was last touched 2026-06-12 and
appears to predate that convergence, so this brings it in line.

Swaps the recipe to ir.save and adds the post-condition assert, because a
silent failure deserves an assertion rather than a reader remembering to
check a file size.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 14, 2026 05:41
@justinchuby
justinchuby merged commit 17a1deb into onnxruntime:main Aug 14, 2026
17 of 18 checks passed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Updates the ONNX export gotchas skill to stop recommending onnx.save(..., save_as_external_data=True, location=...) when the external-data blob already exists (since ONNX’s external-data writer appends), and aligns the documented salvage workflow with the repository’s onnx_ir-based save path.

Changes:

  • Document that onnx.save_model appends to an existing external-data blob and can silently leave orphaned weight data behind.
  • Switch the salvage recipe to onnx_ir.load + in-place dtype cast + ir.save(..., external_data="model.onnx.data") to overwrite the blob.
  • Add a post-condition assertion snippet intended to detect orphaned data by comparing referenced external-data lengths vs file size.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +125 to +130
referenced = sum(
int(dict((kv.key, kv.value) for kv in t.external_data)["length"])
for t in m.graph.initializer
if t.data_location == onnx.TensorProto.EXTERNAL
)
size = pathlib.Path("model.onnx.data").stat().st_size
justinchuby added a commit to justinchuby/onnx-genai that referenced this pull request Aug 14, 2026
…zp was 50.02% dead space) (#927)

`models/qwen14b-zp` shipped a 16.652 GB `model.onnx.data` of which only
**8.330 GB (50.02%) was referenced** by any initializer. The
unreferenced part was a single contiguous prefix `[0, 8322547712)` — an
entire superseded generation of weights left in the file, referenced by
nothing.

Nothing fails when this happens, which is why it went unnoticed: the
model loads and produces byte-identical output. The costs are quieter:

- **2× disk and 2× download.**
- **2× pinned host RAM on the memory-mapped weight path**, which
registers the whole mapping — #912 measured `host_registered_bytes =
16,652,453,888` for 8.33 GB of live weights. On a RAM-constrained host
that is the difference between running and thrashing.
- **A wrong derived number.** Sizing a weight budget from file length
rather than referenced extents made the model look **2.00×** larger than
it is (#853, fixed in #856).

## The script

Streams the referenced byte ranges into a fresh blob and rewrites the
offsets in the model proto, so it never loads tensor data into memory
and works on blobs far larger than RAM.

```
source blob : 16,652,453,888 bytes (16.652 GB)
repacked    :  8,330,399,744 bytes (8.330 GB)
reduction   : 49.97%
tensors     : 920
```

**Verified rather than assumed:** the repacked model produced *exactly*
the same 16 generated token IDs as the original — same prompt, same
binary, same GPU — with `captures=2 fallbacks=0` and `oversubscribed=0`
unchanged. The docstring says so too, because a repack that has not been
checked against token identity is not one anyone should trust.

## On provenance

Which code path produced the doubled blob is **still unknown**, tracked
at
[onnxruntime/mobius#488](onnxruntime/mobius#488).

There is a real appending path — `onnx.save(...,
save_as_external_data=True)` into an existing `location` reaches
`save_external_data`, which opens `"r+b"` and `seek(0, 2)` — and
mobius's own documented salvage recipe does exactly that, fixed in
[onnxruntime/mobius#489](onnxruntime/mobius#489).
But the arithmetic argues it did **not** produce this artifact: that
recipe casts fp32 → fp16, so the second generation would be smaller by
the size of the cast tensors, while here the two generations are the
same size to within **0.088%**. I stated a root cause twice before
checking it; this is what is actually established.

The check is cheap and belongs anywhere a model is packaged:

```python
referenced = sum(
    int(dict((kv.key, kv.value) for kv in t.external_data)["length"])
    for t in m.graph.initializer
    if t.data_location == onnx.TensorProto.EXTERNAL
)
assert referenced >= 0.99 * data_path.stat().st_size
```

Tooling only; no runtime code touched.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants