Skip to content

OptiQ mixed-precision models produce garbage output (Qwen3.6-27B-OptiQ-4bit) #118

Closed

Description

@solderzzc

Summary

mlx-community/Qwen3.6-27B-OptiQ-4bit loads without error but generates incoherent tokens. This is independent of the thinking flag, so it is not #108.

Reproduction

.build/release/SwiftLM \
  --model ~/.cache/huggingface/hub/models--mlx-community--Qwen3.6-27B-OptiQ-4bit/snapshots/<hash>/ \
  --port 5430 --thinking --gpu-layers auto --prefill-size 64 --ctx-size 8192

Prompt: Name the capital of Japan. One word.

--thinking:                     " (' tml_htmlnsub\x00\n\n#\n\n# &г.� c#厉 code"
chat_template_kwargs {enable_thinking:false}:  "},-idthlaf�(aren系_1!"

The server starts normally, reports FULL GPU, logs no warnings, and returns HTTP 200. Only the tokens are wrong.

Isolation

The same binary on mlx-community/Qwen3.5-4B-4bit produces coherent output, so this is specific to the model rather than the build or environment.

What is different about this model

config.json describes mixed-precision quantization — 498 per-layer entries alongside the global defaults:

"quantization": {
  "group_size": 64, "bits": 4, "mode": "affine",
  "language_model.model.embed_tokens": { "bits": 8, "group_size": 64 },
  "language_model.model.layers.0.linear_attn.in_proj_qkv": { "bits": 8, "group_size": 64 },
  ...
}

optiq_metadata.json:

{ "method": "optiq_mixed_precision", "base_model": "Qwen/Qwen3.6-27B",
  "reference": "uniform_4bit", "target_bpw": 4.5, "achieved_bpw": 4.7686,
  "n_high_bits": 220, "n_low_bits": 276 }

Two properties that may matter, neither confirmed as the cause:

  1. Mixed precision. mlx-swift-lm does implement per-layer quantization (Libraries/MLXLMCommon/Load.swift:48-70), including language_model.-prefixed key fallbacks, so this ought to be handled. Whether every key in this config resolves against the actual module paths has not been checked. A silently unmatched key would fall back to the 4-bit default and dequantize the 8-bit layers wrongly — which would look exactly like this.
  2. Architecture. model_type is qwen3_5 and the module names include linear_attn.in_proj_qkv / in_proj_z / in_proj_a / in_proj_b, i.e. linear-attention blocks rather than standard attention.

The repo also ships an optiq/ subdirectory (mtp.safetensors, optiq_vision.safetensors) that is outside model.safetensors.index.json. Whether those are required at inference has not been established.

Not root-caused

I did not identify the cause and did not attempt a fix. Filing so the reproduction and config analysis are recorded.

Why it matters

This model is the one in #108, and OptiQ builds of other models are published in the same family. If mixed-precision quantization is mishandled generally, the failure is silent — no error, no warning, just wrong tokens.

Environment

  • SwiftLM d5a9d11 (main), release build
  • macOS 26.5.2, Apple M5 Pro, 68 GB
  • mlx-swift 133864c, mlx-swift-lm b9bf50b

Activity

  1. solderzzc commented on Aug 6, 2026

    @solderzzc
    MemberAuthor

    Investigation notes. I did not reach a confirmed root cause — recording what is ruled out and the one asymmetry worth a closer look, so nobody repeats this ground.

    Ruled out: extra safetensors colliding with model weights. loadWeights enumerates the model directory recursively (MLXLMCommon/Load.swift:22-34), so this repo's optiq/mtp.safetensors and optiq/optiq_vision.safetensors — neither of which appears in model.safetensors.index.json — are loaded alongside the shards into one weights dictionary, last-write-wins. But their tensor names are namespaced (mtp.*, vision_tower.*) and do not collide with language_model.*. Verified by reading the safetensors headers over HTTP range requests.

    Ruled out: per-layer quantization keys failing to match. The config's 498 entries are all language_model.…-prefixed. Neither sanitize strips that prefix — the LLM one normalizes toward it (MLXLLM/Models/Qwen35.swift:826-830), the VLM one leaves it — and Load.swift:56-62 additionally falls back to dict["language_model.\(path)"]. Module paths and config keys line up in both paths, so the 8-bit layers should not be silently dequantized as 4-bit.

    Ruled out: unmatched keys loading silently. model.update runs with verify: .all (.noUnusedKeys only under expert streaming), so a wholesale key mismatch would throw rather than leave weights uninitialized. The failing run threw nothing.

    The asymmetry. The +1 shift applied to RMSNorm weights differs between the two implementations:

    • VLM (MLXVLM/Models/Qwen35.swift:1264-1265) — applied unconditionally.
    • LLM (MLXLLM/Models/Qwen35.swift:737-741, 777-782) — gated on a heuristic:
      let shouldShiftNormWeights = hasMTPWeights || hasUnsanitizedConv1d

    If that heuristic ever misfires, every norm weight is off by one and the model emits noise while loading cleanly — exactly this symptom. For this checkpoint the MTP weights do reach weights (that recursive enumeration again), so hasMTPWeights should be true and the shift should apply, which argues against it being the cause here. It remains fragile: the signal is a file that is not part of the weight index, so anything that changes which files get enumerated changes how norms are scaled.

    Also worth noting: isVision comes from the --vision flag alone (Sources/SwiftLM/Server.swift:563), not from vision_config in config.json. A checkpoint with a vision tower therefore loads through the text-only path unless the flag is passed, and the two paths differ as above. @Gwada's successful run of a sibling model used --vision; my failing run did not.

    One-command test for anyone who has the model (mine is deleted; re-downloading is 20 GB):

    # same model, same prompt, only the flag differs
    ./SwiftLM --model <path> --port 5413            # observed: garbage
    ./SwiftLM --model <path> --port 5413 --vision   # untested — does this produce coherent output?

    If --vision is coherent and the default is not, the bug is in the text-only path for vision-capable checkpoints and the norm-shift heuristic is the first place to look. If both are garbage, the cause is elsewhere and the above is just a latent fragility.

  2. solderzzc commented on Aug 6, 2026

    @solderzzc
    MemberAuthor

    Root cause found and confirmed by controlled experiment. Correcting my earlier comment: I had ruled the norm-shift heuristic unlikely. It is the cause — I had the direction backwards.

    Mechanism

    loadWeights enumerates the model directory recursively (MLXLMCommon/Load.swift:22-34), so optiq/mtp.safetensors is loaded even though it is not in model.safetensors.index.json. That makes hasMTPWeights true in Qwen35.sanitize, which enables the +1 shift applied to every RMSNorm weight (MLXLLM/Models/Qwen35.swift:737-741, 777-782):

    let hasMTPWeights = weights.keys.contains { $0.contains("mtp.") }
    let shouldShiftNormWeights = hasMTPWeights || hasUnsanitizedConv1d

    This checkpoint's norms are already in final form. Adding 1 to all of them corrupts every normalization in the model — which loads cleanly and generates noise.

    The heuristic uses "MTP weights are present" as a proxy for "this checkpoint's norms need shifting". The OptiQ repo breaks the proxy by shipping an MTP file outside the weight index.

    Evidence

    Same binary (main), same model, same prompt. Only the presence of optiq/ differs; the probe line is instrumentation added to sanitize:

    run optiq/ probe output
    C present weights=1876 hasMTP=true shiftNorms=true '},-idthlaf�(aren系_1!'
    E moved out weights=1847 hasMTP=false shiftNorms=false 'Tokyo'
    F restored weights=1876 hasMTP=true shiftNorms=true '},-idthlaf�(aren系_1!'

    1876 − 1847 = 29, exactly the tensor count in optiq/mtp.safetensors. Removing the file fixes generation; restoring it breaks it again.

    A second bug, same origin

    --vision does not work around it. That path fails to load at all:

    Error: Unhandled keys ["mtp"] in Qwen35
    

    MLXVLM/Models/Qwen35.swift has no MTP module, so the same stray weights that silently corrupt the LLM path hard-fail the VLM path. Both stem from non-indexed .safetensors being loaded as if they were model weights.

    Fix options

    Not submitting a patch, since the right choice depends on intent I do not have:

    1. Restrict loading to the weight index when one exists (Load.swift). Fixes both bugs at the source. Risk: MTP weights are loaded deliberately for --mtp (MTPConfig.retainMTPWeights), so this must keep a path for them — presumably an explicit load rather than directory sweep.
    2. Derive the norm shift from something authoritative rather than MTP presence — a config or metadata marker identifying the converter convention. Needs knowledge of which checkpoints actually require the shift.
    3. Narrow the predicate to MTP keys that came from indexed shards. Smallest change, still a proxy.

    Option 1 looks correct to me but option 2 is what makes the heuristic robust. Whoever added the shift will know which checkpoints depend on it.

    Impact

    Any repo shipping extra .safetensors outside the index hits this: silent corruption on the text path, hard failure on the vision path. --stream-experts is unaffected (it uses .noUnusedKeys), which may be why this went unnoticed.

    Reproduced on SwiftLM d5a9d11, mlx-swift-lm b9bf50b, macOS 26.5.2, M5 Pro.

  3. solderzzc commented on Aug 6, 2026

    @solderzzc
    MemberAuthor

    Fix opened: SharpAI/mlx-swift-lm#43 (the code lives in the submodule).

    Two changes, because the file filter alone was not sufficient:

    1. Load.swift — when model.safetensors.index.json exists, only the files it lists are loaded. optiq/mtp.safetensors is no longer swept in, so the MTP fingerprint stops misfiring and the VLM path no longer chokes on Unhandled keys ["mtp"]. MTP add-ons remain loadable under SWIFTLM_MTP_ENABLE.
    2. Guard on the norm shift itself — with MTP explicitly enabled the add-on is loaded by design, the fingerprint fires again, and output was still noise. The shift is now applied only when the norm weights actually look zero-centered, which is the only case where adding 1 is meaningful.

    Results on Qwen3.6-27B-OptiQ-4bit:

    case before after
    text path '},-idthlaf�(aren系_1!' 'Tokyo'
    text path, SWIFTLM_MTP_ENABLE=1 noise 'Tokyo'
    vision path Unhandled keys ["mtp"] loads past it, then stops on that repo's missing processor_config.json (separate packaging gap)

    No behaviour change for Qwen3.5-4B-4bit or Qwen3.6-35B-A3B-4bit; SwiftLM's unit suites pass.

    One caveat carried into the PR: I could not recover the history of the norm-shift fingerprint (shallow submodule clone), so I do not know which checkpoint family it was written for. The guard only blocks the shift where the weight data shows it must be wrong, but anyone who knows the intended target should sanity-check it.

    Once #43 merges, SwiftLM needs a submodule bump to pick this up. @coolaj86 — this is very likely what you were hitting; #115 fixes the thinking-tag half separately.

  4. solderzzc commented on Aug 7, 2026

    @solderzzc
    MemberAuthor

    Shipped in b674 — OptiQ mixed-precision models load and generate correctly on the release binary.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions