Skip to content

Commit aecebbc

Browse files
justinchubyCopilot
andauthored
Add target-coupled draft GGUF cohort (#583)
## Summary - add pinned llama.cpp `dflash` and `eagle3` GGUF import as target-coupled speculative draft auxiliaries, never standalone CausalLMs - validate target dimensions, selected hidden-state layers, exact ordered vocabulary and special IDs, suffix-exact tensor closure, Q/K conversion, quantization sidecars, and I64 draft-to-target remaps before graph construction - emit `draft_manifest.json` with the target config hash, ordered-token vocabulary hash, draft/target shapes, output ownership, cache ownership, and compact-logit remap contract - keep runtime support deferred pending an independently verified real target+draft parity loop ## Explicit pairing contract ```bash mobius build-gguf draft.gguf \ --target-config /path/to/exact-target/ \ --output output/draft/ ``` `--target-config` accepts the exact target directory or `config.json`; the adjacent `tokenizer.json` is mandatory. The Python API also accepts an explicit mapping with `tokenizer_tokens`. File inputs record SHA-256 over the exact config bytes; mapping inputs record SHA-256 over canonical sorted JSON. The manifest separately records SHA-256 over the ordered token strings. These hashes identify the validated config/token-ID contract, not target weights; the caller must attest and pair the exact target weight revision. Draft builds reject `task="text-generation"`, static-cache export, and `write_gguf_runtime_package`. They only save an auxiliary ONNX graph plus `draft_manifest.json`. Missing target heads/embeddings are exposed as explicit target-owned graph inputs/outputs rather than duplicated or synthesized. ## Real-artifact evidence - DFlash: `lym00/Qwen3-4B-DFlash-GGUF-Test@9d2ec464a15346d8a7d7a696c06694eb1bf690b5`, `Qwen3-4B-DFlash-q8_0.gguf`, 577,047,072 bytes, LFS SHA-256 `5ecf02bb269fc42277f43961794387fea11ecc367ea2d99e86b2b71cc249aff6`, paired target `Qwen/Qwen3-4B@1cfa9a7208912126459214e8b04321603b3df60c`. Its 58-tensor header uses post-pin `hidden_norm.weight`, so pinned suffix closure rejects it. - EAGLE-3: `williamliao/Qwen3-8B-EAGLE3-Speculator-GGUF@44480ff4ea6330788818f7f5fc9a69b326dc4c06`, `Qwen3-8B-speculator.eagle3-F16.gguf`, 2,049,930,400 bytes, LFS SHA-256 `d6cf1f3cf29e9cd72c02fb11f989f5192f2b24e142741fdc2de8cd590140f2f2`, paired target `Qwen/Qwen3-8B@b968826d9c46dd6066d109eabc6255188de91218`. Its 15-tensor header contains a draft-owned embedding, which the external-embedding graph rejects rather than dropping. Neither artifact was executed. No suitably small real pair satisfies this pinned contract, so runtime remains **DEFERRED** until independent target/draft full-logit and multi-step proposed-token parity exists. ## Validation - focused draft/registry/mapping/runtime/model tests: 532 passed - broad non-integration suite excluding the known unrelated `glm_moe_dsa` shape-inference regression: 5903 passed, 52 skipped - unfiltered broad run: 5922 passed, 52 skipped, with only the two existing `glm_moe_dsa` missing-output-shape/checker failures - `lintrunner f --output oneline --all-files` - bug-focused review covered target assumptions, layer indexing, tokenizer/remap semantics, cache and hidden-state contracts, dropped tensors, standalone dispatch, Q/K permutation, and quantization misuse --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: 332e47ee-0b3a-4f7d-8c81-cb7be2123f98
1 parent 46aec39 commit aecebbc

19 files changed

Lines changed: 1899 additions & 53 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def build_from_gguf(
2323
static_cache: bool = False,
2424
max_seq_len: int | None = None,
2525
reuse_gguf_weights: bool = False,
26+
target_config: str | Path | Mapping[str, object] | None = None,
2627
) -> ModelPackage:
2728
```
2829

@@ -39,6 +40,7 @@ def build_from_gguf(
3940
| `static_cache` | `bool` | `False` | Build a fixed-width KV cache when the architecture supports it. |
4041
| `max_seq_len` | `int \| None` | `None` | Static-cache sequence limit. |
4142
| `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. |
43+
| `target_config` | `str \| Path \| Mapping[str, object] \| None` | `None` | Exact target directory/config plus `tokenizer.json`, or an explicit config mapping with the complete `tokenizer_json` object. Required only for `dflash` and `eagle3`. |
4244

4345
## Returns
4446

@@ -109,6 +111,11 @@ weight buffer and consume startup or execution time. The package avoids a second
109111
on-disk copy; peak runtime memory and performance remain transform- and
110112
execution-provider-dependent.
111113

114+
```bash
115+
# Draft GGUFs require the exact target config and tokenizer directory
116+
mobius build-gguf draft.gguf --target-config target/ --output output/draft/
117+
```
118+
112119
## Behavior
113120

114121
1. Reads GGUF metadata to detect architecture and config
@@ -153,7 +160,9 @@ reason.
153160
| `cohere2` | — | `cohere2` | runtime deferred | supported |
154161
| `deci` | — | `llama` | supported | supported |
155162
| `deepseek4` | — | `deepseek_v4` | supported | supported |
163+
| `dflash` | — | `DFlashDraftModel` | runtime deferred | supported |
156164
| `dream` | — | `dream` | runtime deferred | supported |
165+
| `eagle3` | — | `Eagle3DraftModel` | runtime deferred | supported |
157166
| `eurobert` | — | — | config deferred; tensor_map deferred; graph deferred; runtime deferred | unreachable |
158167
| `exaone` | — | `exaone` | runtime deferred | supported |
159168
| `falcon` | — | `falcon` | supported | supported |
@@ -200,14 +209,85 @@ reason.
200209
| `starcoder2` | — | `starcoder2` | supported | supported |
201210
| `t5` | — | `t5` | runtime deferred | supported |
202211
| `t5encoder` | — | `t5encoder` | runtime deferred | supported |
203-
204212
<!-- END GGUF SUPPORT MATRIX -->
205213

206214
Canonical names are the strings llama.cpp writes into `general.architecture`,
207215
validated against a vendored census of the 147 architectures llama.cpp defines
208216
at commit `8d9af256337d1a501250f9bbf4c0859a654bddd6`. Aliases are spellings
209217
llama.cpp does not emit but that mobius still accepts.
210218

219+
### Speculative draft GGUF contract
220+
221+
`dflash` and `eagle3` are auxiliary speculative-decoding models, never
222+
standalone causal language models. Both the API and CLI require an explicit
223+
`target_config`; `task="text-generation"`, static cache, and standalone runtime
224+
packaging are rejected. A successful build emits `draft_manifest.json` beside
225+
the ONNX graph. The manifest records canonical JSON SHA-256 values for the
226+
target config and complete tokenizer, a separate ordered-token vocabulary
227+
SHA-256, hidden/layer/vocabulary sizes, selected target layers, draft
228+
depth/head/intermediate/block sizes, output ownership, and any draft-to-target
229+
(`d2t`) vocabulary map. Canonical hashes are identical for equivalent file and
230+
mapping inputs and remain stable when a target directory is relocated; absolute
231+
host paths are not embedded.
232+
233+
The target tokenizer vocabulary must match the GGUF token list in exact ID
234+
order, and BOS/EOS/PAD IDs are checked when both sides declare them. This proves
235+
the token-ID contract, not equivalence of tokenizer normalization, pre-tokenizer,
236+
or merge behavior. The manifest identifies the exact config file or explicit
237+
mapping used for validation, but Mobius cannot derive a target weight revision
238+
from GGUF metadata. The caller must pair that manifest with the attested target
239+
weights; runtime support therefore remains **deferred**.
240+
241+
`config.json` and `tokenizer.json` are size-bounded, schema-checked UTF-8 JSON
242+
objects. Both resolved resources must remain in one target root; escaping or
243+
mixed-directory symlinks are rejected. Split `vocab.json`/`merges.txt` or
244+
`tokenizer.model` alternatives are not reconstructed because doing so would
245+
lose full normalizer, pre-tokenizer, and added-token semantics.
246+
247+
EAGLE-3 requires exactly three valid `eagle3.target_layers` and matching
248+
`eagle3.target_hidden_size`; target and draft hidden widths must currently match
249+
so target-owned embeddings and an optional shared target head have the correct
250+
width. Its graph accepts target-provided token embeddings,
251+
the three concatenated target hidden states, recycled draft hidden state, and
252+
draft KV cache. DFlash validates every `dflash.target_layers` index and positive
253+
`dflash.block_size`; its graph accepts target hidden-state concatenation, noise
254+
embeddings, separate Q/K position IDs, and draft KV cache. Pinned DFlash
255+
layer-input indices are normalized back to zero-based target decoder-output
256+
indices. DFlash sliding-window schedules are rejected until the graph can model
257+
their per-layer bounded-cache semantics. DeepSeek-V4/DSpark DFlash tensor
258+
families likewise fail the pinned Qwen-style suffix closure; they require a
259+
different graph and are outside this cohort. Draft-owned
260+
`token_embd.weight` is rejected rather than duplicated or ignored because these
261+
graphs deliberately consume target-provided embeddings.
262+
263+
When `output.weight` is absent, the graph returns `draft_hidden` for the exact
264+
target LM head. When present, it returns compact `draft_logits`. If `d2t` is
265+
present, it must use the pinned I64 representation, be in bounds and unique,
266+
and be accompanied by the
267+
draft-owned output projection; the orchestrator takes argmax in draft-vocabulary
268+
space and maps the proposed ID through `draft_to_target`. Unmapped target IDs
269+
simply have no draft row. Supported quantized draft projections retain the
270+
existing MatMulNBits/native route. Integer remaps are never dequantized, and
271+
`.scale`/`.input_scale` sidecars are rejected when their semantics cannot be
272+
represented instead of being dropped.
273+
274+
Pinned public artifacts were inspected as availability evidence, not runtime
275+
parity:
276+
277+
| Architecture | Draft GGUF revision / file | Size / LFS SHA-256 | Exact target |
278+
|---|---|---|---|
279+
| `dflash` | `lym00/Qwen3-4B-DFlash-GGUF-Test@9d2ec464a15346d8a7d7a696c06694eb1bf690b5` / `Qwen3-4B-DFlash-q8_0.gguf` | 577,047,072 bytes / `5ecf02bb269fc42277f43961794387fea11ecc367ea2d99e86b2b71cc249aff6` | `Qwen/Qwen3-4B@1cfa9a7208912126459214e8b04321603b3df60c` |
280+
| `eagle3` | `williamliao/Qwen3-8B-EAGLE3-Speculator-GGUF@44480ff4ea6330788818f7f5fc9a69b326dc4c06` / `Qwen3-8B-speculator.eagle3-F16.gguf` | 2,049,930,400 bytes / `d6cf1f3cf29e9cd72c02fb11f989f5192f2b24e142741fdc2de8cd590140f2f2` | `Qwen/Qwen3-8B@b968826d9c46dd6066d109eabc6255188de91218` |
281+
282+
The DFlash header has 58 tensors (36 Q8_0, 22 F32); it uses the post-pin
283+
`hidden_norm.weight` spelling and is intentionally rejected by this cohort's
284+
suffix closure. The EAGLE-3 header has 15 tensors (10 F16, 4 F32, 1 I64),
285+
including a 32,000-entry `d2t` and a draft-owned target embedding, which this
286+
external-embedding graph also rejects. No suitably small pinned-format pair was
287+
found. Neither payload was executed, and independent target/draft logits plus
288+
multi-step proposed-token parity is still required before runtime can become
289+
supported.
290+
211291
### Masked language-diffusion GGUF contract
212292

213293
`dream`, `llada`, `llada-moe`, and `rnd1` are full-sequence, bidirectional

‎src/mobius/__main__.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,8 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
620620

621621
gguf_path = args.gguf_path
622622
output_dir = args.output_dir
623-
os.makedirs(output_dir, exist_ok=True)
623+
target_config = getattr(args, "target_config", None)
624+
runtime = getattr(args, "runtime", None)
624625

625626
if args.max_seq_len is not None and not args.static_cache:
626627
raise SystemExit("Error: --max-seq-len can only be used with --static-cache.")
@@ -630,6 +631,11 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
630631
raise SystemExit("Error: --max-workers must be a positive integer.")
631632
if mmproj_path is not None and args.static_cache:
632633
raise SystemExit("Error: --static-cache cannot be used with --mmproj.")
634+
if target_config is not None and runtime is not None:
635+
raise SystemExit(
636+
"Error: dflash/eagle3 target-coupled drafts do not support standalone "
637+
"runtime packaging; omit --runtime to save the auxiliary graph and manifest."
638+
)
633639

634640
pkg = build_from_gguf(
635641
gguf_path,
@@ -640,12 +646,14 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
640646
static_cache=args.static_cache,
641647
max_seq_len=args.max_seq_len,
642648
reuse_gguf_weights=reuse_gguf_weights,
649+
target_config=target_config,
643650
)
644651

645652
if args.release:
646653
for model in pkg.values():
647654
strip_debug_metadata(model)
648655

656+
os.makedirs(output_dir, exist_ok=True)
649657
pkg.save(
650658
output_dir,
651659
external_data=args.external_data,
@@ -672,7 +680,13 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
672680
)
673681
print(f"Saved mtp head to {os.path.join(mtp_dir, 'model.onnx')}")
674682

675-
runtime = getattr(args, "runtime", None)
683+
draft_manifest = getattr(pkg, "draft_manifest", None)
684+
if draft_manifest is not None:
685+
from mobius.integrations.gguf._draft import write_draft_manifest
686+
687+
manifest_path = write_draft_manifest(draft_manifest, output_dir)
688+
print(f"Saved draft pairing manifest to {manifest_path}")
689+
676690
if runtime in ("onnx-genai", "ort-genai"):
677691
from mobius.integrations.gguf import write_gguf_runtime_package
678692

@@ -1200,6 +1214,16 @@ def build_parser() -> argparse.ArgumentParser:
12001214
"weights are written to model.onnx.data."
12011215
),
12021216
)
1217+
gguf_parser.add_argument(
1218+
"--target-config",
1219+
default=None,
1220+
metavar="PATH",
1221+
help=(
1222+
"Exact target model directory or config.json for a dflash/eagle3 "
1223+
"speculative draft. The adjacent tokenizer.json is required and its "
1224+
"ordered vocabulary must exactly match the GGUF tokenizer."
1225+
),
1226+
)
12031227
gguf_parser.add_argument(
12041228
"--runtime",
12051229
choices=["ort-genai", "onnx-genai"],

‎src/mobius/_configs/_base.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1669,6 +1669,8 @@ class DFlashConfig(CausalLMConfig):
16691669
block_size: int | None = None
16701670
mask_token_id: int | None = None
16711671
num_target_layers: int | None = None
1672+
draft_vocab_size: int | None = None
1673+
use_draft_lm_head: bool = False
16721674

16731675
@classmethod
16741676
def from_transformers(cls, config, parent_config=None) -> DFlashConfig:
@@ -1766,6 +1768,8 @@ class Eagle3Config(CausalLMConfig):
17661768
fc_norm: bool = False
17671769
target_hidden_size: int | None = None
17681770
eagle_aux_hidden_state_layer_ids: list[int] | None = None
1771+
target_layer_ids: list[int] | None = None
1772+
use_target_lm_head: bool = False
17691773

17701774
@classmethod
17711775
def from_transformers(cls, config, parent_config=None) -> Eagle3Config:

‎src/mobius/components/_dflash.py‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,10 @@ class DFlashAttention(nn.Module):
5050
avoids any symbolic slicing of the rotary tables.
5151
"""
5252

53-
def __init__(self, config: ArchitectureConfig):
53+
def __init__(self, config: ArchitectureConfig, linear_class: type | None = None):
5454
super().__init__()
55+
if linear_class is None:
56+
linear_class = Linear
5557
self.head_dim = config.head_dim
5658
self.num_attention_heads = config.num_attention_heads
5759
self.num_key_value_heads = config.num_key_value_heads
@@ -60,22 +62,22 @@ def __init__(self, config: ArchitectureConfig):
6062
self.rotary_embedding_dim = 0 if math.isclose(prf, 1.0) else int(self.head_dim * prf)
6163
self._rope_interleave = config.rope_interleave
6264

63-
self.q_proj = Linear(
65+
self.q_proj = linear_class(
6466
config.hidden_size,
6567
self.num_attention_heads * self.head_dim,
6668
bias=config.attn_qkv_bias,
6769
)
68-
self.k_proj = Linear(
70+
self.k_proj = linear_class(
6971
config.hidden_size,
7072
self.num_key_value_heads * self.head_dim,
7173
bias=config.attn_qkv_bias,
7274
)
73-
self.v_proj = Linear(
75+
self.v_proj = linear_class(
7476
config.hidden_size,
7577
self.num_key_value_heads * self.head_dim,
7678
bias=config.attn_qkv_bias,
7779
)
78-
self.o_proj = Linear(
80+
self.o_proj = linear_class(
7981
self.num_attention_heads * self.head_dim,
8082
config.hidden_size,
8183
bias=config.attn_o_bias,
@@ -155,10 +157,10 @@ class DFlashDecoderLayer(nn.Module):
155157
→ residual → post_attention_layernorm → SwiGLU MLP → residual.
156158
"""
157159

158-
def __init__(self, config: ArchitectureConfig):
160+
def __init__(self, config: ArchitectureConfig, linear_class: type | None = None):
159161
super().__init__()
160-
self.self_attn = DFlashAttention(config)
161-
self.mlp = MLP(config)
162+
self.self_attn = DFlashAttention(config, linear_class=linear_class)
163+
self.mlp = MLP(config, linear_class=linear_class)
162164
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
163165
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
164166

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,14 @@
131131
"multi-step generation parity. Runtime packaging remains deferred until both exist."
132132
)
133133

134+
_DRAFT_RUNTIME_VALIDATION_PENDING = (
135+
"This is a target-coupled speculative draft, never a standalone CausalLM. "
136+
"Config extraction, exact tensor closure, target shape/tokenizer validation, and "
137+
"synthetic draft execution are covered, but no pinned real GGUF pair has passed "
138+
"independent target+draft full-logit/proposed-token parity. Runtime packaging remains "
139+
"deferred until that evidence and an acceptance-loop integration exist."
140+
)
141+
134142
_ENCODER_GRAPH_MISMATCH = {
135143
"eurobert": (
136144
"EuroBERT uses pre-norm RMSNorm, RoPE, bias-free split Q/K/V attention, and a "
@@ -192,6 +200,36 @@
192200
model_type="qwen3",
193201
tensor_map_recipe=("llama",),
194202
),
203+
GGUFArchitectureSpec(
204+
gguf_arch="dflash",
205+
model_type="DFlashDraftModel",
206+
tensor_map_recipe=("dflash",),
207+
config_key_map="draft",
208+
config_postprocessor="dflash",
209+
required_metadata=(
210+
"attention.layer_norm_rms_epsilon",
211+
"block_size",
212+
"target_layers",
213+
),
214+
runtime=Support.DEFERRED,
215+
reason=_DRAFT_RUNTIME_VALIDATION_PENDING,
216+
),
217+
GGUFArchitectureSpec(
218+
gguf_arch="eagle3",
219+
model_type="Eagle3DraftModel",
220+
tensor_map_recipe=("eagle3",),
221+
tensor_processor="llama",
222+
llama_qk_permute=True,
223+
config_key_map="draft",
224+
config_postprocessor="eagle3",
225+
required_metadata=(
226+
"attention.layer_norm_rms_epsilon",
227+
"target_hidden_size",
228+
"target_layers",
229+
),
230+
runtime=Support.DEFERRED,
231+
reason=_DRAFT_RUNTIME_VALIDATION_PENDING,
232+
),
195233
GGUFArchitectureSpec(
196234
gguf_arch="qwen2moe",
197235
model_type="qwen2_moe",

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@
6868
"cohere2",
6969
"deci",
7070
"deepseek4",
71+
"dflash",
7172
"dream",
73+
"eagle3",
7274
"exaone",
7375
"falcon",
7476
"gemma",
@@ -150,7 +152,7 @@ def test_a_buildable_architecture_resolves_in_the_mobius_registry(self, spec) ->
150152

151153
def test_the_supported_set_is_pinned(self) -> None:
152154
"""Gaining or losing support is a deliberate, reviewable change."""
153-
assert len(supported_architectures()) == _EXPECTED_SUPPORTED_COUNT
155+
assert len(supported_architectures()) == _EXPECTED_SUPPORTED_COUNT + 2
154156

155157
def test_quantized_import_set_is_pinned(self) -> None:
156158
"""Builder acceptance and rejection must come from an explicit policy set."""

0 commit comments

Comments
 (0)