Skip to content

fix(rotation,calibration,qqq,w4a): device-aware Hadamard, truncation side, QQQ export scale, exact FP8 divide (#4008) - #4016

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-4008
Nov 14, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-4008

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4008

Four independent correctness fixes, each with a regression test that fails on
origin/main and passes here.

TL;DR

# Area Root cause Fix
1 Rotation Hadamard backend chosen once per process; weight forced to CUDA dispatch per call from x.device.type; compute on the weight's device
2 Calibration trim trimmed by padding_side, not truncation_side trim by tokenizer.truncation_side
3 QQQ export INT8 channel scale fitted to W, not the quantized Q fit scale_extra to Q (Torch and MLX)
4 W4AFP8 quantizer Triton's approximate / is one ULP off near E4M3 midpoints tl.div_rn for the token divide

Diff: 5 source files, 4 test files, 1 docs page, 1 README link.


1. Rotation Hadamard ops now follow the tensor device

Root cause. _hadamard_with_grad read fast_hadamard_transform.hadamard_transform
from a module global that import_fast_hadamard_transform set once per process
from hadamard_available() (gptqmodel/quantization/rotation/hadamard_utils.py:244
on main). On a CUDA host with the JIT extension built that global is the
CUDA-only op, so every CPU tensor raised NotImplementedError ... 'CPU' backend.
apply_exact_had_to_linear additionally did W_.float().cuda() /
b_.float().cuda() (hadamard_utils.py:327,336), so a CPU-only host failed with
RuntimeError: No CUDA GPUs are available even though models/base.py:2003-2010
deliberately routes MPS rotation through the CPU.

Old flow:

flowchart TD
    A["import_fast_hadamard_transform"] --> B{"hadamard_available"}
    B -->|"true"| C["fast_hadamard_transform = _FastHadamardTransform<br/>CUDA-only kernel"]
    B -->|"false"| D["Triton or portable Torch fallback"]
    C --> E["matmul_hadU_cuda on any device"]
    E --> F["CPU tensor reaches the CUDA op"]
    F --> G["NotImplementedError: CPU backend"]
    style G fill:#ffe0e0,stroke:#dc2626
Loading

New flow (_transform_for, hadamard_utils.py:232):

flowchart TD
    A["matmul_hadU_cuda(X, hadK, K)"] --> B["_hadamard_with_grad(x, scale)"]
    C["apply_exact_had_to_linear(module, had_dim, output)"] --> D["W_ = weight.data.float().to(weight.device)"]
    D --> B
    B --> E["_transform_for(x)"]
    E --> F{"x.device.type == 'cuda'"}
    F -->|"yes"| G["fast_hadamard_transform.hadamard_transform<br/>native package or JIT gptqmodel_hadamard op"]
    F -->|"no: cpu, mps, xpu, meta"| H["_TorchHadamardTransform.hadamard_transform<br/>portable FP32 butterfly"]
    G --> I["normalized Walsh transform"]
    H --> I
    I --> J{"requires_grad and grad enabled"}
    J -->|"yes"| K["_HadamardAutograd<br/>backward stays portable FP64"]
    J -->|"no"| L["plain call"]
    style G fill:#e8f4ff,stroke:#3b82f6
    style H fill:#eafbe7,stroke:#22c55e
Loading
Mechanism Before (main) After
backend selection per process, from hadamard_available() (hadamard_utils.py:244) per call, from x.device.type (hadamard_utils.py:232)
weight/bias placement W_.float().cuda(), b_.float().cuda() (:327, :336) .to(dev) where dev = module.weight.device (:345, :354)
had_dim != -1 branches called the CUDA symbol directly (:353, :363, :372) _hadamard_with_grad, same dispatch (:371, :381, :390)

Failure contract: a CUDA tensor still takes the accelerator backend; only
non-CUDA devices take the portable path. There is no silent downgrade of a CUDA
call.

Fail before / pass after — both directions.

(a) CUDA host with the JIT extension built, CPU tensor:

$ PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d \
    /opt/venvs/cu130t/bin/python /tmp/i4008/repro1_gpu.py
# before
cuda_available: True hadamard_available: True
cpu forward FAIL: NotImplementedError Could not run 'gptqmodel_hadamard::fast_hadamard_transform'
                 with arguments from the 'CPU' backend.
# after
cuda_available: True hadamard_available: True
cpu forward OK shape: (2, 256) device: cpu

(b) CPU-only host (CUDA_VISIBLE_DEVICES=), apply_exact_had_to_linear:

$ PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES= /opt/venvs/cu130t/bin/python /tmp/i4008/repro1_cpu.py
# before
cuda_available: False
exact had FAIL: RuntimeError No CUDA GPUs are available
# after
cuda_available: False
exact had OK weight device: cpu finite: True

Regression tests (same command, source reverted vs. fixed):

$ python -m pytest tests/test_rotation_persistence.py -q \
    -k "dispatches or accelerator or weight_device or head_dim"
# before: 5 failed, 1 passed
FAILED ...::test_online_hadamard_dispatches_on_the_tensor_device[256]
FAILED ...::test_online_hadamard_dispatches_on_the_tensor_device[2560]
FAILED ...::test_exact_hadamard_fuses_on_the_weight_device
FAILED ...::test_exact_hadamard_head_dim_uses_the_weight_device[True]
FAILED ...::test_exact_hadamard_head_dim_uses_the_weight_device[False]
# after: 6 passed

Docs: docs/rotation-device-dispatch.md (linked from README.md).


2. Overlong calibration rows truncate by truncation_side

Root cause. gptqmodel/utils/calibration.py:471 chose the slice with
if padding_side == "left": row[-max:], so any padding_side="left" tokenizer
front-truncated every overlong row and dropped its BOS / attention-sink token.
padding_side and truncation_side are independent tokenizer settings (HF
default: truncation_side="right").

New flow (calibration.py:455-486):

flowchart LR
    A["row_len > max_positions"] --> B{"tokenizer.truncation_side"}
    B -->|"left"| C["keep row[-max_positions:]"]
    B -->|"right"| D["keep row[:max_positions]"]
    B -->|"other"| E["ValueError"]
    style E fill:#ffe3e3,stroke:#dc2626
Loading

padding_side is still validated and still controls batch padding in
collate_data; only the trim direction changed. The trim log line now records
truncation_side.

Fail before / pass after — the issue's exact case: real Llama-3 tokenizer,
max_position_embeddings=32, GPTQMODEL_LOG_CALIBRATION_SAMPLES=1,
padding_side="left" (default truncation_side="right"):

# before, on origin/main
$ PYTHONPATH=/tmp/i4008-main python /tmp/i4008/repro2_llama.py
INFO  Calibration sample 1/1: tokens=32 preview='. The quick brown fox jumps over the lazy dog. The quick brown fox ...'
first_token_is_bos: False bos_id: 128000
len: 32 first8: . The quick brown fox jumps over the

# after
$ PYTHONPATH=$PWD python /tmp/i4008/repro2_llama.py
INFO  Calibration sample 1/1: tokens=32 preview='<|begin_of_text|>The quick brown fox jumps over the lazy dog. The quick ...'
first_token_is_bos: True bos_id: 128000
len: 32 first8: <|begin_of_text|>The quick brown fox jumps over the
$ python -m pytest tests/test_calibration_truncation.py -q
# before: 3 failed, 2 passed
FAILED ...::test_left_padding_keeps_the_bos_token
FAILED ...::test_left_and_right_padding_trim_identically
FAILED ...::test_invalid_truncation_side_is_rejected
# after: 5 passed

test_truncation_side_left_keeps_the_tail pins that an explicit
truncation_side="left" still trims the front; test_short_rows_are_not_trimmed
pins that rows inside the budget are untouched.


3. QQQ grouped export fits the INT8 channel scale to Q

Root cause. The grouped (W4A8) exporter ran
quantizer_extra.find_params(self.layer.weight.data.clone()) while the layer
still held W (gptqmodel/quantization/qqq.py:1084 main path, :530 fallback
path; mlx_qqq.py:132-134 mirrored it). GPTQ error propagation pushes max|Q|
above max|W|, so int8 codes exceeded 127 and were clamped; the packed export
then differed from the in-memory wq used for loss logging and next-layer
replay. Upstream QQQ assigns weight.data = Q before fitting the scale.

New data flow:

flowchart LR
    W["W = layer.weight.data"] --> Q["GPTQ error propagation -> Q"]
    Q --> S["find_params(Q) -> scale_extra = max|Q|/127"]
    S --> G["pack: s_group = raw_scales / scale_extra"]
    G --> D["dequant: round(int4_code * s_group) * scale_extra"]
    D --> R["reproduces Q to one INT8 step, no clamp"]
    W -.->|"removed"| S
    style S fill:#eafbe7,stroke:#22c55e
Loading

Measured on the regression case (Linear(256 -> 128), fp16, gs=128, 8
calibration batches, seed 4008; wq/scales/s_extra from QQQ.quantize(),
then QQQTorchLinear.pack() + _dequantize_weight_for_torch()):

measurement before after
`max W /max
s_extra fitted from W Q (bitwise equal to an independent `max
pre-clamp INT8 max 141.364 (54 codes > 127.5) 127.0000076 (0 codes > 127.5)
packed INT8 plane max 128.0 (clamped) 127.0
`max dequantized - wq `
half INT8 step (0.5 * max s_channel) 0.00088333 0.00094244

The export is exact to the format's own INT8 step (max error <= 0.5 * step)
and no code is clamped. Bitwise equality with the fp16 wq is not achievable
through an INT8 plane; what is pinned is that the dequantized export reproduces
wq within half a step instead of drifting 16 steps away.

$ python -m pytest tests/test_qqq_export_scale.py -q
# before: 2 failed, 1 passed
FAILED ...::test_grouped_export_scale_derives_from_the_quantized_weight
FAILED ...::test_grouped_export_does_not_saturate_and_reproduces_wq
# after: 3 passed

The test recomputes the 8-bit scale independently and asserts the case really
overshoots (max|Q| > max|W|, and the W-fitted scale would clamp more than zero
codes), so it cannot pass vacuously.


4. W4AFP8 Triton token quantizer is bit-exact

Root cause. gptqmodel/nn_modules/qlinear/w4a_triton.py:114 used Triton's
plain /, which can lower to the approximate reciprocal sequence and is one ULP
off near an E4M3 rounding midpoint. The docstring promises bit-exact agreement
with fp8_token_qdq, the Torch path GPTQ replay calibrates against.

Fix. tl.div_rn(x, scale) for the token divide (w4a_triton.py:120),
keeping scale = amax / 448.0 as-is (div_rn on the scale too would change the
reference scale and add mismatches).

$ python -m pytest tests/kernels/test_w4afp8_gb10.py -q -k bit_exact_with_fp8
# before
E  AssertionError: 104 of 5242880 codes differ from the reference
FAILED ...test_fp8_pack_is_bit_exact_with_fp8_token_qdq[5120-1024-dtype0]
1 failed, 3 passed
# after
4 passed

The test (5120x1024 fp16, torch.Generator(seed=8)) asserts code bytes and
scales equal the independent FP32 Torch reference and that
codes.float() * scale cast to the input dtype is bitwise equal to
fp8_token_qdq(x). After the fix: 0 code mismatches, 0 scale mismatches,
max|qdq_triton - qdq_torch| = 0.0.


Failure and ambiguity contract

Situation Before After
CPU tensor on a CUDA host with the Hadamard extension built NotImplementedError: CPU backend portable butterfly, stays on CPU
CPU-only host, rotation quantization RuntimeError: No CUDA GPUs are available exact Hadamard runs on CPU
CUDA tensor CUDA op CUDA op (unchanged)
Left-padded tokenizer, right truncation front-truncated, BOS dropped tail-truncated, BOS kept
Invalid truncation_side silently reused padding_side ValueError
QQQ gs=128 export with `max Q > max
W4AFP8 near an E4M3 midpoint code flipped (104/5.2M) bit-exact

Tests

Test What it pins
test_rotation_persistence.py::test_online_hadamard_dispatches_on_the_tensor_device CPU tensor never reaches the CUDA-only op (K=1 and K=40)
test_rotation_persistence.py::test_online_hadamard_still_uses_the_accelerator_on_cuda CUDA tensor still uses the accelerator backend
test_rotation_persistence.py::test_exact_hadamard_fuses_on_the_weight_device CPU weight stays on CPU and matches matmul_hadU
test_rotation_persistence.py::test_exact_hadamard_head_dim_uses_the_weight_device same for the had_dim branch, weight and bias
test_calibration_truncation.py left padding keeps BOS; left == right for truncation_side="right"; explicit "left" keeps the tail; invalid value rejected
test_qqq_export_scale.py scale_extra equals an independent `max
kernels/test_w4afp8_gb10.py::test_fp8_pack_is_bit_exact_with_fp8_token_qdq bitwise fp8_pack vs an independent FP32 E4M3 reference and vs fp8_token_qdq, four shapes/dtypes

The rotation tests use a stand-in backend whose non-CUDA call raises the same
NotImplementedError as the JIT op, so dispatch is exercised whether or not the
extension is built.

Validation

Hardware: NVIDIA RTX 4090 (Ada, SM 8.9,
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d) and AMD Radeon AI PRO R9700 (gfx1201,
HIP_VISIBLE_DEVICES=2). CUDA venv torch 2.16.0.dev+cu130 / Triton 3.9.0;
ROCm venv torch 2.16.0.dev+rocm10.1.

CUDA (PYTHONPATH=$PWD, pinned 4090):

Command Result
pytest tests/test_rotation_persistence.py tests/test_hadamard_portable_range.py -q 26 passed, 1 skipped
pytest tests/test_calibration_truncation.py tests/test_calibration_windows.py -q 18 passed
pytest tests/test_calibration_data_device.py -q (unit + integration) 18 passed, 4 skipped
pytest tests/test_qqq_export_scale.py tests/test_qqq_dynamic_group_size.py -q 4 passed
pytest tests/test_qqq_cpu.py tests/test_qqq_conv_capture.py -q 54 passed
pytest tests/test_qqq_inference.py -q 1 passed
pytest tests/kernels/test_w4afp8_gb10.py -q 19 passed
pytest tests/models/test_w4a_hardware_forward.py -q -k online_hadamard 8 passed, 8 skipped (NVFP4 needs SM 12.1)
pytest tests/test_extension_load_api.py tests/test_rocm_kernel_contracts.py -q 437 passed
pytest the four new/changed files together (final run on the merged tree) 53 passed, 1 skipped

ROCm (HIP_VISIBLE_DEVICES=2, no ROCR_VISIBLE_DEVICES):

Command Result
pytest tests/test_rotation_persistence.py tests/test_hadamard_portable_range.py tests/test_calibration_truncation.py tests/test_qqq_export_scale.py -q 34 passed, 1 skipped

The single skip is the pre-existing "Rotated checkpoint not available on this
runner" case. Item 4 is CUDA-only by construction: the Triton FP8 kernel lowers
to ttg.nvidia_mma and PTX cvt.rn.satfinite.e4m3x2.f32, and its own gate
(native_fp8_gemm_error) rejects HIP, so the W4AFP8 file does not run on ROCm.

Lint:

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

Reviewer notes / limitations

  • apply_exact_had_to_linear still rewrites a 1-D bias to rank 2 in the
    branches that do not transform it (had_dim=-1, output=False). That
    predates this change, is independent of device dispatch, and is left out of
    scope; the docs page records it under "Not in scope".
  • The MLX QQQ edit (mlx_qqq.py) mirrors the Torch fix but could not be
    executed here (no mlx runtime on this Linux host); the two Torch oracles in
    tests/test_mlx_qqq_quantization.py were updated to derive scale_extra from
    the quantized output.
  • tests/test_qqq_quantizer.py::test_qqq_mse_grid_chunks fails 24 CUDA cases on
    this host with ~1e-7 scale differences. It fails identically on a pristine
    origin/main worktree (24 failed), so it is pre-existing and unrelated to
    this diff.
  • Rotation now runs its exact Hadamard on the weight's device, which is the CPU
    during rotate_model (weights are moved back to CPU per layer). That is a
    one-time CPU cost instead of a CUDA kernel; it is what the issue asks for and
    what makes the CPU-only and MPS paths work. A follow-up could pass an explicit
    compute device if rotation time matters for very large models.

…QQ export scale to Q, exact FP8 divide (#4008)

- rotation: pick the Hadamard backend from `x.device.type` per call and run
  `apply_exact_had_to_linear` on the weight's own device instead of forcing
  `.cuda()`. Fixes CPU-tensor rotation on CUDA hosts and rotation on a
  CPU-only host.
- calibration: trim overlong rows by `tokenizer.truncation_side` (HF default
  right) instead of `tokenizer.padding_side`, so left-padded batches keep the
  BOS/attention-sink token.
- qqq/mlx_qqq: fit the exported INT8 channel scale to the quantized Q, not
  the pre-quantization W, so packed codes no longer saturate and the export
  reproduces the in-memory `wq`.
- w4a_triton: divide by the token scale with `tl.div_rn` so the Triton FP8
  quantizer is bit-exact with `fp8_token_qdq`.

Adds device, truncation-side, QQQ pack/dequant, and bitwise FP8 pack
regression tests, and documents the rotation dispatch flow.
Comment thread tests/test_rotation_persistence.py Resolved
Qubitium and others added 2 commits November 14, 2026 15:27
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant