Repository navigation
fix(mlx): mirror the Torch affine grid fit and pack inference-mode-loaded weights - #4687
Merged
Merged
Conversation
The MLX optimizer still fitted asymmetric qparams with `(max - min) / qmax` and returned `minimum / scale` as the zero point, the formula the Torch reference retired in #4160/#4165. A one-sided or constant group has no representable zero point in that grid, so every value clipped onto code 0 or qmax and the group collapsed to a single code. The optimizer could not repair it: the affine straight-through gradient with respect to the zero point cancels exactly, so the drift was silent. Port `_calc_affine_qparams` line for line: include zero in the fitted range, round the integer zero point onto that grid, re-fit the scale per side from the remaining code budget, then clamp. The bridge keeps its existing contract of returning `-zero_point`, which `_pseudo_quantize` and the runtime packer both consume. Tests (tests/test_mlx_paroquant_optimize.py): - new `test_paroquant_mlx_affine_qparams_match_torch_reference[2,4,8]` fits positive-only, negative-only, balanced and constant groups, requires exact scale/zero parity with `_calc_affine_qparams`, exact `_pseudo_quantize` parity with `pseudo_quantize_dequant`, and asserts the one-sided groups use more than two codes; - new `test_paroquant_mlx_affine_qparams_promote_low_precision_weights[fp16,bf16]` pins the fp32 promotion the callers rely on; - the Qwen3.8 export oracle now derives its expected qparams from `_calc_affine_qparams` instead of re-deriving the retired formula, and the processor monkeypatches target the lazily imported `gptqmodel.quantization.mlx_paroquant_optimize` module; - `test_paroquant_mlx_trained_quality_tracks_torch` now bounds the documented Adam `sqrt(v) + eps` amplification of a float32-noise-floor gradient entry instead of a flat 2e-3 maximum that failed on a single tie flip. Red evidence with the retired fit restored: 5 failed, 49 deselected (`-k affine_qparams`). Green after the fix: 5 passed; whole module 54 passed.
`pack_block` slices the caller's weight, but a weight can arrive without a version counter even though it is not flagged as an inference tensor: `load_state_dict(assign=True)` under `torch.inference_mode()` followed by `module.to(dtype)` materializes exactly that tensor on recent Torch. Slicing it raises `RuntimeError: Inference tensors do not track version counter` and the pack fails during quantization. After moving the weight to the host, probe `_version` and materialize a copy when the probe raises. `pack_block` already runs under `inference_mode()`, so the copy follows the active mode and is sliceable; the caller's tensor is never mutated. Test: `test_pack_block_accepts_inference_mode_loaded_weights[2,3,4,8]` builds the poisoned tensor through that loader transition, asserts the trigger (`not is_inference()` yet `_version` raises), then requires bit-exact parity with a version-tracked control and the independent word oracle, plus an unchanged caller weight. Red evidence with the guard removed: 4 failed, 50 deselected (`-k inference_mode`). Green after the fix: module 54 passed.
…ract Upstream moved under several MLX tests; repair the oracles that pinned the retired behaviour instead of loosening them: - `test_mlx_exl3_pipeline.py`: #3601 removed `EXL3Processor`'s CPU/Metal MLX quantization branch and `models/base.py` already rejects EXL3 quantization without CUDA, so drop `test_exl3_processor_routes_cpu_quantization_through_mlx` and keep one contract test that a CPU target raises. The zero-Hessian fallback now reports the normalized reconstruction error as its proxy error, so compare it to the oracle (and assert both sides took the fallback) rather than asserting zero. - `test_mlx_qwen38_27b_shapes.py`: the QQQ dynamic-input oracle narrowed BF16 activations to FP16 and cast the epilogue early, which #4537/#4534 no longer do. Consume the resident inputs, cast once, and allow one output ULP of the activation dtype (8e-3 bf16 / 2e-3 fp16). - `test_mlx_qqq_quantization.py`: `scale_extra` is fitted to the produced codes, so a documented one-step tie flip moves it by at most one group scale. Compare exactly on rows without code drift, bound the drift elsewhere, and require the exported scale to describe the emitted codes. - `test_mlx_awq_variants.py`: the Torch GEMV_FAST/LLM_AWQ sources require group_size 128 and 128-aligned out_features (#3717); fall back to the MLX holder as the packed source for the combinations the Torch contract rejects, and allow one activation-dtype ULP (bf16 is 2**-7 relative, not 2e-3). - `test_mlx_foem_quantization.py`: native processors read routing metadata from `NamedModule`, so wrap the probe layer. - `test_mlx_qqq_processor.py`: `__init__` records the requested backend; set `BACKEND.AUTO` so the portable Torch holder is the expected macOS choice. - `test_mlx_dense_methods.py` / `test_mlx_method_selection.py`: the MLX BNB holder reuses `BitsAndBytesLinear`'s dependency probe, so skip without `bitsandbytes` installed instead of failing on the import. Full MLX suite (tests/test_*mlx*.py tests/test_q4_torch_apple.py tests/test_pack_block_batched.py): 5377 passed, 83 skipped, 5 failed. The five failures need `/monster/data/model/...` checkpoints that are absent here (`test_mlx_generate` and the four `test_q4_torch_apple` generation tests) and are unrelated to these changes.
`normalize_mlx_rope_config` mutates in place and runs on every export, so a config that was already translated must not accumulate `rope_scaling` or lose `rope_local_base_freq` on the second pass. The existing idempotency test only covered the flat Llama path; cover the split mapping too.
Qubitium
force-pushed
the
fix/mlx-regressions
branch
from
November 17, 2026 09:47
1d9f1e9 to
a4fa1aa
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TL;DR
Four commits from a verification pass over the MLX suites: two real regressions with new red-tested coverage, and test repairs for oracles that were pinning retired behaviour (or failing on a missing optional dependency). #4684 (the #4678 Gemma 3 RoPE fix) is already merged; this PR is based on it.
1.
fix(paroquant): MLX affine qparams drifted from the Torch reference_quantizer_parametersingptqmodel/quantization/mlx_paroquant_optimize.pystill fitted asymmetric qparams with(max - min) / qmaxand returnedminimum / scaleas the zero point — the formula the Torch reference retired in #4160/#4165. A one-sided or constant group has no representable zero point in that grid, so every value clipped onto code 0 orqmaxand the group collapsed to a single code.It could not self-heal: the affine straight-through gradient with respect to the zero point cancels exactly, so the optimizer never saw the drift.
The bridge now mirrors
_calc_affine_qparamsline for line — include zero in the fitted range, round the integer zero point onto that grid, re-fit the scale per side from the remaining code budget, clamp — while keeping its existing-zero_pointreturn contract that_pseudo_quantizeand the runtime packer consume.test_paroquant_mlx_affine_qparams_match_torch_reference[2,4,8]_calc_affine_qparams; exact_pseudo_quantizevspseudo_quantize_dequantparity; one-sided groups must use more than two codestest_paroquant_mlx_affine_qparams_promote_low_precision_weights[fp16,bf16]Red: with the retired fit restored,
-k affine_qparams→ 5 failed. Green: 5 passed; module 54 passed.2.
fix(pack_block): handling of inference-mode-loaded weightspack_blockslices the caller's weight, but a weight can arrive without a version counter while not being flagged as an inference tensor:load_state_dict(assign=True)undertorch.inference_mode()followed bymodule.to(dtype)produces exactly that on recent Torch. Slicing raisesRuntimeError: Inference tensors do not track version counter, so quantization died in the packer.After moving the weight to the host, the packer now probes
_versionand materializes a copy when the probe raises.pack_blockalready runs underinference_mode(), so the copy follows the active mode and is sliceable; the caller's tensor is never mutated.test_pack_block_accepts_inference_mode_loaded_weights[2,3,4,8]builds the tensor through that loader transition, asserts the trigger (not is_inference()yet_versionraises), then requires bit-exact parity with a version-tracked control and the independent word oracle, plus an unchanged caller weight.Red: with the guard removed → 4 failed. Green: module 54 passed.
3.
test(mlx): repair stale oracles, backend skips, and the EXL3 CPU contracttest_mlx_exl3_pipeline.pyEXL3Processor's CPU/Metal MLX quantization branch andmodels/base.pyalready rejects EXL3 without CUDA, so the routing test was deleted and one contract test kept. The zero-Hessian fallback reports the normalized reconstruction error as its proxy error, so the oracle is compared instead of asserting zero (and both sides must report the fallback).test_mlx_qwen38_27b_shapes.pytest_mlx_qqq_quantization.pyscale_extrais fitted to the produced codes, so a documented one-step tie flip moves it by at most one group scale. Exact on rows without code drift, bounded drift elsewhere, and the exported scale must describe the emitted codes.test_mlx_awq_variants.pygroup_size=128and 128-aligned out features (#3717); fall back to the MLX holder as the packed source for combinations the Torch contract rejects, and allow one activation-dtype ULP (bf16 is 2^-7 relative, not 2e-3).test_mlx_foem_quantization.pyNamedModule, so the probe layer is wrapped.test_mlx_qqq_processor.py__init__records the requested backend;BACKEND.AUTOis the portable-Torch-holder case on macOS.test_mlx_dense_methods.py,test_mlx_method_selection.pyBitsAndBytesLinear's dependency probe, soimportorskip("bitsandbytes")instead of failing on the import.test_mlx_rope_parameters_4607.pynormalize_mlx_rope_configmutates in place and runs on every export, so pin that a second pass over an already-translated Gemma 3 config does not accumulaterope_scalingor droprope_local_base_freq.4. Validation
The five failures are environment-only:
test_mlx.py::TestMlxGenerate::test_mlx_generateand the fourtest_q4_torch_apple.py::TestsQ4Torch::test_generation_*require/monster/data/model/...checkpoints that are absent on this host (HFValidationError: Repo id must be in the form 'repo_name' or 'namespace/repo_name'). They are unrelated to these changes and are not skipped, so the gap stays visible.5. Reviewer notes