Skip to content

Commit b6d166a

Browse files
justinchubyCopilot
andauthored
Reuse compatible GGUF weights as ONNX external data (#573)
## 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. ```bash mobius build-gguf output/model.gguf --output output/ --reuse-gguf-weights ``` ```python 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: ```python 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. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: e99f9fcb-697e-4853-b34c-b854c3995535
1 parent 7958f1a commit b6d166a

11 files changed

Lines changed: 2172 additions & 9 deletions

File tree

‎docs/api/build_from_gguf.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ def build_from_gguf(
2222
mmproj: str | Path | None = None,
2323
static_cache: bool = False,
2424
max_seq_len: int | None = None,
25+
reuse_gguf_weights: bool = False,
2526
) -> ModelPackage:
2627
```
2728

@@ -37,6 +38,7 @@ def build_from_gguf(
3738
| `mmproj` | `str \| Path \| None` | `None` | Optional companion multimodal-projector GGUF. |
3839
| `static_cache` | `bool` | `False` | Build a fixed-width KV cache when the architecture supports it. |
3940
| `max_seq_len` | `int \| None` | `None` | Static-cache sequence limit. |
41+
| `reuse_gguf_weights` | `bool` | `False` | Reuse byte-compatible F32/F16 and native IQ/MXFP4 tensor ranges from the original GGUF instead of copying them into ONNX external data. |
4042

4143
## Returns
4244

@@ -63,6 +65,50 @@ pkg.save("output/llama-float/")
6365
mobius build-gguf llama-3.2-1b-q4_0.gguf --output output/llama/
6466
```
6567

68+
### Reuse the original GGUF as external data
69+
70+
Place the GGUF directly in the output directory, then opt in:
71+
72+
```bash
73+
mobius build-gguf output/llama/model.gguf \
74+
--output output/llama/ \
75+
--reuse-gguf-weights
76+
```
77+
78+
The package contains `model.onnx`, the original GGUF, `model.onnx.data` with
79+
only converted/materialized tensors, and `gguf-reuse.json`. The manifest pins
80+
the GGUF location, size, SHA-256, qtypes, and exact reused ranges. ONNX runtimes
81+
do not enforce that digest; applications can call
82+
`mobius.integrations.gguf.verify_gguf_reuse_manifest()` before session creation.
83+
84+
Initial support is deliberately limited to one flat text model. Multimodal,
85+
MTP, nested, sharded, symlinked, absolute, and parent-relative GGUF layouts are
86+
rejected rather than copied or linked. F32/F16 tensors and compatible
87+
IQ4_NL/IQ4_XS/IQ3_S/IQ3_XXS/IQ2_XXS/IQ2_XS/IQ2_S/IQ1_S/IQ1_M/MXFP4
88+
projection/output tensors can be reused when no logical transform is required.
89+
Repacked, requantized, dequantized, or synthesized tensors are true storage
90+
changes and therefore go to the sidecar.
91+
92+
Float transpose, norm-offset arithmetic, Llama Q/K row permutation, and Mamba
93+
`A_log`/shape transforms are not inherent storage incompatibilities. Reuse mode
94+
keeps their original F32/F16 bytes in the GGUF and inserts the corresponding
95+
ONNX `Transpose`, `Sub`, `Neg`/`Log`, or `Reshape` operations before their graph
96+
consumers. Opaque packed UINT8 blocks are never passed through a generic ONNX
97+
`Transpose`; only a consumer with a proven native block layout can reuse them.
98+
99+
Create ORT sessions with graph optimization disabled
100+
(`SessionOptions.graph_optimization_level = ORT_DISABLE_ALL`) so ORT does not
101+
constant-fold them into another materialized weight copy. This first version
102+
therefore rejects `--runtime ort-genai`: the current `genai_config.json` schema
103+
has no supported session option that can require disabled constant folding.
104+
Use direct ONNX Runtime for reuse packages.
105+
106+
Disabling folding preserves storage reuse but does not make transforms free at
107+
runtime. A transpose/permutation or arithmetic node may allocate a transformed
108+
weight buffer and consume startup or execution time. The package avoids a second
109+
on-disk copy; peak runtime memory and performance remain transform- and
110+
execution-provider-dependent.
111+
66112
## Behavior
67113

68114
1. Reads GGUF metadata to detect architecture and config

‎src/mobius/__main__.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,13 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
605605

606606
mmproj_path = getattr(args, "mmproj", None)
607607
keep_quantized = not args.dequantize
608+
reuse_gguf_weights = args.reuse_gguf_weights
609+
if reuse_gguf_weights and args.runtime == "ort-genai":
610+
raise SystemExit(
611+
"Error: --reuse-gguf-weights cannot be combined with --runtime ort-genai "
612+
"because genai_config.json cannot require disabled ORT constant folding. "
613+
"Use direct ONNX Runtime with ORT_DISABLE_ALL."
614+
)
608615

609616
if keep_quantized:
610617
print("Preserving supported GGUF quantization (float-only inputs stay float)...")
@@ -632,6 +639,7 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
632639
execution_provider=args.execution_provider,
633640
static_cache=args.static_cache,
634641
max_seq_len=args.max_seq_len,
642+
reuse_gguf_weights=reuse_gguf_weights,
635643
)
636644

637645
if args.release:
@@ -1183,6 +1191,15 @@ def build_parser() -> argparse.ArgumentParser:
11831191
action="store_true",
11841192
help="Dequantize all GGUF weights to float instead of preserving quantization.",
11851193
)
1194+
gguf_parser.add_argument(
1195+
"--reuse-gguf-weights",
1196+
action="store_true",
1197+
help=(
1198+
"Reuse compatible tensor byte ranges directly from the original GGUF. "
1199+
"The GGUF must be a real file in the flat output directory; converted "
1200+
"weights are written to model.onnx.data."
1201+
),
1202+
)
11861203
gguf_parser.add_argument(
11871204
"--runtime",
11881205
choices=["ort-genai", "onnx-genai"],

‎src/mobius/_model_package.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ def __init__(
9393
) -> None:
9494
super().__init__(models or {})
9595
self.config = config
96+
# Optional persistence policy attached by the GGUF importer.
97+
self.gguf_reuse_plan: Any = None
9698
self.policy_components = dict(policy_components or {})
9799
self.adapter_target_manifest = adapter_target_manifest
98100
self.adapter_service_options = adapter_service_options or AdapterServiceOptions()
@@ -202,13 +204,27 @@ def save(
202204
)
203205
if max_workers <= 0:
204206
raise ValueError(f"max_workers must be positive, got {max_workers}.")
207+
reuse_plan = getattr(self, "gguf_reuse_plan", None)
208+
if reuse_plan is not None:
209+
if external_data != "onnx":
210+
raise ValueError(
211+
"GGUF weight reuse requires external_data='onnx'; safetensors "
212+
"cannot preserve arbitrary GGUF byte ranges."
213+
)
214+
if max_shard_size_bytes is not None:
215+
raise ValueError(
216+
"GGUF weight reuse writes one converted-weight sidecar and does "
217+
"not support max_shard_size_bytes."
218+
)
205219
os.makedirs(directory, exist_ok=True)
206220
selected = {
207221
name: model
208222
for name, model in self.data.items()
209223
if components is None or components(name)
210224
}
211225
use_subfolders = len(selected) > 1
226+
if reuse_plan is not None and (len(selected) != 1 or use_subfolders):
227+
raise ValueError("GGUF weight reuse currently supports one flat ONNX model only.")
212228

213229
for name, model in selected.items():
214230
callback = _make_progress_callback() if progress_bar else None
@@ -221,7 +237,16 @@ def save(
221237
model_dir = directory
222238
path = os.path.join(model_dir, "model.onnx")
223239
with _namespaced_symbolic_dimensions(model, f"component.{name}") as saved_model:
224-
if external_data == "safetensors":
240+
if reuse_plan is not None:
241+
from mobius.integrations.gguf._reuse import save_reuse_package
242+
243+
save_reuse_package(
244+
saved_model,
245+
path,
246+
reuse_plan,
247+
callback=callback,
248+
)
249+
elif external_data == "safetensors":
225250
ir.save_safetensors(
226251
saved_model,
227252
path,
@@ -238,6 +263,13 @@ def save(
238263
save_kwargs["max_workers"] = max_workers
239264
ir.save(saved_model, path, **save_kwargs)
240265

266+
if reuse_plan is None:
267+
# Re-saving a loaded reuse package through the ordinary saver copies
268+
# all weights into ONNX external data, so any old reuse manifest in
269+
# the destination would become a false provenance claim.
270+
stale_reuse_manifest = os.path.join(directory, "gguf-reuse.json")
271+
if os.path.isfile(stale_reuse_manifest):
272+
os.remove(stale_reuse_manifest)
241273
if include_policy_components:
242274
self.save_policy_components(directory, check_weights=check_weights)
243275
if include_adapter_artifacts:
@@ -594,6 +626,8 @@ def apply_weights(
594626
self,
595627
state_dict: dict[str, torch.Tensor],
596628
prefix_map: dict[str, str] | None = None,
629+
*,
630+
fold_constants: bool = True,
597631
) -> None:
598632
"""Apply weights from a state dict across component models.
599633
@@ -655,6 +689,9 @@ def apply_weights(
655689

656690
_log_weight_mapping(state_dict, applied)
657691

692+
if not fold_constants:
693+
return
694+
658695
# Fold constants now that weights have been loaded.
659696
# PackQKV emits Concat(w_q, w_k, w_v) in the graph; those nodes can only
660697
# be constant-folded once the weight tensors carry their const_value.

‎src/mobius/integrations/gguf/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
preflight_hf_gguf,
4646
preflight_local_gguf,
4747
)
48+
from mobius.integrations.gguf._reuse import verify_gguf_reuse_manifest
4849
from mobius.integrations.gguf._runtime_package import write_gguf_runtime_package
4950
from mobius.integrations.gguf._shard_set import (
5051
GgufShardError,
@@ -60,6 +61,7 @@
6061
"build_gemma4_vlm_from_gguf",
6162
"write_gguf_runtime_package",
6263
"write_gguf_tokenizer_json",
64+
"verify_gguf_reuse_manifest",
6365
# Multi-shard GGUF import
6466
"GgufShardSet",
6567
"GgufShardManifest",

0 commit comments

Comments
 (0)