Skip to content

fix(paroquant): fit affine grids that contain one-sided groups - #4160

Merged
Qubitium merged 1 commit into
mainfrom
fix/paroquant-affine-range
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/paroquant-affine-range

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Problem

_calc_affine_qparams fits the asymmetric quantizer by taking the group's
min/max directly, deriving scale = (max - min) / qmax, and then relying on
zero_point = min / scale to land inside [0, qmax]. That only holds when zero
already lies inside the group's range.

For a one-sided or constant group the zero point is unrepresentable, so
pack_params clamps it to a legal integer and the fitted grid shifts off the
data. The group's values then clip to 0 or qmax. Constant groups collapse
toward the scale floor instead of their own value.

This is not repairable by training. In the affine straight-through graph the
gradient of the loss with respect to zero_point_float cancels exactly
(_AffineQuantDequantSTE returns an explicit zero gradient, and the composed
reference graph does the same), so a wrong initial grid stays wrong through
both optimization stages.

Executing the production no-calibration fallback (_identity_result) with
FP32 weights, INT4, group size 128, asymmetric quantization:

input group before after
all +1 0.00014999999257270247 1.0
all -1 -0.00014999999257270247 -1.0

used_identity in that result refers to the rotation only; it never meant the
weights round-trip unchanged.

Fix

gptqmodel/quantization/paroquant/optimization.py, _calc_affine_qparams:

  1. include zero in the fitted range (low = min(min_val, 0),
    high = max(max_val, 0)), so a valid integer zero point always exists;
  2. round the zero point on that grid and clamp it to [0, qmax];
  3. re-fit the scale around the rounded zero point as
    max(-low / zp, high / (qmax - zp)), so both endpoints land on grid points
    instead of on the clipped boundary.

The scale upper bound is taken from the tensor dtype
(min(1e5, torch.finfo(dtype).max)) so fp16 weights cannot overflow the clamp.

Behaviour change is confined to groups whose range excludes zero; groups that
already straddle zero keep the same min/max fit.

Why the entry points are covered

_calc_affine_qparams is the single fit used by every affine path, so the fix
reaches all of them:

stage caller
quantizer init GroupLinearQuantizer.__init__
optimization pseudo_quantize_dequant (default fit and quantizer_impl="reference")
no-calibration fallback _identity_result
export _ParoQuantOptimLinear._export_runtime_state via pack_params

Tests

Added to tests/test_paroquant.py:

  • test_paroquant_affine_qparams_fit_one_sided_and_constant_groups — one-sided,
    constant, zero-only, mixed-sign, and threshold-neighbour rows; asserts the
    integer zero point stays in [0, qmax], every element is within half a step,
    and the result matches an independent float64 Torch oracle.
  • test_paroquant_identity_fallback_quantizes_one_sided_groups — the production
    fallback plus the empty-input optimize_paroquant_linear path.
  • test_paroquant_identity_fallback_preserves_one_sided_groups_in_bfloat16 —
    the same fit under a bfloat16 model dtype.
  • test_paroquant_reference_optimizer_keeps_one_sided_groups_representable —
    quantizer initialization and result export with zero epochs.
  • test_paroquant_optimizer_export_qparams_reproduce_quantized_weight — the
    exported q_scales/q_zeros reproduce the packed pseudo weight bit-exactly.

Validation

  • New tests pass; the full ParoQuant test module shows no regression against the
    unmodified baseline.
  • ruff check passes on both changed files.
  • Oracle agreement: max absolute drift 7.2e-08, max relative drift 8.9e-08
    versus the float64 reference over all covered group shapes.

Scope

Not changed: symmetric quantization, rotation learning, channel scales, packing
layout, and the MLX optimizer (it mirrors the same min/max fit in
mlx_paroquant_optimize.py; a follow-up can align it once the Torch path is
settled).

`_calc_affine_qparams` derived the scale from `(max - min) / qmax` and then clamped the zero point into `[0, qmax]`. A group whose values are all positive or all negative has no representable zero point, so the clamped zero point shifted the grid and clipped the group to 0 or `qmax`. Constant groups collapsed to roughly `1e-5` instead of their value, and the affine zero-point gradient is exactly zero, so optimization could not repair the initial grid.

Include zero in the fitted range, round the zero point on that grid, and re-fit the scale so both endpoints land inside the grid. Add regression coverage for the quantizer fit, optimizer initialization/export, and the no-calibration identity fallback.
@Qubitium
Qubitium merged commit f1023db into main Nov 16, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/paroquant-affine-range branch November 16, 2026 02:34

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review fixes are in #4165 (d1083670a): FP16 range/clamp failures, low-precision zero-point rounding, and bounded-scale export consistency. Also removed optimizer environment fallbacks and clarified mixed-sign saturation. All 29 focused regressions pass per runtime; the FP64 audit has zero code mismatches. Full-module fixture/cache failures reproduce on the baseline.

Qubitium added a commit that referenced this pull request Nov 17, 2026
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.
Qubitium added a commit that referenced this pull request Nov 17, 2026
…aded weights (#4687)

* fix(paroquant): mirror the Torch affine grid fit in the MLX bridge

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.

* fix(pack_block): accept inference-mode-loaded weights

`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.

* test(mlx): repair stale oracles, backend skips, and the EXL3 CPU contract

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.

* test(mlx): pin idempotent re-export of the Gemma 3 split

`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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants