Skip to content

Commit cc40cd7

Browse files
justinchubyCopilot
andauthored
Allow GGUF export with deferred tokenizers (#693)
## Summary - Preserve proven GGUF model and runtime/config components when an authoritative tokenizer route is deferred or blocked. - Emit exactly one structured tokenizer warning with route, blocker category, evidence ID, exact recorded reason, impact, and remediation; never publish unverified tokenizer assets. - Persist generic component `support_status`, `export_status`, and `runtime_validation_status` in `export_report.json`. - Keep architecture, config, tensor closure, graph, qtype, source identity, I/O, malformed known metadata, and unexpected failures fail-closed. ## Final blocker evidence - **Tokenizer field closure:** Complete and incomplete paths accept only exact consumed/extension allowlists plus `tokenizer.chat_template.*`. Unknown/near-miss fields defer as `unsupported-tokenizer-metadata-fields`; malformed known fields remain fatal even when unknown fields coexist. - **Incomplete tokenizer safety:** Present model/`pre`, embedded JSON, RWKV, token list, types/scores/merges, special IDs, booleans, suppress/charsmap, and chat templates validate before downgrade. Tokenless special IDs fail; only `mask_token_id` on recognized masked-diffusion architectures is left to the graph contract. - **MTP tokenizer safety:** Deferred/blocked MTP routes never copy or pass through unevidenced tokenizer repositories. Only runtime evidence or validated embedded materialization writes tokenizer assets; faithful runtime config remains exported. - **Reuse metadata lifecycle:** The rollback journal always manages/removes stale draft, export, and quantization reports across sidecar variants. Failed reruns restore the complete prior graph/report set. - **Final-byte runtime identity:** Evidence matching occurs after final export/compatibility/MTP status bytes. Pre-report evidence is explicitly legacy/non-validating until regenerated final-package hashes exist. - **Atomic publication:** Report-bearing normal saves use sibling staging and atomic no-replace publication; graph/report/draft/permission/concurrent-destination failures leave no stale output. MTP status and reuse remain non-duplicated transactional surfaces. ## Validation - Final MTP/tokenizer regressions: **116 passed, 15 deselected**. - #696 audio-projector affected gate: **428 passed, 453 deselected**. - Final broad serial suite on exact base: **9,471 passed, 64 skipped, 12 deselected, 1 subtest passed**. - Generated GGUF docs, full initialized `lintrunner`, and diff check: clean. - New disposition/runtime modules: targeted mypy clean. - Broad mypy exact-base comparison: branch **3,768** vs base **3,804** existing diagnostics; **0 normalized new errors**. - Multiple independent medium-effort reviews completed; final MTP/mask review reported no findings. - GitHub review threads: **1 total, 0 unresolved**. ## Publication preflight - Clean worktree and matching remote head. - Session artifacts: **0 bytes retained**. Completed exact-base mypy worktrees/logs were deleted; no downloaded GGUF/ONNX/package payloads or scratch caches remain. - Lease push completed after conflict-free semantic rebase onto #696. - All commits contain `Signed-off-by` and required Copilot `Co-authored-by` trailers. GPG signing was unavailable because `gpg` is not installed. - CI is intentionally not monitored and this PR is not being merged by this session. ## Exact revisions - Base: `82e31222c9dbc08d2ea825fd6265498f0f594019` - Head: `960beeddec616d10d83f5bebe0ecd157a64ff199` --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 82e3122 commit cc40cd7

22 files changed

Lines changed: 3056 additions & 278 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ package.save("output")
2828
```
2929

3030
`keep_quantized=True` requests quantized target storage where supported; it does
31-
not guarantee source byte or numerical fidelity. Mobius classifies qtypes before
32-
payload conversion, emits one aggregate warning for lossy requantization, and
33-
saves the typed result as `quantization_report.json`. Use
34-
`keep_quantized=False` for explicit float import.
31+
not guarantee source fidelity. An authoritative tokenizer blocker does not invalidate
32+
a proven graph: the API returns the model, emits one structured warning, omits assets,
33+
and persists the exact component disposition in `export_report.json`. Lossy qtype
34+
conversion remains in `quantization_report.json`; use `keep_quantized=False` for float.
3535

3636
Packed MatMulNBits storage may use a native op or portable nibble unpack,
3737
`DequantizeLinear`, and float `MatMul`; neither implies dense storage or a specific kernel.
@@ -59,12 +59,15 @@ build_from_gguf(
5959
)
6060
```
6161

62-
The function returns a `ModelPackage`. Import validates architecture metadata, exact tensor
63-
closure, shapes, qtypes, and selected graph route before publication. Source reuse requires
64-
the original immutable GGUF at runtime. Runtime packages additionally require an exact
65-
artifact, graph, tokenizer, runtime version, parity proof, and deterministic state/generation
66-
evidence match.
67-
Processor-owned `image_token_id` overrides are forwarded unchanged for `mmproj=` packages.
62+
The function returns a `ModelPackage`. Mobius-side graph/semantic inability, corruption,
63+
identity, I/O, malformed tokenizer, and unexpected errors remain fail-closed. Authoritative
64+
tokenizer blockers become partial exports with exact reasons and no unverified assets.
65+
Downstream runtime, version, registry, or executor limitations preserve the accurate model
66+
package and record distinct `export_status` and `runtime_validation_status` fields instead of
67+
blocking export. Only exact artifact, graph, tokenizer, version, parity, and state evidence
68+
covering the final directory bytes (including `export_report.json` and
69+
`runtime_compatibility.json`) marks a package validated and end-to-end runnable. Existing
70+
pre-report runtime evidence remains unvalidated until its final-package hashes are regenerated.
6871

6972
Use `build_mmproj_from_gguf("mmproj.gguf", projector_type=..., target_architecture=...)`
7073
to export a registry-evidenced standalone `vision_encoder`, `audio_encoder`, or

‎src/mobius/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
"CausalLMConfig",
2323
"CausalLMTask",
2424
"ComponentInfo",
25+
"ComponentExportDisposition",
26+
"ComponentExportReport",
2527
"DepthAnythingConfig",
2628
"EncoderConfig",
2729
"EpCapabilities",
@@ -108,6 +110,7 @@
108110
)
109111
from mobius._constants import OPSET_VERSION
110112
from mobius._execution_providers import EpCapabilities, ep_registry, get_ep, register_ep
113+
from mobius._export_report import ComponentExportDisposition, ComponentExportReport
111114
from mobius._inspect import ComponentInfo, inspect_components
112115
from mobius._model_package import ModelPackage
113116
from mobius._optimizations import optimize_model

‎src/mobius/__main__.py‎

Lines changed: 82 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -663,12 +663,6 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
663663
mmproj_path = getattr(args, "mmproj", None)
664664
keep_quantized = not args.dequantize
665665
reuse_gguf_weights = args.reuse_gguf_weights
666-
if reuse_gguf_weights and args.runtime == "ort-genai":
667-
raise SystemExit(
668-
"Error: --reuse-gguf-weights cannot be combined with --runtime ort-genai "
669-
"because genai_config.json cannot require disabled ORT constant folding. "
670-
"Use direct ONNX Runtime with ORT_DISABLE_ALL."
671-
)
672666

673667
if keep_quantized:
674668
print(
@@ -713,6 +707,8 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
713707
from mobius.integrations.gguf._shard_set import open_gguf_model
714708

715709
# Resolve and validate the exact selected source before graph construction.
710+
# Authoritative tokenizer blockers may later produce a clearly reported
711+
# partial package; all model and source checks still fail closed here.
716712
resolved_gguf_path = _resolve_gguf_path(gguf_path)
717713
gguf_model = open_gguf_model(resolved_gguf_path)
718714
_validate_gguf_model(gguf_model, source=str(resolved_gguf_path))
@@ -749,7 +745,8 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
749745
strip_debug_metadata(model)
750746

751747
if runtime is None:
752-
os.makedirs(output_dir, exist_ok=True)
748+
if getattr(pkg, "export_report", None) is None:
749+
os.makedirs(output_dir, exist_ok=True)
753750
pkg.save(
754751
output_dir,
755752
external_data=args.external_data,
@@ -759,6 +756,7 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
759756
max_workers=args.max_workers,
760757
)
761758
_print_saved_gguf_models(pkg, output_dir)
759+
_print_gguf_export_status(pkg, output_dir, runtime=runtime)
762760

763761
# ModelPackage.save() persisted the MTP sidecar into its manifest-selected
764762
# collision-safe directory.
@@ -772,9 +770,12 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
772770

773771
draft_manifest = getattr(pkg, "draft_manifest", None)
774772
if draft_manifest is not None:
775-
from mobius.integrations.gguf._draft import write_draft_manifest
773+
if getattr(pkg, "export_report", None) is None:
774+
from mobius.integrations.gguf._draft import write_draft_manifest
776775

777-
manifest_path = write_draft_manifest(draft_manifest, output_dir)
776+
manifest_path = write_draft_manifest(draft_manifest, output_dir)
777+
else:
778+
manifest_path = os.path.join(output_dir, "draft_manifest.json")
778779
print(f"Saved draft pairing manifest to {manifest_path}")
779780

780781
if runtime in ("onnx-genai", "ort-genai"):
@@ -795,11 +796,20 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
795796
),
796797
max_workers=args.max_workers,
797798
)
798-
# The writer returns only after atomically publishing the complete graph,
799-
# tokenizer, and runtime configuration directory.
799+
# The writer atomically publishes either the validated runtime package or
800+
# an accurate model package with an explicit unvalidated disposition.
800801
_print_saved_gguf_models(pkg, output_dir)
801802
for name, path in artifacts.items():
802803
print(f" {name}: {path}")
804+
from mobius._export_report import ComponentExportReport
805+
806+
if isinstance(getattr(pkg, "export_report", None), ComponentExportReport):
807+
_print_gguf_export_status(pkg, output_dir, runtime=runtime)
808+
else:
809+
print(
810+
f"Export status: COMPLETE - {runtime} package is end-to-end runnable "
811+
"under its pinned evidence contract."
812+
)
803813

804814

805815
def _print_saved_gguf_models(pkg: Any, output_dir: str) -> None:
@@ -814,6 +824,59 @@ def _print_saved_gguf_models(pkg: Any, output_dir: str) -> None:
814824
print(f"Saved {name} to {path}")
815825

816826

827+
def _print_gguf_export_status(
828+
pkg: Any,
829+
output_dir: str,
830+
*,
831+
runtime: str | None,
832+
) -> None:
833+
"""Distinguish a durable partial package from a complete runtime package."""
834+
from mobius._export_report import ComponentExportReport
835+
836+
report = getattr(pkg, "export_report", None)
837+
if not isinstance(report, ComponentExportReport):
838+
print(
839+
"Export status: MODEL ONLY - ONNX model files were saved; "
840+
"runtime/tokenizer packaging was not requested."
841+
)
842+
return
843+
omitted = ", ".join(
844+
component.name for component in report.components if component.output == "omitted"
845+
)
846+
if report.export_status == "partial":
847+
if omitted:
848+
print(
849+
"Export status: PARTIAL - proven model files were saved, but one or more "
850+
"components were omitted."
851+
)
852+
else:
853+
print(
854+
"Export status: PARTIAL - all requested components were exported, but "
855+
"one or more support dispositions remain deferred or blocked."
856+
)
857+
else:
858+
print("Export status: COMPLETE - the accurate model package was saved.")
859+
if report.runtime_validation_status == "unvalidated":
860+
print(
861+
"Runtime validation: UNVALIDATED - export success is not a runtime "
862+
"support or end-to-end execution claim."
863+
)
864+
elif report.runtime_validation_status == "validated":
865+
print("Runtime validation: VALIDATED - the package is end-to-end runnable.")
866+
runtime_component = report.component("runtime")
867+
if (
868+
runtime is not None
869+
and runtime_component is not None
870+
and runtime_component.output == "omitted"
871+
):
872+
print(f" requested runtime: {runtime} (omitted)")
873+
elif runtime is not None and report.runtime_validation_status == "unvalidated":
874+
print(f" requested runtime: {runtime} (unvalidated)")
875+
if omitted:
876+
print(f" omitted components: {omitted}")
877+
print(f" export report: {os.path.join(output_dir, 'export_report.json')}")
878+
879+
817880
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
818881
"""Execute the 'convert-comfyui' subcommand."""
819882
from mobius.integrations.onnx_genai import convert_comfyui_workflow
@@ -1353,9 +1416,10 @@ def build_parser() -> argparse.ArgumentParser:
13531416
choices=["ort-genai", "onnx-genai"],
13541417
default=None,
13551418
help=(
1356-
"Generate runtime-specific config files after building. "
1357-
"Both routes require an exact tokenizer.huggingface.json embedded in "
1358-
"the GGUF; opaque tokenizer.ggml.pre metadata is not reconstructed. "
1419+
"Request runtime-specific packaging after building. Exact evidence emits "
1420+
"a validated runtime config and tokenizer; downstream runtime/version/"
1421+
"registry/executor limitations preserve the model with an unvalidated "
1422+
"export report instead of blocking it. "
13591423
"'onnx-genai' writes inference_metadata.yaml and 'ort-genai' writes "
13601424
"genai_config.json."
13611425
),
@@ -1364,8 +1428,8 @@ def build_parser() -> argparse.ArgumentParser:
13641428
"--runtime-version",
13651429
default=None,
13661430
help=(
1367-
"Exact selected runtime version. Required once an architecture has a "
1368-
"runtime-supported evidence record; it must equal the version validated there."
1431+
"Selected runtime version. An exact evidence match marks the package "
1432+
"validated; other versions are exported with runtime status unvalidated."
13691433
),
13701434
)
13711435
gguf_parser.add_argument(
@@ -1374,7 +1438,8 @@ def build_parser() -> argparse.ArgumentParser:
13741438
metavar="OWNER/REPO",
13751439
help=(
13761440
"Exact Hugging Face repository containing tokenizer assets for runtime "
1377-
"packaging. Requires --tokenizer-revision and must match runtime evidence."
1441+
"packaging. Requires --tokenizer-revision. Missing or unmatched evidence "
1442+
"preserves a model-only runtime-unvalidated package."
13781443
),
13791444
)
13801445
gguf_parser.add_argument(

0 commit comments

Comments
 (0)