Repository navigation
feat(macaq): add native MACaQ MXFP4 W4A4 quantization - #4066
Merged
Merged
Conversation
Qubitium
force-pushed
the
macaq-port
branch
4 times, most recently
from
November 15, 2026 01:14
6918bf0 to
098d62c
Compare
Qubitium
marked this pull request as ready for review
November 15, 2026 03:05
Port Huawei CSL's MACaQ (arXiv:2611.10649, Apache-2.0) as METHOD.MACAQ / FORMAT.MACAQ with the MACAQ_TORCH and MACAQ_TRITON backends. - quantization/macaq.py: D1 balance pre-scale, block-Hadamard rotation, OCP MXFP4 round-to-nearest, Hessian-weighted exponent screen, greedy flip refinement, and the pack/dequant helpers. - utils/macaq_triton.py: activation quantizer, fused rotate+quantize, W4A4 tl.dot_scaled GEMM, and the W4A16 dequant GEMM. - nn_modules/qlinear/macaq.py: MacaqLinear (portable Torch) and MacaqTritonLinear (CUDA). - looper/macaq_processor.py: looper processor and checkpoint capture. - Credits in CREDITS.md and README.md; design notes in docs/macaq.md. The Triton dense kernel carries the upstream K-tail mask fix, and the decoder accepts padded and E8M0-typed scale grids. Covered by tests/test_macaq.py and the Llama-3.2-1B-Instruct end-to-end model test.
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.
Summary
Ports Huawei CSL MACaQ as
METHOD.MACAQ/FORMAT.MXFP4_MACAQwith OCP MXFP4 W4A4 Torchand Triton modules, calibration, safetensors, and Llama 3.2 1B tests.
The port has its own quantizer because its FP4 grid, solve, packed
layout, and activation kernel differ from GPTQ.
Each Linear keeps its own D1 balance and block-Hadamard transform.
The default D1 exponent is
alpha=0.75, matching the reference CLI.The config and both quantizer entry points default to compiled flips
on supported GPUs. The W4A4 kernel uses decode-aware tiles and a
fused bias/output epilogue on NVIDIA CUDA; an R9700-specific tile
plan enables native W4A4 on ROCm
gfx1201.FORMAT.MXFP4_MACAQidentifies the native checkpoint schema. Its weightvalues use generic OCP MXFP4, while
pre_scale,BH, and the savedactivation mode provide the MACaQ transform needed at inference.
Other MXFP4 checkpoint layouts require conversion before loading.
Quantization and replay flow
Each calibration chunk traverses the current block once while hooks
capture all selected projection Hessians. MACaQ quantizes them, then
replays the packed block to supply inputs to the next block. Replay
is required for the reference streaming recipe. Temporary packed
replay modules are removed before final checkpoint modules are made.
flowchart TD A["Config validation"] -->|valid| B["Resolve pack backend"] A -->|invalid config| F1["ValueError"] B -->|NVIDIA CUDA or ROCm gfx1201 with Triton| T["MACAQ_TRITON"] B -->|portable or explicit Torch| P["MACAQ_TORCH"] B -->|unsupported backend| F2["select_quant_linear error"] T --> B1["build_layer_subset_plans<br/>one combined block subset"] P --> B1 B1 --> C["MacaqProcessor.preprocess"] C -->|excluded| S["skip module"] C -->|included| E["Macaq.add_batch<br/>capture Hessian"] E -->|empty or nonfinite| F3["ValueError"] E -->|usable| Q["Macaq.quantize<br/>screen and flip"] Q --> D{"compile_flip on<br/>CUDA+GIL or ROCm gfx1201?"} D -->|yes| K["_compiled_flip_sweep<br/>serialized Inductor"] D -->|no| J["_flip_sweep eager"] K --> R["MacaqProcessor.process<br/>_install_packed_replay"] J --> R R -->|next block input| F["Packed W4A4 block replay"] R -->|last block| X["Remove replay child"] F --> X R -->|duplicate replay child| F4["RuntimeError"] X --> U["submodule_finalize<br/>pack permanent module"] U --> V["BaseQModel.save<br/>safetensors"] V --> L["GPTQModel.load<br/>MacaqLinear.forward"] classDef error fill:#fdd,stroke:#c00,color:#000; class F1,F2,F3,F4 error;The MACaQ plan is in
quantization_run_plan.py; combined captureand packed replay are in
macaq_processor.py, and runtime is inqlinear/macaq.py.The MACaQ guide keeps the full flow and failure paths.
Speed and quality validation
The paper's 11x quantization-time claim is against MR-GPTQ and
DuQuant++ at matched W4A4 quality on Llama-3-8B, not plain GPTQ
W4A16. The compiled path ports upstream's repeated-sweep fusion.
It is the default on NVIDIA CUDA with the GIL and on ROCm
gfx1201,including free-threaded Python. CPU, other ROCm GPUs, and
free-threaded NVIDIA Python use eager sweeps. Inductor calls are
serialized to prevent first-use autotuning races. Shared-input
Hessians are still accumulated per projection in this port.
An A/B on identical port code used Llama-3.2-1B-Instruct, 64
calibration messages (28,672 padded tokens), BF16 weights, eager
attention, 2048-token concat, batch 1, 128 flips, and
alpha=0.75.Both runs used an RTX 4090, Torch 2.15.0+cu132, Triton 3.9.0,
cudaMallocAsync, and the same inference kernel revision.Compilation reduced full quantization time by 1.96x in this single
exploratory A/B. The first unsynchronized attempt hit an Inductor
autotuning race across workers;
_compiled_flip_sweepnow serializescompiler calls. Unit tests compare packed codes exactly, including
concurrent first use.
The same full workflow was measured on an R9700 (
gfx1201) withPython 3.14.10t,
PYTHON_GIL=0, Torch 2.16.0.dev+rocm10.1, and thenative allocator. Both runs used 64 calibration rows, BF16 weights,
eager attention, batch 1, 64 flips, and all 112 projections. The
benchmark script defaults to compiled flips;
--no-compile-flipselected the eager control.
Compilation reduced full quantization time by 1.49x in this
single-run A/B. It includes calibration, block replay, and packing.
Fixed 128x512 and 256x2048 weight/Hessian fixtures with 64 sweeps
had zero code mismatches and identical weighted error between modes.
The unmodified Huawei reference on the same 1B checkpoint and RTX
4090 model, with FP16 weights and 25,532 raw-text tokens, measured:
Compilation improved its total time 2.23x. These reference runs use
different dtype and token formatting from the GPTQModel timing, so
they are indicative rather than a direct A/B comparison.
The W4A4 kernel also ports Huawei's decode-aware tiles and fused
bias/output epilogue. Kernel-call timings include activation packing
and GEMM with resident BF16 inputs and weights on the same RTX 4090.
triton.testing.do_bench_cudagraph(..., rep=250)measured:These are Linear kernel calls, not full-model generation latency.
The M=64 cutoff was tuned to use the larger tiles after a local A/B.
The R9700 (
gfx1201) path was measured on ROCm 10.1 / HIP 7.16,Torch 2.16.0.dev20261025+rocm10.1, and Triton 3.9. Resident BF16
inputs, packed weights, an identity BH, unit pre-scale, and BF16 bias
were timed with
do_bench_cudagraph(..., rep=100). Earlier tiles andR9700 tiles ran the same kernel code on the same GPU.
These are per-Linear calls. Other ROCm architectures use Torch
until their numerical behavior and tile plan are validated.
An earlier full 112-projection quality run used 115,325
WikiText-2 training tokens, 128 flips, and
alpha=0.75.Perplexity was measured on 16 contiguous 512-token test chunks.
Tests and review fixes
git diff --checkUnit coverage includes Torch/Triton numerical parity, K-tail masks,
dynamic config, packed replay, Conv1D layout, and checkpoint restore.
The fast e2e test packs two decoder layers, saves and reloads the
checkpoint, then requires native 4-bit activation packing and W4A4
GEMM during ARC evaluation. All 14 packed projections are used and
none falls back to Torch. The full 112-projection quality run is a
separate validation. Triton was tested on NVIDIA SM89 and R9700
gfx1201; the portable Torch path was unit-tested on CPU. Thetwo-R9700 thread probe serially prewarms JIT and does not qualify
concurrent cold compilation.
Credits and scope
The algorithm, numerical recipe, and kernel structure are from
Huawei CSL MACaQ, Apache-2.0.
The upstream NOTICE
and author attribution are preserved in the ported file headers,
CREDITS.md, the README citation, and
the paper citation.
This PR ports the dense Torch/Triton path and native safetensors.
MoE kernels, GGUF, the vLLM plugin, Diffusers, and TTS remain upstream.
The R9700 compiled sweep passed a two-GPU, free-threaded first-use
probe with exact eager-code parity. Its Inductor calls remain
serialized. Free-threaded NVIDIA compilation remains unqualified.