Skip to content

feat(macaq): add native MACaQ MXFP4 W4A4 quantization - #4066

Merged
Qubitium merged 15 commits into
ModelCloud:mainfrom
Qubitium:macaq-port
Nov 15, 2026
Merged

Qubitium merged 15 commits into
ModelCloud:mainfrom
Qubitium:macaq-port

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Ports Huawei CSL MACaQ as
METHOD.MACAQ / FORMAT.MXFP4_MACAQ with OCP MXFP4 W4A4 Torch
and 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.

Property GPTQ MACaQ
Weight grid affine INT4 E2M1 + E8M0 per 32
Search inverse-Hessian column updates exponent screen + row flips
Activations W4A16 MXFP4 W4A4
Packed data INT32 words nibbles + E8M0 bytes

FORMAT.MXFP4_MACAQ identifies the native checkpoint schema. Its weight
values use generic OCP MXFP4, while pre_scale, BH, and the saved
activation 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;
Loading
Stage GPTQ flow MACaQ flow
Method GPTQ plan MACaQ plan
Capture grouped subsets combined block subset
Replay GPTQ forward packed W4A4
Runtime GPTQ kernel selector E2M1 W4A4

The MACaQ plan is in quantization_run_plan.py; combined capture
and packed replay are in macaq_processor.py, and runtime is in
qlinear/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.

W4A4 flip mode Full quantization Peak allocated Reserved
Eager 89.10 s 6.06 GiB 7.38 GiB
Compiled, including first use 45.47 s 4.89 GiB 5.53 GiB

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_sweep now serializes
compiler calls. Unit tests compare packed codes exactly, including
concurrent first use.

The same full workflow was measured on an R9700 (gfx1201) with
Python 3.14.10t, PYTHON_GIL=0, Torch 2.16.0.dev+rocm10.1, and the
native 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-flip
selected the eager control.

R9700 flip mode Full quantization Peak allocated Reserved
Eager 121.18 s 5.97 GiB 9.04 GiB
Compiled, including first use 81.56 s 4.99 GiB 7.62 GiB

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:

Reference run Total Capture Quantize Replay
Compiled flips 29.9 s 1.3 s 25.4 s 2.2 s
Eager flips 66.6 s 1.2 s 62.8 s 1.3 s

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:

M x N x K Earlier Tuned Speedup
1 x 2048 x 2048 41.20 us 18.40 us 2.24x
1 x 8192 x 2048 42.47 us 18.99 us 2.24x
16 x 2048 x 2048 40.71 us 19.66 us 2.07x
64 x 8192 x 2048 45.69 us 41.17 us 1.11x
128 x 2048 x 2048 42.96 us 39.01 us 1.10x
256 x 8192 x 2048 116.60 us 105.57 us 1.10x

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 and
R9700 tiles ran the same kernel code on the same GPU.

M x N x K Earlier tiles R9700 tiles Speedup
1 x 2048 x 2048 46.12 us 17.39 us 2.65x
1 x 8192 x 2048 77.88 us 32.15 us 2.42x
16 x 2048 x 2048 46.80 us 17.86 us 2.62x
64 x 8192 x 2048 104.39 us 83.93 us 1.24x
128 x 2048 x 2048 86.08 us 56.57 us 1.52x
256 x 8192 x 2048 344.40 us 306.47 us 1.12x

These are per-Linear calls. Other ROCm architectures use Torch
until their numerical behavior and tile plan are validated.

python scripts/benchmark_macaq_quantization.py \
  --model /monster/data/model/Llama-3.2-1B-Instruct \
  --calibration /monster/data/model/dataset/nm-calibration/llm.parquet \
  --rows 64 --order macaq --rounds 1 --compile-flip

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.

Runtime Perplexity
BF16 20.50
MACaQ W4A16, same packed weights 21.81
MACaQ W4A4 Triton 24.34

Tests and review fixes

Check Result
CUDA MACaQ units plus Llama model test 45 + 1 passed
R9700 MACaQ units plus Llama model test 44 + 1 passed; 1 skipped
ROCm device-family contract suite 429 passed
Fast ARC, 2 of 16 layers 0.328125 accuracy; 0.296875 normalized
R9700 fast ARC, 2 runs 0.3438-0.3516 acc; 0.3281 norm
FP16/BF16 activation bytes exact E2M1 pack test passed
Post-reload ARC inference W4A4 pack + GEMM ran; no Torch fallback
Compiled/eager flips exact codes; concurrent first use
R9700 64-sweep parity 0 code mismatches at 128x512, 256x2048
W4A4 tiles and epilogue FP16/BF16/FP32, M=32/64/65, K-tail
R9700 Torch oracle, M7 N64 K128 0 max error in 6 x 448 outputs
R9700 packed weight, N64 K128 4096 + 256 bytes; 0 dense cache
Repeated Triton forwards only packed weights and scales retained
R9700 GIL=0 inference 3 processes, 8 threads x 4 calls, passed
R9700 GIL=0 compiled flips 3 processes, 8 threads x 4 calls, passed
Full checkpoint 112 packed modules, zero temporary replay keys
Ruff and git diff --check passed

Unit 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. The
two-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.

@Qubitium
Qubitium force-pushed the macaq-port branch 4 times, most recently from 6918bf0 to 098d62c Compare November 15, 2026 01:14
@Qubitium
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.
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.

1 participant