Repository navigation
fix(rotation,calibration,qqq,w4a): device-aware Hadamard, truncation side, QQQ export scale, exact FP8 divide (#4008) - #4016
Merged
Merged
Conversation
…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.
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
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.
Fixes #4008
Four independent correctness fixes, each with a regression test that fails on
origin/mainand passes here.TL;DR
x.device.type; compute on the weight's devicepadding_side, nottruncation_sidetokenizer.truncation_sideW, not the quantizedQscale_extratoQ(Torch and MLX)/is one ULP off near E4M3 midpointstl.div_rnfor the token divideDiff: 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_gradreadfast_hadamard_transform.hadamard_transformfrom a module global that
import_fast_hadamard_transformset once per processfrom
hadamard_available()(gptqmodel/quantization/rotation/hadamard_utils.py:244on
main). On a CUDA host with the JIT extension built that global is theCUDA-only op, so every CPU tensor raised
NotImplementedError ... 'CPU' backend.apply_exact_had_to_linearadditionally didW_.float().cuda()/b_.float().cuda()(hadamard_utils.py:327,336), so a CPU-only host failed withRuntimeError: No CUDA GPUs are availableeven thoughmodels/base.py:2003-2010deliberately 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:#dc2626New 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:#22c55emain)hadamard_available()(hadamard_utils.py:244)x.device.type(hadamard_utils.py:232)W_.float().cuda(),b_.float().cuda()(:327,:336).to(dev)wheredev = module.weight.device(:345,:354)had_dim != -1branches: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:
(b) CPU-only host (
CUDA_VISIBLE_DEVICES=),apply_exact_had_to_linear:Regression tests (same command, source reverted vs. fixed):
Docs:
docs/rotation-device-dispatch.md(linked fromREADME.md).2. Overlong calibration rows truncate by
truncation_sideRoot cause.
gptqmodel/utils/calibration.py:471chose the slice withif padding_side == "left": row[-max:], so anypadding_side="left"tokenizerfront-truncated every overlong row and dropped its BOS / attention-sink token.
padding_sideandtruncation_sideare independent tokenizer settings (HFdefault:
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:#dc2626padding_sideis still validated and still controls batch padding incollate_data; only the trim direction changed. The trim log line now recordstruncation_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"(defaulttruncation_side="right"):test_truncation_side_left_keeps_the_tailpins that an explicittruncation_side="left"still trims the front;test_short_rows_are_not_trimmedpins that rows inside the budget are untouched.
3. QQQ grouped export fits the INT8 channel scale to
QRoot cause. The grouped (W4A8) exporter ran
quantizer_extra.find_params(self.layer.weight.data.clone())while the layerstill held
W(gptqmodel/quantization/qqq.py:1084main path,:530fallbackpath;
mlx_qqq.py:132-134mirrored it). GPTQ error propagation pushesmax|Q|above
max|W|, so int8 codes exceeded 127 and were clamped; the packed exportthen differed from the in-memory
wqused for loss logging and next-layerreplay. Upstream QQQ assigns
weight.data = Qbefore 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:#22c55eMeasured on the regression case (
Linear(256 -> 128), fp16,gs=128, 8calibration batches, seed 4008;
wq/scales/s_extrafromQQQ.quantize(),then
QQQTorchLinear.pack()+_dequantize_weight_for_torch()):/maxs_extrafitted fromWQ(bitwise equal to an independent `max0.5 * max s_channel)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
wqis not achievablethrough an INT8 plane; what is pinned is that the dequantized export reproduces
wqwithin half a step instead of drifting 16 steps away.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 zerocodes), so it cannot pass vacuously.
4. W4AFP8 Triton token quantizer is bit-exact
Root cause.
gptqmodel/nn_modules/qlinear/w4a_triton.py:114used Triton'splain
/, which can lower to the approximate reciprocal sequence and is one ULPoff 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.0as-is (div_rnon the scale too would change thereference scale and add mismatches).
The test (5120x1024 fp16,
torch.Generator(seed=8)) asserts code bytes andscales equal the independent FP32 Torch reference and that
codes.float() * scalecast to the input dtype is bitwise equal tofp8_token_qdq(x). After the fix: 0 code mismatches, 0 scale mismatches,max|qdq_triton - qdq_torch| = 0.0.Failure and ambiguity contract
NotImplementedError: CPU backendRuntimeError: No CUDA GPUs are availabletruncation_sidepadding_sideValueErrorTests
test_rotation_persistence.py::test_online_hadamard_dispatches_on_the_tensor_devicetest_rotation_persistence.py::test_online_hadamard_still_uses_the_accelerator_on_cudatest_rotation_persistence.py::test_exact_hadamard_fuses_on_the_weight_devicematmul_hadUtest_rotation_persistence.py::test_exact_hadamard_head_dim_uses_the_weight_devicehad_dimbranch, weight and biastest_calibration_truncation.pytruncation_side="right"; explicit"left"keeps the tail; invalid value rejectedtest_qqq_export_scale.pyscale_extraequals an independent `maxkernels/test_w4afp8_gb10.py::test_fp8_pack_is_bit_exact_with_fp8_token_qdqfp8_packvs an independent FP32 E4M3 reference and vsfp8_token_qdq, four shapes/dtypesThe rotation tests use a stand-in backend whose non-CUDA call raises the same
NotImplementedErroras the JIT op, so dispatch is exercised whether or not theextension 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 torch2.16.0.dev+cu130/ Triton3.9.0;ROCm venv torch
2.16.0.dev+rocm10.1.CUDA (
PYTHONPATH=$PWD, pinned 4090):pytest tests/test_rotation_persistence.py tests/test_hadamard_portable_range.py -qpytest tests/test_calibration_truncation.py tests/test_calibration_windows.py -qpytest tests/test_calibration_data_device.py -q(unit + integration)pytest tests/test_qqq_export_scale.py tests/test_qqq_dynamic_group_size.py -qpytest tests/test_qqq_cpu.py tests/test_qqq_conv_capture.py -qpytest tests/test_qqq_inference.py -qpytest tests/kernels/test_w4afp8_gb10.py -qpytest tests/models/test_w4a_hardware_forward.py -q -k online_hadamardpytest tests/test_extension_load_api.py tests/test_rocm_kernel_contracts.py -qpytestthe four new/changed files together (final run on the merged tree)ROCm (
HIP_VISIBLE_DEVICES=2, noROCR_VISIBLE_DEVICES):pytest tests/test_rotation_persistence.py tests/test_hadamard_portable_range.py tests/test_calibration_truncation.py tests/test_qqq_export_scale.py -qThe 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_mmaand PTXcvt.rn.satfinite.e4m3x2.f32, and its own gate(
native_fp8_gemm_error) rejects HIP, so the W4AFP8 file does not run on ROCm.Lint:
Reviewer notes / limitations
apply_exact_had_to_linearstill rewrites a 1-D bias to rank 2 in thebranches that do not transform it (
had_dim=-1,output=False). Thatpredates this change, is independent of device dispatch, and is left out of
scope; the docs page records it under "Not in scope".
mlx_qqq.py) mirrors the Torch fix but could not beexecuted here (no
mlxruntime on this Linux host); the two Torch oracles intests/test_mlx_qqq_quantization.pywere updated to derivescale_extrafromthe quantized output.
tests/test_qqq_quantizer.py::test_qqq_mse_grid_chunksfails 24 CUDA cases onthis host with ~1e-7 scale differences. It fails identically on a pristine
origin/mainworktree (24 failed), so it is pre-existing and unrelated tothis diff.
during
rotate_model(weights are moved back to CPU per layer). That is aone-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.