Skip to content

Reuse compatible GGUF weights as ONNX external data - #573

Merged
justinchuby merged 5 commits into
mainfrom
justinchuby-reuse-gguf-weights
Aug 25, 2026
Merged

justinchuby merged 5 commits into
mainfrom
justinchuby-reuse-gguf-weights

Conversation

@justinchuby

@justinchuby justinchuby commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Stacked on #571 (justinchuby-gguf-registry-foundation). Adds an explicit opt-in path that publishes ONNX beside the original GGUF without writing a second full copy of byte-compatible weights.

mobius build-gguf output/model.gguf --output output/ --reuse-gguf-weights
package = build_from_gguf("output/model.gguf", reuse_gguf_weights=True)
package.save("output/")

Storage and transform behavior

  • Unchanged F32/F16 tensors and consumer-compatible native IQ4_NL, IQ4_XS, IQ3_S, IQ3_XXS, IQ2_XXS, IQ2_XS, IQ2_S, IQ1_S, IQ1_M, and MXFP4 tensors point at exact GGUF location + offset + length ranges.
  • Float transpose, norm offset, Llama Q/K row permutation, and Mamba A_log/shape transforms keep the source bytes and run as ONNX graph operations. Opaque packed UINT8 is never generically transposed.
  • Repacked, requantized, dequantized, synthesized, or otherwise materialized large tensors are written exactly once to model.onnx.data.
  • Disabling constant folding preserves the on-disk reuse but transformed weights may still allocate runtime buffers and add startup/execution cost.

Persistence and verification

A persistent same-directory advisory lock serializes writers, recovery, and shared verification. Mixed saving stages and fsyncs the sidecar, model, and manifest, validates the complete staged package, then installs it through an atomically published durable transaction journal with hard-linked rollback backups. The journal records replacing/committed state so crashes cannot produce mixed rollback or leak full backup copies. Interrupted reruns recover before save/verification; failed reruns restore prior artifacts; obsolete sidecars are removed transactionally.

Recovery deletes only staged and backup paths owned by a structurally and path-validated journal; generated-looking filenames are never treated as proof of ownership. Lock, journal, staged, backup, model, manifest, and sidecar paths reject symlinks and non-regular artifacts. Lock acquisition validates directory-entry/opened inode identity; journal files are created through exclusive no-follow temporary files and atomic replacement.

gguf-reuse.json pins source location, size, SHA-256, source tensor/qtype/range, initializer dtype/length, source/final shapes, transform name, and transform parameters. Verification enumerates every ONNX external initializer: each must be either an exact manifest-pinned GGUF range or a non-overlapping range in the one permitted sidecar. Sidecar ranges must exactly equal the byte count implied by concrete non-negative shape and supported dtype. Verification rejects unmanifested/unsafe locations, wrong dtype/qtype/shape/ranges, mixed reused/converted claims, and mutated transform wiring/constants/permutations.

Scope and runtime requirements

This PR supports one flat text-model package. The real little-endian GGUF must already be in the output directory. It rejects nested/non-flat packaging, mmproj/MTP packages, symlinks, unsafe hardlinks, generated-name collisions, changed source identity, safetensors output, and sidecar sharding rather than copying or linking the GGUF.

Use direct ONNX Runtime with graph optimization disabled:

options = ort.SessionOptions()
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL

--reuse-gguf-weights --runtime ort-genai is rejected because the current genai_config.json schema has no supported setting that requires disabled constant folding.

Validation

  • 214 affected GGUF builder, ModelPackage, runtime-package, CLI, API, and option-parity tests pass.
  • Synthetic mixed GGUF/sidecar execution matches the ordinary converted package numerically on ORT CPU with optimizations disabled.
  • Tests cover writer/verifier ownership, committed and interrupted crash recovery, atomic journal publication, unsafe links/artifacts, source collisions, preservation of generated-looking source/user files, complete external enumeration, exact sidecar nbytes, qtype/dtype/range and transform mutations, source identity, hardlink capability, stale-sidecar removal, and exception rollback.
  • lintrunner f --output oneline --all-files and lintrunner -a pass locally.

Waiver

No multi-GB public GGUF was downloaded. Real-weight validation is deferred to avoid a large network/storage dependency; synthetic files use the real GGUF writer/reader, exact offsets, native block routes, mixed persistence, reload, and ORT execution.

@github-actions

github-actions Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 7958f1a → c5772c2

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 7958f1a → c5772c2

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 176 176 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

@justinchuby
justinchuby force-pushed the justinchuby-gguf-registry-foundation branch from 184176f to 3b52342 Compare August 25, 2026 14:48
Base automatically changed from justinchuby-gguf-registry-foundation to main August 25, 2026 14:49
@justinchuby
justinchuby requested a review from a team August 25, 2026 14:49
justinchuby and others added 5 commits August 25, 2026 07:51
Add an explicit build-gguf opt-in that points compatible ONNX initializers at exact tensor ranges in the original GGUF while externalizing converted weights to a separate sidecar. Pin and verify source provenance, enforce safe flat packaging, and preserve mixed external references during save.

Document the initial consumer and layout limitations, including deferred graph-expressible transforms and ORT optimization requirements, and cover mixed save/reload, exact ranges, unsafe paths, identity changes, and CPU inference.

Co-authored-by: Copilot App <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Reject ORT GenAI packaging when constant folding cannot be disabled, verify every external initializer and graph-level transform against the source manifest, and retain graph-expressible float transforms over GGUF-backed bytes.

Stage, fsync, validate, and transactionally install the model, sidecar, and manifest with durable rollback journals, crash recovery, confined journal paths, obsolete artifact removal, and explicit filesystem capability checks.

Co-authored-by: Copilot App <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Protect mixed-package recovery and replacement with a persistent advisory lock, publish transaction state atomically, and reject unsafe generated artifacts without following links. Validate converted sidecar references against their exact dtype-and-shape byte size and cover concurrent ownership, crash recovery, symlink mutation, and truncated or oversized ranges.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: e99f9fcb-697e-4853-b34c-b854c3995535
Signed-off-by: Justin Chu <[email protected]>
Remove filename-inferred stale staging cleanup so recovery deletes only artifacts named by a structurally validated transaction journal. Cover a source GGUF and unrelated user file whose names resemble generated staging files.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: e99f9fcb-697e-4853-b34c-b854c3995535
Signed-off-by: Justin Chu <[email protected]>
Reject external-byte reuse for split GGUF sets before accessing single-file storage metadata. Normal multi-shard builds continue through the current main path unchanged.

Co-authored-by: Copilot App <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Copilot AI lite review requested due to automatic review settings August 25, 2026 14:53
@justinchuby
justinchuby force-pushed the justinchuby-reuse-gguf-weights branch from 5cc663c to c5772c2 Compare August 25, 2026 14:53
@justinchuby
justinchuby merged commit b6d166a into main Aug 25, 2026
18 of 21 checks passed
@justinchuby
justinchuby deleted the justinchuby-reuse-gguf-weights branch August 25, 2026 14:53

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

This PR adds an opt-in “GGUF weight reuse” mode for build_from_gguf / mobius build-gguf that preserves byte-compatible GGUF tensor payloads by referencing the original .gguf file as ONNX external data, while writing only truly materialized tensors to model.onnx.data. It also adds transactional save + verification via a manifest (gguf-reuse.json) and rejects runtime packaging modes that can’t require disabled constant folding.

Changes:

  • Add reuse_gguf_weights plumbing from CLI → GGUF builder → ModelPackage.save(), including constant-folding disablement and ORT GenAI runtime rejection.
  • Introduce src/mobius/integrations/gguf/_reuse.py implementing reuse planning, transactional persistence (lock + journal + rollback), and a verifier for manifest/ONNX external initializers.
  • Expand unit tests and docs to cover the new flag, persistence/rollback, and verifier behavior.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/gguf_test.py Adds CLI help/forwarding tests and CLI-level rejection for --runtime ort-genai with reuse.
src/mobius/integrations/gguf/_runtime_package.py Rejects ORT GenAI packaging when the package was built with GGUF reuse.
src/mobius/integrations/gguf/_runtime_package_test.py Adds coverage for runtime-package rejection in reuse mode.
src/mobius/integrations/gguf/_reuse.py New core implementation: attach external initializers, transactional save/journal, and manifest verification.
src/mobius/integrations/gguf/_reader.py Exposes GGUF endianness and per-tensor storage ranges needed for reuse/verification.
src/mobius/integrations/gguf/_builder.py Adds reuse_gguf_weights option, disables folding during apply, records certain transforms for runtime, and attaches GGUF-backed external initializers.
src/mobius/integrations/gguf/_builder_test.py Adds extensive tests for mixed GGUF/sidecar save, verifier behavior, and transactional recovery/rollback.
src/mobius/integrations/gguf/init.py Exports verify_gguf_reuse_manifest.
src/mobius/_model_package.py Adds gguf_reuse_plan state, routes save() through reuse transaction saver when present, and adds fold_constants to apply_weights().
src/mobius/main.py Adds --reuse-gguf-weights flag and performs CLI-level incompatible-option rejection.
docs/api/build_from_gguf.md Documents reuse_gguf_weights, manifest verification, and ORT optimization requirements/limitations.

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

Comment on lines +340 to +366
def _validate_source(plan: GGUFReusePlan, output_directory: Path) -> None:
source = plan.source_path
if source.is_symlink():
raise ValueError("The GGUF source became a symlink; refusing an unsafe external path.")
if source.parent.resolve() != output_directory.resolve():
raise ValueError(
"reuse_gguf_weights=True requires flat same-directory packaging: move the "
f"GGUF to {output_directory} before building. Mobius will not copy, hardlink, "
"or symlink a multi-GB source file."
)
if source.name in _GENERATED_NAMES:
raise ValueError(
f"The GGUF source name {source.name!r} collides with a generated package "
"artifact. Rename the GGUF before building."
)
for generated_name in _GENERATED_NAMES:
generated_path = output_directory / generated_name
if generated_path.exists() and os.path.samefile(source, generated_path):
raise ValueError(
f"The GGUF source is hard-linked to generated artifact "
f"{generated_name!r}. Use an independent real file."
)
if source.stat().st_size != plan.size or _sha256(source) != plan.sha256:
raise ValueError(
"The GGUF source no longer matches the file used to build this package "
"(size or SHA-256 changed). Rebuild from the intended GGUF."
)
Comment on lines +194 to +207
uses = list(initializer.uses())
if not uses:
return
dtype = initializer.dtype
final_shape = initializer.shape
assert dtype is not None and final_shape is not None
prefix = f"{initializer.name}.gguf_reuse"
output = ir.Value(
name=f"{prefix}.output",
shape=final_shape,
type=ir.TensorType(dtype),
)
initializer.replace_all_uses_with(output)
initializer.shape = ir.Shape(candidate.source_shape)
justinchuby added a commit that referenced this pull request Aug 25, 2026
## Summary

- clean up still-valid typing, documentation, test robustness,
error-message,
  maintainability, and performance findings left by the GGUF PR stack
- preserve the behavioral fixes merged in #625-#632
- hash reused multi-GB GGUF sources once, at the final pre-publication
integrity
  gate, while retaining cheap identity checks around staging

Exact base: `2db9d33debdc254d879a51b14434c9a81c230f4f`

Exact head: `4541ed2bc9d2ab4227484510b4a85b2d9113eb25`

## Reconstructed original 17-item low-priority tranche

The persisted audit retained only the totals, so this list was
reconstructed
from the live threads and current source. All but the already-fixed #596
comment are addressed in this PR.

| PR | Comment | Disposition |
|---|---:|---|
| #550 | 3837144656 | Implemented: correct tuple return annotation |
| #552 | 3837389183 | Implemented: multichannel waveform shape docs |
| #559 | 3837716261 | Implemented: name-based cache assertions |
| #573 | 3854308350 | Implemented: one final GGUF hash, with integrity
regression coverage |
| #574 | 3854345521 | Implemented: `TensorRole \| None` typing |
| #574 | 3854345597 | Implemented: removed obsolete verdict filtering |
| #577 | 3854472859 | Implemented: documented SSM sequence length |
| #578 | 3843112613 | Implemented: documented F64 passthrough |
| #579 | 3854518332 | Implemented: generalized fused-projection error |
| #580 | 3854576300 | Implemented: removed brittle node counts |
| #583 | 3854681386 | Implemented: documented conditional draft outputs
|
| #587 | 3854816872 | Implemented: corrected MTP output contract docs |
| #596 | 3846110059 | Already fixed on base: unambiguous GQA bias
comment |
| #600 | 3855174281 | Implemented: metadata-count-only MTP error |
| #607 | 3855776048 | Implemented: stable route-field assertions |
| #607 | 3855776086 | Implemented: public tensor iterator |
| #609 | 3856486136 | Implemented: fail-closed LM-head comment |

## Current unresolved-thread disposition

This covers all 48 Copilot threads returned by the reproducible
#600-#630
query. The one human #623 thread is excluded.

| PR | Comment | Current-main disposition and evidence |
|---|---:|---|
| #600 | 3855174177 | Already fixed by #629: package cycle and
reserved-sidecar validation |
| #600 | 3855174238 | Already fixed by #629: explicit MTP sidecar
naming/loading |
| #600 | 3855174281 | Implemented here: error no longer invents an
observed block count |
| #602 | 3848155961 | Outside exact stack; already fixed: top-level
`expert_dtype` is classified before early return |
| #602 | 3848155983 | Outside exact stack; still-valid behavioral
block-quant validation, unchanged |
| #602 | 3848156000 | Outside exact stack; still-valid truncated-read
behavioral finding, unchanged |
| #602 | 3848156022 | Outside exact stack; still-valid descriptor
byte/dtype validation, unchanged |
| #602 | 3848156040 | Outside exact stack; still-valid expert-bank
payload validation, unchanged |
| #603 | 3855249765 | Already fixed by #630: runtime preflight preserves
shard sets |
| #603 | 3855249840 | Already fixed by #630: success output follows
durable runtime publication |
| #604 | 3855343082 | Implemented here: graph-only MTP persistence
distinguished from runtime rejection |
| #604 | 3855343131 | Already fixed by #630: runtime success messages
are atomic |
| #607 | 3855776001 | Implemented here: missing generation golden skips
before provenance read |
| #607 | 3855776048 | Implemented here: only stable route fields are
asserted |
| #607 | 3855776086 | Implemented here: tensor count uses
`tensor_items_raw()` |
| #608 | 3856079371 | Still-valid behavioral cache-symlink containment
finding; unchanged |
| #608 | 3856079415 | Still-valid behavioral lowercase-digest validation
finding; unchanged |
| #609 | 3856486136 | Implemented here: comment matches value-preserving
policy |
| #610 | 3855541683 | Already fixed by #628: Falcon bias precedence is
explicit |
| #610 | 3855541761 | Already fixed by #628: CTRL tiny config exercises
projection biases |
| #611 | 3856595840 | Implemented here: runtime test resolves the
distribution providing the module |
| #612 | 3855677383 | Already fixed by #625: supported-version
endianness detection |
| #612 | 3855677427 | Implemented here: shared `INT64_MAX` sentinel |
| #612 | 3855677460 | Implemented here: shared PLaMo2 width inference |
| #612 | 3855677486 | Implemented here: accepted PLaMo2 activation
spellings are explicit |
| #613 | 3855845678 | Implemented here: canonical issue URL |
| #613 | 3855845757 | Implemented here: Mamba-1 function-registration
docs |
| #613 | 3855845806 | Implemented here: test expects the canonical issue
URL |
| #614 | 3855988545 | Implemented here: removed stale Nemotron-H
divergence comments |
| #614 | 3855988597 | Already fixed by #628: zero-head geometry raises
actionable `ValueError` |
| #615 | 3856082290 | Already fixed by #626: dense GraniteHybrid bias
closure |
| #618 | 3856729330 | Implemented here: required routes filter ORT GenAI
evidence |
| #618 | 3856729409 | Implemented here: env-selected runtime version is
authoritative |
| #618 | 3856729490 | Stale/N/A: PR-description-only matrix claim;
repository workflow claims one pinned version |
| #618 | 3856729563 | Implemented here: schema tail restored to normal
indentation |
| #619 | 3856342484 | Already fixed on base: Kimi Linear uses
`/issues/605` |
| #619 | 3856342532 | Already fixed by #628: config rejects convolution
kernels below 2 |
| #619 | 3856342580 | Already fixed by #628: GGUF contract rejects
convolution kernels below 2 |
| #620 | 3855717041 | Already fixed by #627: tied LM-head-only
checkpoints are retained |
| #621 | 3856722324 | Already fixed by #628: Kimi-K3 required metadata
is complete |
| #623 | 3855931210 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939302 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939358 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939394 | N/A to current main: comment belongs to open,
unmerged #623 |
| #624 | 3856777152 | Implemented here: runtime compatibility reuses the
emitted model type |
| #625 | 3857049733 | Implemented here: unsupported header reports both
endian candidates |
| #629 | 3857313182 | Newer post-audit behavioral sidecar-symlink
cleanup finding; unchanged |
| #629 | 3857313251 | Newer post-audit cross-platform path-safety
finding; unchanged |

## Validation

- affected GGUF/package/ORT GenAI/model/schema tests: 1,040 passed
- broad non-integration suite: 7,851 passed, 56 skipped, 1 subtest
passed
- generated GGUF docs checks: 7 passed
- initialized `lintrunner`; full lint/format passed
- GPT-5.6 Sol medium review: one integrity finding fixed; re-review
found no significant issues

Signed-off-by: Justin Chu <[email protected]>
Co-authored-by: Copilot App <[email protected]>
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.

3 participants