Skip to content

fix(models): deepseek::ModelArgs silently drops an inherited quantization block #975

Closed

Description

@inureyes

Background

PR #972 (issue #958, merged as db6cce9dc) bounded the declared quantization parameters where they are stored, adding mlxcel_core::layers::validate_quantization_params(group_size, bits) (src/lib/mlxcel-core/src/layers.rs:1292) and calling it at the shared loaders plus roughly twenty family-local expert-plane constructors, and making QuantizedEmbedding::new and QuantizedMultiLinear::new return Result. The defect class it exists to close: a config-derived value passes every Rust-side check, violates an undocumented MLX precondition, and terminates the process at the FIRST forward pass rather than failing at load, because quantized_matmul and gather_qmm cross the cxx bridge as UniquePtr<MlxArray> rather than Result (src/lib/mlxcel-core/src/lib.rs:1092, :1108), so the C++ throw is an uncatchable std::terminate that catch_unwind cannot contain.

This issue is the adjacent problem on the same code: #972 bounded the values the loaders store, but on one family the values reaching those loaders are not the ones the checkpoint declared. The declared quantization block is silently discarded and hardcoded defaults are used instead.

Which path inherits from where

This is a nested-sub-config inheritance case in the DeepSeek-OCR VLM loaders, plus the plain text loader for the same config struct. It is not a text_config case and not a shared-args conversion.

src/models/deepseek.rs:35 declares ModelArgs with two flat, top-level optional fields and no nested block:

#[serde(default)]
pub group_size: Option<i32>,

#[serde(default)]
pub bits: Option<i32>,

(:70 and :73, read through group_size() at :97 and bits() at :101, which fall back to 64 and 4.) There is no quantization field on the struct and no #[serde(deny_unknown_fields)].

The three DeepSeek-OCR loaders in src/loading/vlm_deepseekocr.rs inherit the root quantization OBJECT into language_config before deserializing into that struct:

if !obj.contains_key("quantization")
    && let Some(q) = full_config.get("quantization")
{
    obj.insert("quantization".to_string(), q.clone());
}

then

let args: models::deepseek::ModelArgs = serde_json::from_value(lc)?;
let (gs, bits) = (args.group_size(), args.bits());

The three sites are load_deepseekocr_vlm (insert at :78, deserialize at :84, read the pair at :86), the Unlimited-OCR loader (:152 / :158 / :160), and the DeepSeek-OCR 2 loader (:245 / :251 / :253).

Serde ignores the unknown quantization key, so the nested object is discarded on deserialization. group_size and bits stay None, and group_size() / bits() return the hardcoded 64 / 4 regardless of what the checkpoint declares. The inheritance code runs, succeeds, and accomplishes nothing.

DeepSeekModel::load (src/models/deepseek.rs:602) has the same shape for a plain deepseek config.json: it deserializes the whole file into ModelArgs at :609, so a normal MLX-style nested "quantization": {"group_size": N, "bits": M} block is dropped there too. Only a checkpoint that happens to carry flat top-level group_size / bits keys is read correctly, and no MLX conversion tool emits that spelling.

The contrast that shows this is a struct bug, not a loader bug

src/loading/vlm_deepseek_vl2.rs:91 performs the byte-identical inheritance and then deserializes into models::deepseek_v2::ModelArgs at :97. That one works, because deepseek_v2::ModelArgs has a real nested field: pub quantization: Option<Quantization> at src/models/deepseek_v2.rs:114, backed by pub struct Quantization { group_size, bits } at :118, with accessors at :181 and :188. The two loaders look the same at the call site and behave differently purely because of the config struct they target.

Consequence, at load and at first forward

The declared values propagate to four places in this family: the embedding at src/models/deepseek.rs:624, the MoE expert planes through SwitchLinear::from_stacked_parts (which reads the pair at :887), every dense projection through load_quantized_linear at :916, and the DeepSeek-OCR projector at src/loading/vlm_deepseekocr.rs:94. The consequence of substituting 64 / 4 for the declared values differs by path, and both halves matter:

  • Dense projections, the embedding, and the OCR projector go through reconcile_quantization_layout (src/lib/mlxcel-core/src/layers.rs:1467). For affine weights it trusts group_size and re-derives bits from the tensor shapes. A wrong bits is therefore corrected, with only a tracing::warn! on the mlxcel::quant target (:1587). A wrong group_size is worse: infer_quantization_bits (:1155) solves packed_in * 32 / (num_groups * group_size) and, for a real group_size-32 4-bit tensor read as group_size 64, lands on bits = 2, which is in the accepted {2,3,4,5,6,8} set. The resulting (64, 2) pair is self-consistent, so MLX's own shape check passes and the kernel runs. The output is silently wrong, with a warning line and no load failure.
  • MoE expert planes take no such path. SwitchLinear::from_stacked_parts stores the pair verbatim and hands it to gather_qmm, so a group_size that does not match the tensor fails MLX's packed_in * 32 == bits * num_groups * group_size check and aborts uncatchably at the first routed forward pass.

Neither outcome is a load error, which is the point: nothing in the pipeline reports that the declared block was ignored.

Impact today is latent

Every DeepSeek-family checkpoint currently under models/ declares exactly the fallback values, so nothing misbehaves right now. models/deepseek-ocr-4bit (model_type: deepseekocr) and models/deepseek-ocr-2-4bit (model_type: deepseekocr_2) both declare root {"group_size": 64, "bits": 4, "mode": "affine"} and carry no language_config.quantization, so both land on 64 / 4 by coincidence. There is no local model_type: deepseek checkpoint at all, so DeepSeekModel::load is unexercised. An 8-bit export, or a group_size of 32 or 128, would be mis-read on every one of these paths.

Adjacency to #991, flagged rather than asserted

#991 reports that deepseek_v2 generates degenerate output on models/deepseek-v2-lite-4bit while mlx-lm is correct on the same weights, and that investigation established models/deepseek-vl2-small-4bit runs the same DeepSeekV2Model::from_weights correctly. Neither of those checkpoints reaches the code in this issue. models/deepseek-v2-lite-4bit is model_type: deepseek_v2 and loads through deepseek_v2::ModelArgs; models/deepseek-vl2-small-4bit is model_type: deepseek_vl_v2 and loads through src/loading/vlm_deepseek_vl2.rs, which also targets deepseek_v2::ModelArgs. Both therefore read their nested quantization block correctly, via the field at src/models/deepseek_v2.rs:114. On the evidence available, this issue and #991 are separate defects in sibling modules and do not interact. That is worth re-checking rather than assuming, because the two modules are near-duplicates and a fix here that touches shared config plumbing could easily reach deepseek_v2.

Proposed Solution

Give deepseek::ModelArgs the nested field the loaders already assume it has.

  1. Add #[serde(default)] pub quantization: Option<...> to src/models/deepseek.rs:35.
  2. Change group_size() (:97) and bits() (:101) to prefer the nested block, keeping the flat group_size / bits fields as a fallback so anything relying on the current spelling keeps loading.
  3. Prefer the existing shared type over adding another private copy. models::config::QuantizationArgs (src/models/config.rs:244) already exists with Option<i32> group_size, Option<i32> bits, Option<String> mode, and get_group_size() / get_bits() / get_mode() accessors that default to 64 / 4 / "affine". It currently has zero production callers. There are 59 near-identical private pub struct Quantization declarations under src/models/, and the divergence between deepseek.rs and deepseek_v2.rs is precisely what produced this bug, so adding a sixtieth is the wrong move. Note that get_mode() returns the declared string unbounded, which is fix(core): bound the declared quantization mode string, not just group_size and bits #973; adopting QuantizationArgs here should not silently widen that surface.
  4. Add a deserialization test that feeds a language_config with an inherited nested quantization block through deepseek::ModelArgs and asserts the declared values survive, so the inheritance in src/loading/vlm_deepseekocr.rs has a regression gate.
  5. Consider whether DeepSeekModel::load should also reject a quantization block it cannot interpret, rather than falling through to defaults. Silence is the failure mode here, so an explicit error is worth more than a correct default.

Inspection and reproduction

Confirm the drop without building anything. This prints the deserialized struct's view of an inherited block:

python3 - <<'PY'
import json
# What the loader builds and hands to serde, for the OCR-2 checkpoint.
full = json.load(open("models/deepseek-ocr-2-4bit/config.json"))
lc = dict(full["language_config"])
lc.setdefault("quantization", full["quantization"])
print("inherited into language_config:", lc["quantization"])
print("flat keys serde will actually read:", {k: lc.get(k) for k in ("group_size", "bits")})
PY

Expected output: the nested block is present, and both flat keys are None, so group_size() / bits() return 64 / 4.

Confirm the struct has no nested field and no unknown-field rejection:

grep -n "pub struct ModelArgs" -A 45 src/models/deepseek.rs | grep -n "quantization\|group_size\|bits\|deny_unknown_fields"
# Contrast with the sibling that works.
grep -n "pub quantization: Option<Quantization>" -A 6 src/models/deepseek_v2.rs

Demonstrate the mis-read on a real checkpoint. models/deepseek-ocr-4bit declares the fallback values, so edit a copy to declare something else and observe that the output does not change, which it should. Symlink rather than copy to avoid duplicating the weights:

mkdir -p /tmp/deepseek-ocr-8bitdecl
for f in /Volumes/Monolith/Development/rust/mlxcel/models/deepseek-ocr-4bit/*; do ln -sf "$f" /tmp/deepseek-ocr-8bitdecl/; done
rm /tmp/deepseek-ocr-8bitdecl/config.json
python3 - <<'PY'
import json
c = json.load(open("/Volumes/Monolith/Development/rust/mlxcel/models/deepseek-ocr-4bit/config.json"))
c["quantization"] = {"group_size": 32, "bits": 8, "mode": "affine"}
json.dump(c, open("/tmp/deepseek-ocr-8bitdecl/config.json", "w"), indent=2)
PY
DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer \
  cargo build --release --features metal,accelerate
./target/release/mlxcel generate -m /tmp/deepseek-ocr-8bitdecl -p "Hello" -n 8
# The `mlxcel::quant` warning only surfaces through a tracing subscriber, and the CLI installs none.
# Only `mlxcel-server` does (`src/server/startup.rs:1009`), so use it when the warning is the signal:
RUST_LOG=mlxcel::quant=warn ./target/release/mlxcel-server -m /tmp/deepseek-ocr-8bitdecl

Expected today: identical behavior to the unedited checkpoint, and no reconciliation warning from the server either, because the declared block never reaches the loader. Expected after the fix: the declared (32, 8) reaches reconcile_quantization_layout, which either warns and reconciles against the real shapes or fails at load, and either way the change is visible. That the CLI has no subscriber at all is part of why this defect is silent: even when the reconciler does fire, the only user-facing surface that reports it is the server.

Local validation: possible and not possible

Possible here. The quantized MoE checkpoints available under models/ in the repo root are gpt-oss-20b-mxfp4, deepseek-v2-lite-4bit, qwen3-30b-a3b-4bit, qwen3-moe-4bit, mixtral-8x7b-4bit, jamba-v0.1-4bit, nemotron-h-30b-4bit and llama-4-scout-17b-4bit. For this issue the relevant ones are models/deepseek-ocr-4bit and models/deepseek-ocr-2-4bit, the only two local checkpoints that reach deepseek::ModelArgs. Both are regression controls: because they declare exactly the fallback pair, their OCR output must be byte-identical before and after the fix, which is the check that the new nested field does not change the values any existing checkpoint loads with. The deserialization behavior itself is fully testable locally as a unit test, with no model on disk.

Not possible here. No local checkpoint declares anything other than 64 / 4 on this path, and there is no local model_type: deepseek checkpoint at all, so the positive case (a declared block that differs from the fallback is honoured end to end on real weights) cannot be validated against a genuine artifact. It has to be driven either by an edited config over symlinked weights, as above, or by a unit test. models/deepseek-v2-lite-4bit is not usable as a cross-family control right now: it produces degenerate output for an unrelated reason tracked as #991.

Machine notes

  • Pass DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer on every cargo invocation. Without it cmake fails with xcrun: error: unable to find utility "metal".
  • Only the release profile is warm (target/release exists, target/debug does not). A plain debug cargo check triggers a cold MLX C++ build. Use cargo check --release --features metal,accelerate and cargo test --release.
  • A test that actually trips an MLX C++ throw aborts the whole test binary with SIGABRT rather than failing cleanly, because the bridge functions return UniquePtr<MlxArray> and cannot propagate the exception. Keep the tests here at the deserialization and load-Result level and never run a forward pass in them.

Acceptance Criteria

  • deepseek::ModelArgs deserializes a nested "quantization": {"group_size": N, "bits": M} block and group_size() / bits() return N / M.
  • All three DeepSeek-OCR loaders in src/loading/vlm_deepseekocr.rs see the inherited root block instead of falling back to 64 / 4, verified at each of the three sites rather than only the first.
  • DeepSeekModel::load reads a nested block from a plain deepseek config.json.
  • A config carrying the flat top-level group_size / bits keys still loads with those values, so the change is backward compatible with whatever spelling the current fields exist for.
  • A language_config that declares its own quantization block still wins over the inherited root block, matching the !obj.contains_key("quantization") guard the loaders already have.
  • A unit test covers the inheritance path end to end (nested block inserted into language_config, deserialized through deepseek::ModelArgs, values asserted), not just the struct in isolation.
  • No sixtieth private Quantization struct is added. Either models::config::QuantizationArgs is adopted or the reason it was not is recorded in the code.
  • models/deepseek-ocr-4bit and models/deepseek-ocr-2-4bit produce byte-identical OCR output before and after, since both declare the fallback values.
  • Whether this interacts with fix(models): deepseek_v2 generates degenerate output on a real checkpoint while mlx-lm is correct on the same weights #991 is checked and stated, rather than assumed either way, before the change lands.
  • cargo clippy --release --lib --tests --features metal,accelerate -- -D warnings is clean and cargo fmt --all -- --check passes.

Refs

Follow-up to #958 (PR #972, merged as db6cce9dc), which bounded the values the family-local expert loaders store; this is the adjacent problem that the values reaching those loaders are not the ones the checkpoint declared. Adjacent, not established as related: #991. Sibling follow-ups from the same trace: #973 and #974.

Activity

  1. added
    status:ready
    type:bug
    priority:medium
    area:models
    on Jul 30, 2026
  2. added
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    on Aug 3, 2026
  3. added a commit that references this issue on Aug 20, 2026
    a86e634
  4. self-assigned this
    on Aug 31, 2026
  5. added
    status:done
    and removed
    status:review
    on Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:mediumstatus:donetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions