Skip to content

fix(cli): reject a DFlash drafter before the offline standalone load - #1170

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-1168-dflash-drafter-cli-load
Aug 15, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-1168-dflash-drafter-cli-load

Conversation

@inureyes

@inureyes inureyes commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Summary

mlxcel generate --draft-model <dflash-drafter> failed with Error: Weight not found: model.embed_tokens.weight, with and without --draft-kind, for every DFlash drafter and every target. The offline path calls load_model on the drafter directory because the classic SpeculativeGenerator it falls through to drives a full LoadedModel, and a DFlash checkpoint is not one: it ships no embed_tokens and no lm_head because it borrows both from the target when it binds, and its tensors carry no model. prefix. Its config.json nevertheless declares an ordinary "model_type": "qwen3", so get_model_type classified it ModelType::Qwen3, model_metadata routed it to Qwen3Model::load, and the first UnifiedEmbedding::from_weights lookup failed with a message naming a tensor rather than the problem. This PR makes both offline entry points fail where it makes sense, with a message that names the real problem, and corrects the docs that overstated CLI support.

This deliberately does not build an offline DFlash round loop. That remains out of scope and is still described by the existing --draft-kind message in generate.rs and by docs/speculative-acceptance.md.

The discriminator is structural, not the resolved drafter kind

DEFAULT_DRAFTER_KIND is DrafterKind::Dflash and drafter_kind_by_model_type() maps only gemma4_assistant and gemma4_unified_assistant, so every drafter that is not a Gemma 4 assistant auto-resolves to Dflash, including an ordinary small full model (a Qwen3 0.6B, say) used as a classic drafter. That pairing loads and runs fine today on the classic SpeculativeGenerator path, so rejecting on the resolved kind would have broken a working workflow. The new probe keys on the checkpoint's own DFlash markers instead: a nested dflash_config object (what DFlashConfig::from_json itself reads) and/or architectures: ["DFlashDraftModel"] (what HuggingFace AutoModel dispatch reads). Every test added here carries an ordinary-full-model control asserting the classic path still resolves.

The server path is unaffected

DFlashDrafter::load reads config.json into DFlashConfig::from_json directly and resolve_drafter_kind peeks model_type through its own reader, so neither reaches get_model_type. Re-confirmed on this branch that every get_model_type call site in the tree takes a target or model path and never a drafter path (src/loading/mod.rs, src/distributed/pipeline/stage_executor/mod.rs, src/distributed/tensor_parallel/inference.rs, src/server/chat_template.rs, src/server/startup.rs, src/server/model_provider.rs, src/server/batch/xla_worker.rs, src/multimodal/host_preprocessor.rs, and the three target-path uses in src/commands/generate.rs). The drafter reaches load_drafter through SpeculativeDispatch and DrafterSlot::ensure_loaded, neither of which touches detection. src/bin/speculative_bench.rs likewise passes only the target to load_model. A new test in tests/speculative_dispatch.rs pins that SpeculativeDispatch::resolve still returns the DFlash variant for the same fixture directory that detection now rejects, with and without an explicit --draft-kind.

For the record, the working reference this issue measured on main @ 6e781fcf (Qwen 3.5 27B 4-bit target, which loads as ModelType::Qwen35VLM, plus the 27B DFlash drafter, 120-token completion): rounds 24, proposed_tokens 347, accepted_tokens 95, acceptance_rate 0.274, emitted_per_verify 4.96. That also backs the "VLM paths" claim the supported-models table makes for DFlash, which is why this PR keeps it.

What changed

  • src/lib/mlxcel-core/src/drafter/dflash/config.rs: new DFLASH_DRAFT_ARCHITECTURE constant, is_dflash_drafter_config(&Value), and is_dflash_drafter_dir(&Path), placed next to the parser that consumes dflash_config so the structural definition lives with the loader that keys on it. The doc comment records why model_type and the resolved DrafterKind are both wrong discriminators. An unreadable or missing config.json returns false so the general loader keeps reporting its own I/O and parse diagnostics.
  • src/lib/mlxcel-core/src/drafter/dflash/mod.rs: re-exports the three new items.
  • src/models/detection.rs: get_model_type rejects a structurally-DFlash directory before any model_type dispatch, via a shared dflash_drafter_not_standalone_error. This is the single source of truth for the -m case and covers server startup and the distributed stage loaders at the same time.
  • src/commands/generate.rs: new reject_dflash_drafter_offline, called in run_generation_mode immediately before load_model(draft_model_path). The error says the directory is a DFlash drafter, that the offline path does not construct the DFlashGenerator round loop, and that mlxcel-server with --draft-kind dflash does. It fires with no --draft-kind and with --draft-kind dflash; an explicit --draft-kind mtp is a different request that keeps its own targeted errors from run_offline_mtp.
  • docs/supported-models.md: the DFlash row now reads mlxcel-server only and explains that offline mlxcel generate rejects a DFlash drafter with a named error, so it no longer contradicts docs/speculative-acceptance.md by omission. The MTP row gained the matching detail that it does work offline under --draft-kind mtp. A following paragraph explains why a DFlash checkpoint is not a standalone model.
  • docs/speculative-acceptance.md: the "note on the drafter-kind line" section now distinguishes the auto-detected dflash fallback applied to an ordinary full model (which still runs the classic path) from a real DFlash drafter (which is now refused up front), and records the structural discriminator.
  • src/commands/generate_tests.rs (finalization pass, security finding M3): drafter_fixture_dir and the identical inline empty-fixture pattern built a predictable path under env::temp_dir() with create_dir_all and cleaned up only on the success path (CWE-377/379 class, CI-relevant on shared-TMPDIR Linux runners). Both now use tempfile::tempdir(), matching the pattern the mlxcel-core tests added in this PR already use.
  • CHANGELOG.md, TECHNICAL_REPORTS/1170-dflash-drafter-cli-load-20260816.en.md (finalization pass): the ## [Unreleased] entry and technical report this repository's convention expects for every merged PR.

Test plan

New coverage, all on synthetic fixtures. No test previously invoked mlxcel generate --draft-model at any level, which is why a path that could never work for any DFlash drafter stayed green. All of the below has now actually been executed (by the orchestrator and by review), not just written.

  • cargo test --release --workspace --features metal,accelerate --no-fail-fast: every target passes except -p mlxcel --lib, which reports 5621 passed / 3 failed. All 3 failures are multimodal::video::tests::* and are unrelated to this PR: this branch touches 0 lines of src/multimodal/video.rs, and a PATH-controlled experiment on the same binary gives 34 passed / 0 failed with ffmpeg hidden from PATH versus 31 passed / 3 failed with ffmpeg 9.0.1 present. Root cause is src/multimodal/video.rs:1123 passing -vsync, an argument ffmpeg 9 removed. Filed as fix(video): every video path is broken on ffmpeg 8+ because -vsync was removed, and the tests hide it by passing when ffmpeg is absent #1172.
  • Gotcha for the next person: the four new commands::generate::tests::* precheck tests compile into --bin mlxcel, not --lib, so they were not part of the --lib run above. They were run separately with cargo test --release --bin mlxcel --features metal,accelerate commands::generate: 4 passed.
  • cargo clippy -- -D warnings clean on both crates (mlxcel, mlxcel-core).
  • cargo fmt --check clean.
  • Classic-path non-regression, executed rather than reasoned about: -m qwen3-0.6b-4bit --draft-model qwen3-0.6b-4bit still runs SpeculativeGenerator end to end, 24 tokens, acceptance_rate 1.0000, 137.54 tok/s.
  • Mutation test confirming the new detection tests are real assertions, not tautologies: guarding the new arm as if false && ... makes models::detection and commands::generate fail with the pre-fix classification, on both markers.

Not verified here: an end-to-end run of mlxcel generate --draft-model models/qwen3.5-27b-dflash against a real 27B target. The change is a pre-load guard, so the reproduction is a one-line error rather than a load, but that confirmation has not been re-run on this branch.

Known limitations

Reported and deliberately not fixed in this PR:

  • The precheck fires only after the target model finishes loading, so an operator with a large target waits through the full load before seeing the error. Moving the check earlier would also intercept --draft-kind mtp, which is deliberately routed elsewhere and must keep its own targeted errors from run_offline_mtp.
  • --draft-model <dir>/config.json (pointing directly at the config file rather than the directory) bypasses the precheck and falls through to the detection error with -m phrasing, because the precheck does not apply resolve_model_dir the way the rest of the loading path does.
  • The probe uses raw serde_json::from_slice on config.json, while get_model_type applies sanitize_config_json first. A config containing bare NaN/Infinity literals (invalid JSON, but occasionally emitted by some tooling) would therefore fail the precheck open. No current checkpoint is affected, and the sanitizer lives in the root crate while the probe lives in mlxcel-core, so closing this gap is a cross-crate change left for later.

Closes #1168

`mlxcel generate --draft-model <dflash-drafter>` failed with `Error: Weight not found: model.embed_tokens.weight`, with and without `--draft-kind`. The offline path calls `load_model` on the drafter directory because the classic `SpeculativeGenerator` it falls through to drives a full `LoadedModel`. A DFlash checkpoint is not one: it ships no `embed_tokens` and no `lm_head` (it borrows both from the target when it binds) and its tensors carry no `model.` prefix. Its `config.json` nevertheless declares an ordinary `"model_type": "qwen3"`, so `get_model_type` classified it as `ModelType::Qwen3`, `model_metadata` routed it to `Qwen3Model::load`, and the first `UnifiedEmbedding::from_weights` lookup failed. The same target and drafter pair works on `mlxcel-server`, which routes the drafter through `load_drafter`.

The discriminator is structural, not the resolved drafter kind. `DEFAULT_DRAFTER_KIND` is `Dflash` and `drafter_kind_by_model_type` maps only the two Gemma 4 assistant types, so every drafter that is not a Gemma 4 assistant auto-resolves to `Dflash`, including an ordinary small full model used as a classic drafter. Rejecting on the resolved kind would break that legitimate, currently-working pairing. `is_dflash_drafter_config` / `is_dflash_drafter_dir` therefore key on the checkpoint's own DFlash markers: a nested `dflash_config` object (what `DFlashConfig::from_json` itself reads) and/or `architectures: ["DFlashDraftModel"]` (what HuggingFace `AutoModel` dispatch reads).

Two entry points now share that probe. `get_model_type` rejects a DFlash directory before any `model_type` dispatch, so `mlxcel generate -m <dflash-dir>` reports "not a standalone model" instead of a weight-lookup failure, and so do server startup and the distributed stage loaders. `reject_dflash_drafter_offline` runs in `run_generation_mode` before `load_model`, so `--draft-model <dflash-dir>` names the directory as a DFlash drafter, says the offline path does not construct the `DFlashGenerator` round loop, and points at `mlxcel-server`.

The server drafter path is untouched: `DFlashDrafter::load` parses `config.json` directly and `resolve_drafter_kind` peeks `model_type` through its own reader, so neither reaches `get_model_type`. Every `get_model_type` call site in the tree operates on a target or model path, never a drafter path.

Validation: the offline `--draft-model` precheck, the `-m` detection rejection, and the structural probe are covered by new tests in `src/commands/generate_tests.rs`, `src/models/detection_tests.rs`, `src/lib/mlxcel-core/src/drafter/dflash/config.rs`, and `tests/speculative_dispatch.rs`, each with an ordinary-full-model control that must keep resolving. The DFlash row in `docs/supported-models.md` now states the server-only limitation instead of contradicting `docs/speculative-acceptance.md` by omission.

Closes #1168
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:docs User and developer documentation area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags status:review Under review labels Aug 15, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make mlxcel generate fail where it makes sense, with a message that names the real problem, when a DFlash drafter checkpoint is passed to --draft-model or -m, and fix the docs that overstated offline CLI support.

Findings Addressed

None requiring a fix. No CRITICAL or HIGH findings. The four items below are MEDIUM/LOW and are reported rather than fixed, so the branch stays at the already-validated 82096193.

Remaining Items

  • The --draft-model precheck runs after the target model has fully loaded (MEDIUM). Empirically the operator sees Loading model from ... / Model loaded ... / Generating... and the echoed prompt before the error, so with the real 27B target they pay the whole target load first. run_generate_once has a pre-load validation block (src/commands/generate.rs:1982-1990) that would be the natural home. Not a one-liner: an early call would also intercept --draft-kind mtp, which is deliberately routed to run_offline_mtp's own targeted errors, so it needs the parsed explicit kind threaded up.
  • reject_dflash_drafter_offline does not apply resolve_model_dir (LOW). --draft-model <dflash-dir>/model.safetensors skips the CLI-specific message and falls through to the detection-level error, which phrases the remedy as "Pass a full model to -m" even though the user passed --draft-model. resolve_model_dir is private at src/loading/mod.rs:75, so this is not a one-liner. Marginal, since --draft-model takes a directory.
  • is_dflash_drafter_config treats an empty "dflash_config": {} as a marker (LOW). Upstream mlx-vlm's _has_config excludes {} while its get_model_and_args does not, so upstream is internally inconsistent and no published checkpoint ships an empty block. Informational only.
  • The probe's doc comment argues the marker choice from first principles but does not cite that it matches upstream (LOW). https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/utils.py uses is_dflash = config.get("dflash_config", None) is not None, and mlx-vlm docs/usage.md states "DFlash checkpoints are detected from dflash_config". Adding that URL would follow the "Referencing upstream source" convention. Not applied because a comment-only edit in mlxcel-core invalidates the whole downstream build cache and would stale the completed full-suite validation.

Also LOW, style only: the src/commands/generate_tests.rs fixture helper uses std::env::temp_dir() plus a manual fs::remove_dir_all after the assertions, so a failing assertion leaks the directory. It matches an existing pattern in the same file, but tempfile::tempdir() is the dominant convention in src/**_tests.rs and is what this PR's own sibling fixtures in config.rs and tests/speculative_dispatch.rs use.

Blast radius of the detection change

All 24 non-test get_model_type call sites take a target or model path, never a drafter path: src/loading/mod.rs:528,537,689,706, src/distributed/pipeline/stage_executor/mod.rs:346, src/distributed/tensor_parallel/inference.rs:83, src/server/chat_template.rs:1338, src/server/startup.rs:733,767,1076,1696,2149, src/server/model_provider.rs:131, src/server/batch/xla_worker.rs:250, src/multimodal/host_preprocessor.rs:170, src/commands/generate.rs:564,797,1264. A grep of draft_model_path across the root crate finds no detection call on a drafter path. Three of the server-startup uses swallow Err (.ok()?, is_ok_and, match { Err => default }), so even a hypothetical false positive degrades to a feature-off default rather than a failure.

The separation is structural, not just current practice: get_model_type lives in the root mlxcel crate, and mlxcel-core, which owns load_drafter, resolve_drafter_kind, and DFlashDrafter::load, cannot call it. The server chain was re-read end to end: WorkerDrafterSlot::ensure_loaded (src/server/batch/speculative_burst.rs:270) to load_drafter (src/lib/mlxcel-core/src/drafter/mod.rs:810) to resolve_drafter_kind (:415, own peek_drafter_model_type reader) to DFlashDrafter::load (src/lib/mlxcel-core/src/drafter/dflash/drafter.rs:98, reads config.json straight into DFlashConfig::from_json). The strongest confirmation is tests/speculative_parity.rs, the #[ignore]-gated real-model DFlash test: it calls load_model on the target only and resolve_drafter_kind / load_drafter on the drafter (lines 632, 659, 669), so the one test that drives the whole DFlash pipeline in process never routes the drafter through detection.

False-positive surface: every config.json under models/ on the development box was re-scanned (11 directories). Only qwen3.5-27b-dflash carries a marker. The MTP drafter qwen3.8-27b-mtp-bf16 has no architectures key and no dflash_config, so the offline MTP path is untouched. Nothing in the tree writes or reads dflash_config outside the DFlash config parser. dflash_config is also upstream mlx-vlm's own discriminator, so a standalone model carrying it would misbehave upstream too. No script or CI job keys on the old Weight not found text.

Verification performed

Beyond the queued suites, all on 82096193 with DEVELOPER_DIR set and --release --features metal,accelerate:

Mutation test (are the new tests real?). Guarding the detection arm as if false && is_dflash_drafter_config(&v) and rebuilding makes both dflash_drafter_is_rejected_as_a_standalone_model and dflash_drafter_is_rejected_on_either_marker_alone fail with a DFlash drafter is not a standalone model: Qwen3, which is exactly the pre-fix classification. Reverted with git checkout HEAD -- src/models/detection.rs. Coverage runs both ways: a probe stuck at true is caught by four ordinary-full-model controls, a probe stuck at false by five rejection tests. The controls are not vacuous, ordinary_qwen3_full_model_still_detects_as_qwen3 asserts the concrete ModelType::Qwen3, and ordinary_full_model_is_not_mistaken_for_a_dflash_drafter asserts both resolve_drafter_kind == Dflash and !is_dflash_drafter_dir, which is precisely the trap the structural discriminator exists to avoid.

End-to-end against the real published checkpoint (models/qwen3.5-27b-dflash, 58 tensors), using models/qwen3-0.6b-4bit as a cheap target so the drafter guard is reached without a 27B load:

Case Result
-m <dflash-dir> New detection error, no Weight not found
--draft-model <dflash-dir>, no --draft-kind New CLI precheck error, no Weight not found
--draft-model <dflash-dir> --draft-kind dflash Same new CLI precheck error
--draft-model <dflash-dir> --draft-kind mtp Clean MTP-capability error from run_offline_mtp, no Weight not found
--draft-model <ordinary 0.6B>, no --draft-kind Classic path intact: drafter loads, Resolved drafter kind: dflash (block_size = 16, default), SpeculativeGenerator runs, 24 tokens, acceptance_rate=1.0000, 137.54 tok/s
--draft-model <ordinary 0.6B> --draft-kind dflash Pre-existing generate.rs:1482 error preserved, so the speculative-acceptance.md:274-276 claim stays true

Targeted suites, all green: models::detection 30 passed, drafter::dflash::config 16 passed (6 new), commands::generate::tests::offline_draft 4 passed, --test speculative_dispatch 22 passed (5 new).

Lints: cargo fmt --check clean. cargo clippy --release -p mlxcel-core --lib --tests -- -D warnings clean. cargo clippy --release -p mlxcel --lib --bins --tests -- -D warnings clean. python3 scripts/ci/check_cross_repo_refs.py clean, every #1168 reference is same-repo. That closes the two boxes the PR description left unchecked.

Note for the record: commands::generate::tests::* compile into the --bin mlxcel target, not --lib, so a -p mlxcel --lib run does not include the four new --draft-model precheck tests. They were run separately.

Not measured: --draft-kind mtp against a genuinely Gemma 4 MTP-capable target combined with a DFlash drafter directory. That combination bypasses the new precheck by design and lands in load_drafter(.., Some(Mtp)). No Gemma 4 target is on this box. On the Qwen target that is available, the equivalent case errors cleanly at the MTP-capability gate.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL and no HIGH findings. Nothing auto-fixed, no commits pushed. Three MEDIUM and three LOW items below, all advisory.

1. Path handling in is_dflash_drafter_dir

No panic path. std::fs::read returns Err on any I/O failure; serde_json::from_slice returns Err on invalid UTF-8 content and on malformed JSON rather than panicking; serde_json 1.0.151 is pinned with neither the unbounded_depth feature enabled nor disable_recursion_limit() called anywhere in the tree, so the default 128-frame nesting limit holds and an adversarially nested config is an Err, not a stack overflow. Value::get, as_array, and as_str are all non-panicking. Verified by grep across the workspace and Cargo.lock.

Symlink following is required behavior here, not a defect: on the development box models/qwen3.5-27b-dflash is itself a symlink, so a probe that refused to traverse links would break the operator's own layout. The path is an operator-supplied CLI argument, not a value crossing a trust boundary.

TOCTOU against the later real load exists but buys nothing. Winning the race only downgrades the message back to the pre-PR one, and load_model re-reads config.json through get_model_type, which now carries the same structural rejection. The two guards cover each other.

2. Information disclosure in the two error messages

Both echo path.display(), which matches the established convention in this tree (src/models/gpt_oss.rs:1182, src/models/gemma3.rs:951, src/loading/vlm_muse_glimmer.rs:258, src/models/sanitize.rs:1195, src/multimodal/host_preprocessor.rs:170). The path is the operator's own argument, and both messages are otherwise free of tensor names, environment values, and internal identifiers.

Neither message reaches an HTTP response body. The two server-side get_model_type sites that could carry an error toward a client discard it instead: src/server/model_provider.rs:131 uses is_ok_and, and src/server/chat_template.rs:1338 uses .ok()?. The remaining server sites fail at startup into logs.

3. Denial of service and resource use

The get_model_type arm adds zero I/O. It runs on the Value that function already parsed, so the cost is one map lookup plus a scan of a one-element architectures array.

get_model_type is not on any per-request path. All 18 call sites were traced to their callers: every one is startup, ModelProvider/worker construction, or model load. The three whose results feed request-time decisions are memoized, notably ModelProvider.single_stream_queue_admission: Arc<AtomicBool> (constructed at model_provider.rs:432, :746, :850; read per request at :944), the AppState chat template Arc<ChatTemplateProcessor>, and XlaServeWorker.phi4mm_media_preprocessor. One near-miss worth a comment guard rather than a change: inlining uses_single_stream_queue_admission into model_provider.rs:944 would turn it into a config.json read per request.

The only added I/O is the single fs::read in reject_dflash_drafter_offline, once per CLI process, immediately before a load that reads the same file anyway.

4. Correctness of the failure-open choice

Confirmed not a bypass, and the right call. The guard is a usability guard, not a trust boundary. It grants no capability, and no privilege, authentication, or authorization decision sits downstream of it. Failing open falls through to exactly the code path that ran before this PR, and that path now contains the detection-level rejection, so the worst an attacker gains by forcing false is the pre-PR error message on their own local invocation.


MEDIUM

M1. The precheck does not normalize a file path to its directory. reject_dflash_drafter_offline joins config.json onto the raw --draft-model value, but loading::load_model calls resolve_model_dir (src/loading/mod.rs:75-81) first, which maps a file to its parent. So --draft-model models/qwen3.5-27b-dflash/config.json skips the precheck entirely. Contained, not broken: load_model then hits the get_model_type rejection, so the user still gets a named error. It is the -m phrasing though, which does not name mlxcel-server --draft-kind dflash. Mirroring resolve_model_dir in the probe, or accepting a path that already points at config.json, closes it.

M2. Parse divergence between the two entry points. is_dflash_drafter_dir calls serde_json::from_slice on raw bytes, while get_model_type runs sanitize_config_json first, which rewrites bare NaN, Infinity, and -Infinity literals (src/models/sanitize.rs:1923-1928). A drafter config carrying those literals, which is the reason that sanitizer exists, makes the CLI precheck fail open. Same containment as M1: detection still catches it. I confirmed the published qwen3.5-27b-dflash config carries none of those literals, so no current checkpoint is affected. Note the layering constraint before fixing: sanitize_config_json lives in the root mlxcel crate and the probe lives in mlxcel-core, so reuse means moving the three-line sanitizer down rather than adding a dependency. A doc-comment note on the divergence is an acceptable alternative.

M3. Test temp-directory hygiene in src/commands/generate_tests.rs. drafter_fixture_dir and the inline empty directory build a predictable name under std::env::temp_dir() and create it with create_dir_all, which succeeds on a pre-existing directory or a symlink to one, then clean up only on the success path. On Linux CI, where TMPDIR is the world-writable /tmp, that is the CWE-377/CWE-379 pattern: an attacker who pre-creates the name as a symlink gets config.json written through it and the target's contents removed by remove_dir_all. On macOS env::temp_dir() is the per-user /var/folders/.../T, so the practical exposure is CI only. Separately, an assertion failure leaks the directory, and the two-case loop in offline_draft_model_rejects_a_dflash_drafter_on_either_marker_alone leaks on the first failure. This matches a pre-existing pattern in the same file and in detection_tests.rs::temp_path, but tempfile is already a dev-dependency and the mlxcel-core tests added by this same PR use tempfile::tempdir(), so the PR is internally inconsistent. Test-only, no production impact.

LOW

L1. The CLI now reads the drafter's config.json three times per invocation: resolve_drafter_kind via peek_drafter_model_type, then is_dflash_drafter_dir, then load_model via get_model_type. Microseconds once per process, so no action needed. Noted only because having peek_drafter_model_type hand back the parsed Value would collapse two of them.

L2. fs::read is unbounded. Consistent with get_model_type's read_to_string on the same file, and the input is operator-supplied, so this is not new exposure. A bounded read would still be strictly better for a probe whose input is always a few KB.

L3. --draft-kind mtp pointed at a DFlash drafter directory still reaches Gemma4AssistantDraftModel::from_path and surfaces a weight-level error. The PR scopes this out deliberately and says so. Flagged only so it reads as a known remainder rather than an oversight.

What the review confirmed as correct

Keying on checkpoint structure rather than the resolved DrafterKind is the right discriminator, and it is pinned by an ordinary-full-model control at all four test levels. Scanning every config.json under models/ reproduced the PR's claim independently: only qwen3.5-27b-dflash carries a marker, and the MTP target (model_type: qwen3_5_mtp, no architectures) and both Qwen 3.5/3.8 targets are untouched. The two guards form a genuine belt and braces, which is what makes the failure-open choice in M1 and M2 safe rather than merely tolerable.

`drafter_fixture_dir` in src/commands/generate_tests.rs built a predictable directory name under env::temp_dir() and created it with create_dir_all, which succeeds against a pre-existing directory or symlink there (CWE-377/379), and it cleaned up only on the success path, so an assertion failure leaked the fixture. This is CI-relevant on Linux where TMPDIR is shared across jobs.

Replace it, and the identical inline pattern in the missing-config fixture two lines below it, with tempfile::tempdir(), which creates a securely-permissioned, randomly-named directory and removes it on drop regardless of how the test exits. This matches the pattern the mlxcel-core drafter::dflash::config tests added in this same PR already use, removing an inconsistency within the PR.

Validation:
- cargo test --release --bin mlxcel --features metal,accelerate commands::generate: 82 passed, including all four offline_draft_model_* precheck tests.
- cargo fmt --check and cargo clippy --release --bin mlxcel --features metal,accelerate --tests -- -D warnings: clean.

Refs #1170
This PR was missing the two documentation artifacts every other merged PR in this repository carries: a CHANGELOG.md entry under ## [Unreleased] / ### Fixed, and an English technical report under TECHNICAL_REPORTS/ (Korean translation intentionally skipped for this PR).

The CHANGELOG entry summarizes the DFlash-drafter-offline-load rejection (#1168) and the discriminator choice (checkpoint structure, not resolved DrafterKind). The technical report additionally covers the M3 test-hygiene fix from this finalization pass (drafter_fixture_dir moved to tempfile::tempdir()) and the full validation record: the workspace test run, the separately-run --bin mlxcel precheck tests, clippy/fmt, the real-checkpoint classic-path non-regression run, and the mutation test confirming the new detection tests are not tautologies.

Refs #1170
This repository pairs every TECHNICAL_REPORTS entry with an English and a Korean version; PR #1170's report was missing its Korean counterpart. Adds TECHNICAL_REPORTS/1170-dflash-drafter-cli-load-20260816.ko.md, written as Korean technical prose rather than a literal translation, following the section structure of the existing .ko.md reports (1157, 1158, 1150-1154).

Also removes one stray em dash from the English report's Code Quality section, replacing it with a colon per this project's no-em-dash convention.

Refs #1170
@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 15, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Orchestrator verification against real checkpoints

Run on the development box at 27654b29 with freshly built release binaries, DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer.

The reported symptom is gone, in all three entry shapes

All three now produce a named error, and Weight not found: model.embed_tokens.weight appears in none of them.

invocation result
generate -m qwen3-0.6b-4bit --draft-model qwen3.5-27b-dflash named DFlash-drafter error naming mlxcel-server as the way to use it
same plus --draft-kind dflash same named error
generate -m qwen3.5-27b-dflash named "not a standalone model" error

The server path is not regressed, measured rather than reasoned

This was the highest-risk item, since the fix adds a rejection inside get_model_type. Same 27B pair, after the change:

INFO Lazy-loading drafter from models/qwen3.5-27b-dflash (kind=Some(Dflash))
INFO Drafter loaded (kind=dflash, 1 ms)

An 80-token completion drove real speculative work: rounds 15, proposed_tokens 185, accepted_tokens 65, acceptance_rate 0.351, emitted_per_verify 5.27. Comparable to the pre-change reference recorded in #1168 (24 rounds, 0.274 acceptance on a 120-token completion); the two differ in completion length, not in behavior.

Suite

cargo test --release --workspace --features metal,accelerate --no-fail-fast: every target passes except -p mlxcel --lib at 5621 passed / 3 failed.

All 3 failures are multimodal::video::tests::* and are not attributable to this PR. Two independent lines of evidence:

  1. This PR touches 0 lines of src/multimodal/video.rs.
  2. A PATH-controlled experiment on the same compiled binary, same commit, varying only whether ffmpeg is visible:
arm ffmpeg on PATH result
A hidden 34 passed, 0 failed
B ffmpeg 9.0.1 31 passed, 3 failed

Root cause is src/multimodal/video.rs:1123 passing -vsync, which ffmpeg 9 removed. Filed as #1172. Worth noting the second-order finding recorded there: those tests pass by silently skipping when ffmpeg is absent, which is the same shape of gap this PR closes on the CLI side, where no test invoked mlxcel generate --draft-model at all.

cargo test --release --bin mlxcel --features metal,accelerate commands::generate: 82 passed, 0 failed, after the tempfile::tempdir() change.

@inureyes
inureyes merged commit 865bede into main Aug 15, 2026
7 checks passed
@inureyes
inureyes deleted the fix/issue-1168-dflash-drafter-cli-load branch August 15, 2026 18:23
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ablup#1170)

## Summary

`mlxcel generate --draft-model <dflash-drafter>` failed with `Error: Weight not found: model.embed_tokens.weight`, with and without `--draft-kind`, for every DFlash drafter and every target. The offline path calls `load_model` on the drafter directory because the classic `SpeculativeGenerator` it falls through to drives a full `LoadedModel`, and a DFlash checkpoint is not one: it ships no `embed_tokens` and no `lm_head` because it borrows both from the target when it binds, and its tensors carry no `model.` prefix. Its `config.json` nevertheless declares an ordinary `"model_type": "qwen3"`, so `get_model_type` classified it `ModelType::Qwen3`, `model_metadata` routed it to `Qwen3Model::load`, and the first `UnifiedEmbedding::from_weights` lookup failed with a message naming a tensor rather than the problem. This PR makes both offline entry points fail where it makes sense, with a message that names the real problem, and corrects the docs that overstated CLI support.

This deliberately does not build an offline DFlash round loop. That remains out of scope and is still described by the existing `--draft-kind` message in `generate.rs` and by `docs/speculative-acceptance.md`.

## The discriminator is structural, not the resolved drafter kind

`DEFAULT_DRAFTER_KIND` is `DrafterKind::Dflash` and `drafter_kind_by_model_type()` maps only `gemma4_assistant` and `gemma4_unified_assistant`, so **every** drafter that is not a Gemma 4 assistant auto-resolves to `Dflash`, including an ordinary small full model (a Qwen3 0.6B, say) used as a classic drafter. That pairing loads and runs fine today on the classic `SpeculativeGenerator` path, so rejecting on the resolved kind would have broken a working workflow. The new probe keys on the checkpoint's own DFlash markers instead: a nested `dflash_config` object (what `DFlashConfig::from_json` itself reads) and/or `architectures: ["DFlashDraftModel"]` (what HuggingFace `AutoModel` dispatch reads). Every test added here carries an ordinary-full-model control asserting the classic path still resolves.

## The server path is unaffected

`DFlashDrafter::load` reads `config.json` into `DFlashConfig::from_json` directly and `resolve_drafter_kind` peeks `model_type` through its own reader, so neither reaches `get_model_type`. Re-confirmed on this branch that every `get_model_type` call site in the tree takes a target or model path and never a drafter path (`src/loading/mod.rs`, `src/distributed/pipeline/stage_executor/mod.rs`, `src/distributed/tensor_parallel/inference.rs`, `src/server/chat_template.rs`, `src/server/startup.rs`, `src/server/model_provider.rs`, `src/server/batch/xla_worker.rs`, `src/multimodal/host_preprocessor.rs`, and the three target-path uses in `src/commands/generate.rs`). The drafter reaches `load_drafter` through `SpeculativeDispatch` and `DrafterSlot::ensure_loaded`, neither of which touches detection. `src/bin/speculative_bench.rs` likewise passes only the target to `load_model`. A new test in `tests/speculative_dispatch.rs` pins that `SpeculativeDispatch::resolve` still returns the DFlash variant for the same fixture directory that detection now rejects, with and without an explicit `--draft-kind`.

For the record, the working reference this issue measured on `main` @ `6e781fcf` (Qwen 3.5 27B 4-bit target, which loads as `ModelType::Qwen35VLM`, plus the 27B DFlash drafter, 120-token completion): rounds 24, proposed_tokens 347, accepted_tokens 95, acceptance_rate 0.274, emitted_per_verify 4.96. That also backs the "VLM paths" claim the supported-models table makes for DFlash, which is why this PR keeps it.

## What changed

- `src/lib/mlxcel-core/src/drafter/dflash/config.rs`: new `DFLASH_DRAFT_ARCHITECTURE` constant, `is_dflash_drafter_config(&Value)`, and `is_dflash_drafter_dir(&Path)`, placed next to the parser that consumes `dflash_config` so the structural definition lives with the loader that keys on it. The doc comment records why `model_type` and the resolved `DrafterKind` are both wrong discriminators. An unreadable or missing `config.json` returns `false` so the general loader keeps reporting its own I/O and parse diagnostics.
- `src/lib/mlxcel-core/src/drafter/dflash/mod.rs`: re-exports the three new items.
- `src/models/detection.rs`: `get_model_type` rejects a structurally-DFlash directory before any `model_type` dispatch, via a shared `dflash_drafter_not_standalone_error`. This is the single source of truth for the `-m` case and covers server startup and the distributed stage loaders at the same time.
- `src/commands/generate.rs`: new `reject_dflash_drafter_offline`, called in `run_generation_mode` immediately before `load_model(draft_model_path)`. The error says the directory is a DFlash drafter, that the offline path does not construct the `DFlashGenerator` round loop, and that `mlxcel-server` with `--draft-kind dflash` does. It fires with no `--draft-kind` and with `--draft-kind dflash`; an explicit `--draft-kind mtp` is a different request that keeps its own targeted errors from `run_offline_mtp`.
- `docs/supported-models.md`: the DFlash row now reads `mlxcel-server` only and explains that offline `mlxcel generate` rejects a DFlash drafter with a named error, so it no longer contradicts `docs/speculative-acceptance.md` by omission. The MTP row gained the matching detail that it does work offline under `--draft-kind mtp`. A following paragraph explains why a DFlash checkpoint is not a standalone model.
- `docs/speculative-acceptance.md`: the "note on the drafter-kind line" section now distinguishes the auto-detected `dflash` fallback applied to an ordinary full model (which still runs the classic path) from a real DFlash drafter (which is now refused up front), and records the structural discriminator.
- `src/commands/generate_tests.rs` (finalization pass, security finding M3): `drafter_fixture_dir` and the identical inline `empty`-fixture pattern built a predictable path under `env::temp_dir()` with `create_dir_all` and cleaned up only on the success path (CWE-377/379 class, CI-relevant on shared-`TMPDIR` Linux runners). Both now use `tempfile::tempdir()`, matching the pattern the `mlxcel-core` tests added in this PR already use.
- `CHANGELOG.md`, `TECHNICAL_REPORTS/1170-dflash-drafter-cli-load-20260816.en.md` (finalization pass): the `## [Unreleased]` entry and technical report this repository's convention expects for every merged PR.

## Test plan

New coverage, all on synthetic fixtures. No test previously invoked `mlxcel generate --draft-model` at any level, which is why a path that could never work for any DFlash drafter stayed green. All of the below has now actually been executed (by the orchestrator and by review), not just written.

- [x] `cargo test --release --workspace --features metal,accelerate --no-fail-fast`: every target passes except `-p mlxcel --lib`, which reports 5621 passed / 3 failed. All 3 failures are `multimodal::video::tests::*` and are unrelated to this PR: this branch touches 0 lines of `src/multimodal/video.rs`, and a PATH-controlled experiment on the same binary gives 34 passed / 0 failed with ffmpeg hidden from `PATH` versus 31 passed / 3 failed with ffmpeg 9.0.1 present. Root cause is `src/multimodal/video.rs:1123` passing `-vsync`, an argument ffmpeg 9 removed. Filed as lablup#1172.
- [x] Gotcha for the next person: the four new `commands::generate::tests::*` precheck tests compile into `--bin mlxcel`, not `--lib`, so they were **not** part of the `--lib` run above. They were run separately with `cargo test --release --bin mlxcel --features metal,accelerate commands::generate`: 4 passed.
- [x] `cargo clippy -- -D warnings` clean on both crates (`mlxcel`, `mlxcel-core`).
- [x] `cargo fmt --check` clean.
- [x] Classic-path non-regression, executed rather than reasoned about: `-m qwen3-0.6b-4bit --draft-model qwen3-0.6b-4bit` still runs `SpeculativeGenerator` end to end, 24 tokens, acceptance_rate 1.0000, 137.54 tok/s.
- [x] Mutation test confirming the new detection tests are real assertions, not tautologies: guarding the new arm as `if false && ...` makes `models::detection` and `commands::generate` fail with the pre-fix classification, on both markers.

Not verified here: an end-to-end run of `mlxcel generate --draft-model models/qwen3.5-27b-dflash` against a real 27B target. The change is a pre-load guard, so the reproduction is a one-line error rather than a load, but that confirmation has not been re-run on this branch.

## Known limitations

Reported and deliberately not fixed in this PR:

- The precheck fires only after the target model finishes loading, so an operator with a large target waits through the full load before seeing the error. Moving the check earlier would also intercept `--draft-kind mtp`, which is deliberately routed elsewhere and must keep its own targeted errors from `run_offline_mtp`.
- `--draft-model <dir>/config.json` (pointing directly at the config file rather than the directory) bypasses the precheck and falls through to the detection error with `-m` phrasing, because the precheck does not apply `resolve_model_dir` the way the rest of the loading path does.
- The probe uses raw `serde_json::from_slice` on `config.json`, while `get_model_type` applies `sanitize_config_json` first. A config containing bare `NaN`/`Infinity` literals (invalid JSON, but occasionally emitted by some tooling) would therefore fail the precheck open. No current checkpoint is affected, and the sanitizer lives in the root crate while the probe lives in `mlxcel-core`, so closing this gap is a cross-crate change left for later.

Closes lablup#1168
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:docs User and developer documentation area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cli): mlxcel generate --draft-model loads a DFlash drafter as a standalone model and dies on "Weight not found: model.embed_tokens.weight"

1 participant