Skip to content

Commit 027fd42

Browse files
justinchubyCopilot
andauthored
Prove DFlash and EAGLE3 GGUF draft runtime (#695)
## Summary - Add exact target/draft GGUF pair construction with separate cache namespaces, target hidden-state outputs, shared embedding/LM-head bridges, atomic package publication, and self-verifying graph identities. - Add a direct ONNX Runtime greedy coordinator for DFlash and EAGLE3 with accepted-prefix verification, target/draft cache rollback, compressed-vocabulary remapping, strict output-capacity bounds, and target-only baseline comparison. - Add a separate test-only direct ORT oracle that imports neither `DraftPairRunner` nor production transition helpers, derives target-layer/remap/block/mask contracts from raw immutable GGUF metadata, and compares production behavior against independently recorded transitions. - Make EAGLE3 consume real draft-owned embeddings, normalize GGUF/HuggingFace hidden-state indices correctly, and preserve fully-owned cross-width variants. - Semantically rebase onto exact current `main` at `d68f66418096e0fe9a073764b819d6898de314de`, integrating #696, #693, and #691 while retaining shared MTP cache/publication/status infrastructure without duplication. - Keep higher-level runtime compatibility advisory; no production revision pin or downstream runtime gate is added. ## Immutable evidence Evidence is bound in `testdata/evidence/gguf_draft_runtime_evidence.json` (13,293,887,389 bytes total, below the 16 GiB cap), including artifact/config/tokenizer/source/graph/package/runtime hashes. Separate SHA-256-bound independent traces record every proposal ID/remapped token and proposal-logit digest, posterior/accepted prefix/correction, target verification/replay logits and tokens, target/draft cache lengths and tensor digests before/tentative/committed/replay states, final cache states, exact counters, and the explicit batch-size-one reorder disposition. - **DFlash:** `Qwen/Qwen3-4B-GGUF@bc640142...` + `AtomicChat/Qwen3-4B-DFlash-GGUF@b53c7de6...`; 32/32 direct-ORT greedy tokens equal target-only, 18/75 proposals accepted, 3 multi-token rounds, 5 rejected-suffix rollbacks. Independent full-tensor Q8 source comparison: cosine `0.999879`, relative L2 `0.005406`. - **EAGLE3:** `Qwen/Qwen3-8B-GGUF@7c41481f...` + `williamliao/Qwen3-8B-EAGLE3-Speculator-GGUF@44480ff4...`; 32/32 direct-ORT greedy tokens equal target-only, 20/43 proposals accepted, 7 multi-token rounds, 10 rejected-suffix rollbacks. Independent pinned llama.cpp conversion matches all 15 tensor names, qtypes, shapes, and values exactly. - Pinned llama.cpp additionally exercised the real acceptance loops with 49/114 DFlash and 45/85 EAGLE3 accepted tokens. - Four mutations now alter execution before validation: wrong mapping/order is fed through target verification, draft-cache corruption is threaded into the next round, and target rollback corruption is replayed against full committed history. Each fails its distinct semantic invariant. Target Q4_K/Q6_K imports truthfully report lossy INT4 affine block-32 repacking; target-only and speculative comparisons use the same repacked target graph. Every target replay starts from an empty cache and rebuilds the complete prompt plus committed token history. Quantized batched verification and full-history replay can differ numerically, so both states are bound and maximum absolute differences are recorded (DFlash `1.967625`, EAGLE3 `0.912386`) while replay argmax tokens must match exactly. Draft replay likewise reconstructs the complete committed history from empty state. Production DFlash uses target-only tail generation when fewer than one fixed block remains; EAGLE3 caps each final proposal width to `remaining - 1`. Parametric tests prove target sessions, caches, and counters never process beyond requested `max_new_tokens` for remaining capacity 1 through width+1. The reference coordinator is batch-size 1 and truthfully reports beam/reorder unsupported. Higher-level execution remains `runtime_unvalidated` without gating export. ## Validation - Final exact-main broad non-integration suite: 9,668 passed, 64 skipped, 1 subtest passed. - Final affected draft+MTP+CLI/evidence/docs/census suite: 302 passed, 2 real-artifact probes skipped by opt-in. - Both immutable real-artifact probes were rerun after the three blocker fixes; all eight execution-mutating discriminator runs failed at their expected semantic invariants. - Pinned Ruff format/lint, generated GGUF docs, and focused isolated mypy passed. `_config_mapping.py` retains three unrelated pre-existing mypy errors outside the DFlash change. - Final medium review specifically verified execution-mutating discriminators, complete empty-cache target replay, bounded final-round production behavior, DFlash mask metadata propagation, and semantic #693/#691 conflict resolution; no significant findings remain. No CI monitoring or merge is requested. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent d68f664 commit 027fd42

34 files changed

Lines changed: 3821 additions & 104 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 8 additions & 4 deletions
Large diffs are not rendered by default.

‎docs/cli_reference.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ mobius build-gguf GGUF_PATH --output OUTPUT_DIR [options]
398398
| `--runtime-version VERSION` | Exact selected runtime version. Once runtime support exists, this must equal the version in the matching evidence record; compatible-version ranges are not inferred. |
399399
| `--mmproj PATH` | Exact companion `clip` GGUF. Pairing validates source identity, target architecture, modality, tensor closure, and dimensions before graph construction. |
400400
| `--target-config PATH` | Exact target config directory for `dflash`/`eagle3`; requires the adjacent complete `tokenizer.json` and emits a target-binding draft manifest. |
401+
| `--target-gguf PATH` | Exact target GGUF for a `dflash`/`eagle3` pair; emits target/draft graphs, cache namespaces, required shared-weight bridges, and `runtime_unvalidated` manifest/status metadata. |
401402
| `--release` | Strip build-time debug and provenance metadata before saving while preserving functional `mobius.*` metadata. |
402403
| `--static-cache` | Build a fixed-width cache where supported. |
403404
| `--max-seq-len N` | Set the fixed cache length; requires `--static-cache`. |

‎src/mobius/__main__.py‎

Lines changed: 76 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,10 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
678678
gguf_reference = gguf_path
679679
output_dir = args.output_dir
680680
target_config = getattr(args, "target_config", None)
681+
target_gguf = getattr(args, "target_gguf", None)
681682
runtime = getattr(args, "runtime", None)
683+
draft_pair = target_gguf is not None
684+
requested_pair_runtime = runtime if draft_pair else None
682685

683686
if args.max_seq_len is not None and not args.static_cache:
684687
raise SystemExit("Error: --max-seq-len can only be used with --static-cache.")
@@ -688,18 +691,25 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
688691
raise SystemExit("Error: --max-workers must be a positive integer.")
689692
if mmproj_path is not None and args.static_cache:
690693
raise SystemExit("Error: --static-cache cannot be used with --mmproj.")
694+
if draft_pair and target_config is None:
695+
raise SystemExit("Error: --target-gguf requires --target-config.")
696+
if draft_pair and (mmproj_path is not None or args.static_cache or reuse_gguf_weights):
697+
raise SystemExit(
698+
"Error: --target-gguf cannot be combined with --mmproj, --static-cache, "
699+
"or --reuse-gguf-weights."
700+
)
691701
tokenizer_repository = getattr(args, "tokenizer_repository", None)
692702
tokenizer_revision = getattr(args, "tokenizer_revision", None)
693703
if (tokenizer_repository is None) != (tokenizer_revision is None):
694704
raise SystemExit(
695705
"Error: --tokenizer-repository and --tokenizer-revision must be provided together."
696706
)
697-
if runtime is None and tokenizer_repository is not None:
707+
if (runtime is None or draft_pair) and tokenizer_repository is not None:
698708
raise SystemExit(
699709
"Error: pinned tokenizer materialization is only available with --runtime."
700710
)
701711

702-
if runtime is not None:
712+
if runtime is not None and not draft_pair:
703713
from mobius.integrations.gguf._builder import (
704714
_resolve_gguf_path,
705715
_validate_gguf_model,
@@ -726,35 +736,65 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
726736
"Error: --tokenizer-revision must be an immutable 40-hex commit SHA."
727737
)
728738

729-
pkg = build_from_gguf(
730-
gguf_reference,
731-
mmproj=mmproj_path,
732-
image_token_id=args.image_token_id,
733-
dtype=args.dtype,
734-
keep_quantized=keep_quantized,
735-
execution_provider=args.execution_provider,
736-
static_cache=args.static_cache,
737-
max_seq_len=args.max_seq_len,
738-
reuse_gguf_weights=reuse_gguf_weights,
739-
target_config=target_config,
740-
_gguf_model=gguf_model if runtime is not None else None,
741-
)
739+
if draft_pair:
740+
from mobius.integrations.gguf import build_draft_pair_from_gguf
741+
742+
pkg = build_draft_pair_from_gguf(
743+
target_gguf,
744+
gguf_reference,
745+
target_config=target_config,
746+
dtype=args.dtype,
747+
keep_quantized=keep_quantized,
748+
execution_provider=args.execution_provider,
749+
)
750+
if runtime is not None:
751+
print(
752+
f"Warning: --runtime {runtime} does not claim downstream draft execution; "
753+
"saving the direct-ORT package with runtime=runtime_unvalidated."
754+
)
755+
runtime = None
756+
else:
757+
pkg = build_from_gguf(
758+
gguf_reference,
759+
mmproj=mmproj_path,
760+
image_token_id=args.image_token_id,
761+
dtype=args.dtype,
762+
keep_quantized=keep_quantized,
763+
execution_provider=args.execution_provider,
764+
static_cache=args.static_cache,
765+
max_seq_len=args.max_seq_len,
766+
reuse_gguf_weights=reuse_gguf_weights,
767+
target_config=target_config,
768+
_gguf_model=gguf_model if runtime is not None else None,
769+
)
742770

743771
if args.release:
744772
for model in pkg.values():
745773
strip_debug_metadata(model)
746774

747775
if runtime is None:
748-
if getattr(pkg, "export_report", None) is None:
749-
os.makedirs(output_dir, exist_ok=True)
750-
pkg.save(
751-
output_dir,
752-
external_data=args.external_data,
753-
max_shard_size_bytes=(
776+
save_kwargs = {
777+
"external_data": args.external_data,
778+
"max_shard_size_bytes": (
754779
_parse_size(args.max_shard_size) if args.max_shard_size else None
755780
),
756-
max_workers=args.max_workers,
757-
)
781+
"max_workers": args.max_workers,
782+
}
783+
if draft_pair:
784+
from mobius.integrations.gguf import write_draft_pair_package
785+
786+
artifacts = write_draft_pair_package(
787+
pkg,
788+
output_dir,
789+
requested_runtime=requested_pair_runtime,
790+
runtime_version=getattr(args, "runtime_version", None),
791+
**save_kwargs,
792+
)
793+
else:
794+
if getattr(pkg, "export_report", None) is None:
795+
os.makedirs(output_dir, exist_ok=True)
796+
pkg.save(output_dir, **save_kwargs)
797+
artifacts = {}
758798
_print_saved_gguf_models(pkg, output_dir)
759799
_print_gguf_export_status(pkg, output_dir, runtime=runtime)
760800

@@ -769,14 +809,16 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
769809
print(f"Saved mtp head to {os.path.join(output_dir, mtp_dir, 'model.onnx')}")
770810

771811
draft_manifest = getattr(pkg, "draft_manifest", None)
772-
if draft_manifest is not None:
812+
if draft_manifest is not None and not draft_pair:
773813
if getattr(pkg, "export_report", None) is None:
774814
from mobius.integrations.gguf._draft import write_draft_manifest
775815

776816
manifest_path = write_draft_manifest(draft_manifest, output_dir)
777817
else:
778818
manifest_path = os.path.join(output_dir, "draft_manifest.json")
779819
print(f"Saved draft pairing manifest to {manifest_path}")
820+
elif draft_pair:
821+
print(f"Saved draft pairing manifest to {artifacts['manifest']}")
780822

781823
if runtime in ("onnx-genai", "ort-genai"):
782824
from mobius.integrations.gguf import write_gguf_runtime_package
@@ -1411,6 +1453,16 @@ def build_parser() -> argparse.ArgumentParser:
14111453
"ordered vocabulary must exactly match the GGUF tokenizer."
14121454
),
14131455
)
1456+
gguf_parser.add_argument(
1457+
"--target-gguf",
1458+
default=None,
1459+
metavar="PATH",
1460+
help=(
1461+
"Exact target GGUF for a dflash/eagle3 pair. Emits target and draft "
1462+
"graphs, independent cache namespaces, required embedding/head bridges, "
1463+
"and a runtime_unvalidated direct-ORT manifest."
1464+
),
1465+
)
14141466
gguf_parser.add_argument(
14151467
"--runtime",
14161468
choices=["ort-genai", "onnx-genai"],

‎src/mobius/_configs/_base.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2649,10 +2649,12 @@ class Eagle3Config(CausalLMConfig):
26492649
eagle_aux_hidden_state_layer_ids: list[int] | None = None
26502650
target_layer_ids: list[int] | None = None
26512651
use_target_lm_head: bool = False
2652+
use_draft_token_embedding: bool = False
26522653

26532654
@classmethod
26542655
def from_transformers(cls, config, parent_config=None) -> Eagle3Config:
26552656
layer_cfg = getattr(config, "transformer_layer_config", None)
2657+
is_speculators_format = layer_cfg is not None
26562658
if layer_cfg is not None:
26572659
# speculators format: arch config nested under transformer_layer_config.
26582660
if isinstance(layer_cfg, dict):
@@ -2673,6 +2675,7 @@ def from_transformers(cls, config, parent_config=None) -> Eagle3Config:
26732675
eagle_aux_hidden_state_layer_ids=getattr(
26742676
config, "eagle_aux_hidden_state_layer_ids", None
26752677
),
2678+
use_draft_token_embedding=is_speculators_format,
26762679
)
26772680

26782681

‎src/mobius/_model_package.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,9 @@ class ModelPackage(UserDict[str, ir.Model]):
347347
mtp_head: Optional nested MTP sidecar package. :meth:`save` records its
348348
collision-free directory in an explicit package manifest, and
349349
:meth:`load` restores it automatically.
350+
draft_manifest: Optional target/draft orchestration and identity contract.
351+
draft_pair_quantization_reports: Per-component GGUF fidelity reports for a
352+
target-coupled draft package.
350353
"""
351354

352355
def __init__(
@@ -376,6 +379,13 @@ def __init__(
376379
self.gguf_reuse_plan: Any = None
377380
self.draft_manifest: Any = None
378381
self.mtp_head: ModelPackage | None = None
382+
self.draft_manifest: dict[str, Any] | None = None
383+
self.draft_config: object | None = None
384+
self.draft_pair_quantization_reports: dict[str, GGUFQuantizationReport | None] = {}
385+
self.gguf_architecture: str | None = None
386+
self.gguf_execution_provider: str | None = None
387+
self.gguf_source_path: str | None = None
388+
self.gguf_target_source_path: str | None = None
379389
self.policy_components = dict(policy_components or {})
380390
self.adapter_target_manifest = adapter_target_manifest
381391
self.adapter_service_options = adapter_service_options or AdapterServiceOptions()

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@
3939
GgufArchResolutionError,
4040
resolve_model_type,
4141
)
42+
from mobius.integrations.gguf._draft_pair import (
43+
build_draft_pair_from_gguf,
44+
write_draft_pair_package,
45+
)
46+
from mobius.integrations.gguf._draft_runtime import (
47+
DraftGenerationResult,
48+
DraftGenerationStats,
49+
DraftPairRunner,
50+
)
4251
from mobius.integrations.gguf._mmproj import (
4352
build_audio_projector_from_gguf,
4453
build_gemma3_vlm_from_gguf,
@@ -84,6 +93,11 @@
8493
__all__ = [
8594
"build_from_gguf",
8695
"build_audio_projector_from_gguf",
96+
"build_draft_pair_from_gguf",
97+
"write_draft_pair_package",
98+
"DraftGenerationResult",
99+
"DraftGenerationStats",
100+
"DraftPairRunner",
87101
"build_gemma3_vlm_from_gguf",
88102
"build_gemma4_vlm_from_gguf",
89103
"build_mmproj_from_gguf",

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -334,9 +334,10 @@
334334
_DRAFT_RUNTIME_VALIDATION_PENDING = (
335335
"This is a target-coupled speculative draft, never a standalone CausalLM. "
336336
"Config extraction, exact tensor closure, target shape/tokenizer validation, and "
337-
"synthetic draft execution are covered, but no pinned real GGUF pair has passed "
338-
"independent target+draft full-logit/proposed-token parity. Runtime packaging remains "
339-
"deferred until that evidence and an acceptance-loop integration exist."
337+
"synthetic draft execution are covered. Exact real target/draft pairs pass the direct "
338+
"ONNX Runtime acceptance loop with independent source/raw-GGUF evidence, cache rollback, "
339+
"multi-token acceptance, and target-only greedy equality. Use build_draft_pair_from_gguf; "
340+
"higher-level generation runtimes remain runtime_unvalidated and do not gate export."
340341
)
341342

342343
_POCKETTTS_BUNDLE_REASON = (

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import re
2323
import shutil
2424
from collections import Counter
25-
from collections.abc import Callable, Collection, Iterable, Mapping
25+
from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
2626
from dataclasses import asdict, dataclass
2727
from pathlib import Path, PurePosixPath
2828
from typing import TYPE_CHECKING, Any
@@ -6727,7 +6727,7 @@ def _serialize_route_graph_config(config: Any, gguf_arch: str) -> str:
67276727
def build_from_gguf(
67286728
gguf_path: str | Path,
67296729
*,
6730-
task: str | None = None,
6730+
task: str | ModelTask | None = None,
67316731
dtype: str | None = None,
67326732
keep_quantized: bool = True,
67336733
execution_provider: str = "default",
@@ -6738,6 +6738,7 @@ def build_from_gguf(
67386738
allow_dense_moe: bool | None = None,
67396739
reuse_gguf_weights: bool = False,
67406740
target_config: str | Path | Mapping[str, object] | None = None,
6741+
output_layer_indices: Sequence[int] | None = None,
67416742
_gguf_model: Any | None = None,
67426743
) -> ModelPackage:
67436744
"""Build an ONNX :class:`ModelPackage` from a GGUF file.
@@ -6819,6 +6820,9 @@ def build_from_gguf(
68196820
config mapping for a ``dflash``/``eagle3`` speculative draft. A
68206821
mapping must include the complete ``tokenizer_json`` object. Required for draft GGUFs
68216822
and rejected for standalone architectures.
6823+
output_layer_indices: Optional zero-based decoder layers to expose as
6824+
``hidden_states.{index}`` outputs. This is used by target-coupled
6825+
draft packages and leaves ordinary decoder exports unchanged.
68226826
68236827
Returns:
68246828
A :class:`ModelPackage` containing the built model(s).
@@ -7068,6 +7072,13 @@ def build_from_gguf(
70687072
logger.info("GGUF contains no mapped quantized weights; using the float import path")
70697073
# 2. Extract config from GGUF metadata
70707074
config = gguf_to_config(gguf_model)
7075+
if output_layer_indices is not None:
7076+
indices = list(output_layer_indices)
7077+
if any(type(index) is not int for index in indices):
7078+
raise TypeError("output_layer_indices must contain integers")
7079+
if len(set(indices)) != len(indices):
7080+
raise ValueError("output_layer_indices must not contain duplicates")
7081+
config.output_layer_indices = indices
70717082
spec = get_arch_spec(gguf_arch)
70727083
from mobius.integrations.gguf._draft import (
70737084
is_draft_architecture,
@@ -7611,6 +7622,9 @@ def combine_mtp_report(mtp_report) -> None:
76117622
prefix_map=prefix_map,
76127623
fold_constants=not reuse_gguf_weights,
76137624
)
7625+
bind_shared_initializers = getattr(resolved_task, "bind_shared_initializers", None)
7626+
if callable(bind_shared_initializers):
7627+
bind_shared_initializers(pkg)
76147628
if reuse_gguf_weights:
76157629
from mobius.integrations.gguf._reuse import attach_reused_initializers
76167630

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4896,6 +4896,7 @@ def _dflash_postprocess(
48964896
vocab_size=len(metadata.get("tokenizer.ggml.tokens", ())),
48974897
target_layer_ids=target_layers,
48984898
block_size=int(metadata["dflash.block_size"]),
4899+
mask_token_id=int(metadata["tokenizer.ggml.mask_token_id"]),
48994900
num_target_layers=None,
49004901
draft_vocab_size=draft_vocab,
49014902
use_draft_lm_head="output.weight" in model.tensor_names,
@@ -4910,7 +4911,15 @@ def _eagle3_postprocess(
49104911
) -> Eagle3Config:
49114912
from mobius._configs import Eagle3Config
49124913

4913-
target_layers = [int(value) for value in metadata["eagle3.target_layers"]]
4914+
target_hidden_state_indices = [int(value) for value in metadata["eagle3.target_layers"]]
4915+
if any(index <= 0 for index in target_hidden_state_indices):
4916+
raise ValueError(
4917+
"eagle3.target_layers must use positive HuggingFace hidden-state indices"
4918+
)
4919+
# GGUF stores HuggingFace hidden_states[k] indices (and llama.cpp reads
4920+
# layer-input k). Mobius captures decoder layer outputs, so hidden_states[k]
4921+
# is output_layer_indices[k - 1].
4922+
target_layers = [index - 1 for index in target_hidden_state_indices]
49144923
raw_shapes = {name: shape for name, _raw, _qtype, shape in model.tensor_items_raw()}
49154924
target_vocab = len(metadata.get("tokenizer.ggml.tokens", ()))
49164925
draft_vocab = int(raw_shapes["d2t"][0]) if "d2t" in raw_shapes else target_vocab
@@ -4927,6 +4936,7 @@ def _eagle3_postprocess(
49274936
norm_before_fc=bool(metadata.get("eagle3.norm_before_fc")),
49284937
fc_norm=False,
49294938
use_target_lm_head="output.weight" not in model.tensor_names,
4939+
use_draft_token_embedding="token_embd.weight" in model.tensor_names,
49304940
)
49314941
return Eagle3Config(**fields)
49324942

0 commit comments

Comments
 (0)