Skip to content

[BUG] MACaQ (#4066): int32 row-offset overflow (garbage rows / HIP crash), HF loads as random weights, Triton ignores device ordinal, sm_120 BLOCK_K=32 compile fail, MoE fallback ignored #4090

Closed

Description

@Qubitium

Audit of the new MACaQ MXFP4 W4A4 feature (#4066) on main @ a15e6bf, tested on CUDA (RTX 5090 sm_120, RTX 4090 sm_89) and ROCm (R9700 gfx1201). The core math is sound; see the clean list at the end. The defects are in kernel launch and edge handling, MoE, config handling and HF interop.

1. Int32 row offsets in the Triton activation and dequant kernels overflow once rows*K >= 2^31: garbage rows on CUDA, illegal-address crash on ROCm (high)

utils/macaq_triton.py:

  • _quant_mxfp4_kernel (:125-152), _rot_scale_quant_kernel (:160-189) and _dequant_w4_to_bf16_kernel (:240-258) all use row = tl.program_id(0) (i32).
  • They compute row * stride_xr / row * stride_pr in i32.
  • The dense GEMM already widens offs_m to int64 (:200).

Scenario: one large prefill or eval batch through a wide down_proj. The limit is 2^31 / in_features tokens:

down_proj K Tokens at overflow
Llama-3.2-1B 8192 ~262k
Qwen2.5-7B 18944 ~113k
Llama-3.1-8B 14336 ~150k
70B 28672 ~75k
CUDA (5090), MacaqTritonLinear K=18944, M=113423 vs Torch path:
  rows 0-8 / 113351-113359: rel err 2.6e-3     rows 113359-113367: 9.93e-1     last 8 rows: 1.09
  triton disabled: False  (no warning)
ROCm (R9700), MacaqTritonLinear in=8192 out=2048:
  262000 tokens -> OK, tail maxdiff 0.0
  262400 tokens -> hipErrorIllegalAddress; the forward's except-fallback sets _triton_disabled but the HIP context is already dead
kernel level K=14336: 149790 rows OK, 149860 rows -> illegal memory access

Fix: use row = tl.program_id(0).to(tl.int64) in all three kernels, or pass int64 strides. Add a test with rows*K just over 2^31, or a mocked large stride.

2. MACaQ checkpoints load in HF transformers as random dense weights, silently (medium)

config.json stores quant_method: "macaq". The #4085 fix registers a refusing HF quantizer only for gptqmodel_gguf (gptqmodel/__init__.py:131-156). For macaq, transformers 5.22 only warns Unknown quantization type, got macaq ... we will skip the quantization. It marks every packed weight MISSING (randomly initialized) and returns a plain model:

AutoModelForCausalLM.from_pretrained(qwen2.5-0.5b-macaq) -> Counter({'Linear': 169})
generate: 'The capital of France is\n   \n度过kovitimate blackColor.blitptronStringEncoding...'
HF vs GPTQModel logits: max diff 22.5, argmax agreement 0.0   (GPTQModel.load PPL 22.67)

Fix: register a refusing quantizer (or real support) for macaq, and add a guard test like the GGUF one.

Related, not verified (no local checkpoint): #4081 says ParoQuant HF load "now fails cleanly with an unknown quantization type". In transformers 5.22 an unknown type is only a warning, so it may now produce random weights the same way.

3. The Triton launches ignore the tensor's GPU: modules on a non-current GPU permanently fall back to Torch, 8.5x slower decode (medium)

The launches in mxfp4_w4a4_linear, rot_scale_quantize_mxfp4, quantize_mxfp4 and dequant_w4_to_bf16 (utils/macaq_triton.py:385-426) aren't wrapped in torch.cuda.device(x.device). With tensors on cuda:1 while cuda:0 is current, Triton raises ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?). The catch-all in MacaqLinear.forward (qlinear/macaq.py:279-287) then sets _triton_disabled=True permanently.

Qwen2.5-0.5B MACaQ, CUDA_VISIBLE_DEVICES=0,2:
  GPTQModel.load(..., device="cuda:0") -> 61.5 tok/s, 0 modules disabled
  GPTQModel.load(..., device="cuda:1") ->  7.2 tok/s, 164/164 modules on Torch

This affects every multi-GPU device_map and every device="cuda:N" with N != 0. GGUF Triton and the W4A _launch_device helper already guard their launches. Fix: guard every MACaQ launch the same way. Also consider not disabling Triton permanently on any exception (e.g. a transient OOM).

4. sm_120 (Blackwell): the W4A4 GEMM fails to compile when in_features % 64 == 32, and the module silently stays on Torch (medium)

_pick_tiles (utils/macaq_triton.py:349-365) falls back to block_k=32 when no larger candidate divides K. On sm_120, tl.dot_scaled lowers to native mma.sync...kind::mxf4nvf4.block_scale, which needs K-tile >= 64, so Triton fails with RuntimeError: PassManager::run failed. The catch-all then disables Triton for that module. sm_89 (emulated) and gfx1201 compile BLOCK_K=32 fine.

5090: (M=1,K=32) (1,96) (64,96), and block_k=32 at K=64/128/256 -> PassManager::run failed   | 4090: all OK
tinyllama-15M (hidden 288): 36/42 modules on Torch on 5090 (0 on 4090); calibration 40.8 s vs 21.3 s
BLOCK_K=64 + existing kb_mask/ks_mask tails on K=96/288/160 (sm_120) -> rel 0.0 vs fp64 reference

Fix: use BLOCK_K >= 64 and rely on the existing K-tail masks instead of requiring BLOCK_K | K. test_triton_dense_kernel_masks_k_tail only uses K values that are multiples of 64.

5. MoE: an expert with no calibration tokens crashes quantization; the configured fallback is never read (medium)

looper/macaq_processor.py:114 sets task.fallback, but nothing in the MACaQ path reads it. quantization/macaq.py:706-710 raises instead:

tiny OLMoE (16 experts, top-2), sparse calibration:
  MACaQ -> ValueError: MACaQ: Hessian for mlp.experts.2.gate_proj has no usable calibration signal; increase calibration data or enable fallback.
  GPTQ  -> "Using rtn fallback quantization (observed 0 samples...)" -> completes

The fallback (RTN, 0.5%) is already enabled by default, so the error's advice doesn't help. Real 64-128 expert MoEs routinely leave experts unrouted.

Fix: honor task.fallback with an MXFP4 RTN at or below the threshold (identity H, no D1), or exclude the expert.

6. A single non-zero exp_offsets entry is silently ignored (low)

quantization/macaq.py:533: the condition len(exp_offsets) > 1 sends a one-element tuple to mxfp4_rtn_signed_index(...) with offset 0. The validator accepts exp_offsets=(-1,) or (2,), but the result is identical to (0,) (scales bit-identical).

Fix: pass exp_offsets[0] to the RTN path. test_single_offset_screen_matches_plain_rtn only uses (0,).

7. dynamic={pattern: False}, as documented, crashes MacaqConfig (low)

docs/macaq.md:319 says dynamic may exclude modules with False, and MacaqConfig.__post_init__ (config.py:6243) accepts it. The shared normalization (_normalize_dynamic_layer_config, config.py:4571/4719) then calls .items() on it:

MacaqConfig(dynamic={'.*down_proj': False}) -> AttributeError: 'bool' object has no attribute 'items'
MacaqConfig(dynamic={'-:.*down_proj': {}})   -> OK

Fix: translate False to a -: exclusion before base normalization, or fix the docs.

Checked, no defect found

  • E2M1/E8M0 encoding: grid, sign and ±0, saturation at 6, floor(log2 amax)-2, clamping to [0,254], all-zero blocks. On HIP, log2/exp2 are exact at powers of two over 2^-40..2^120.
  • Transforms: D1 and the block-Hadamard rotation invert exactly between weights and activations, and the Hessian is rotated as BᵀHB.
  • Flip refinement: monotone on its objective; fast == dense and compiled == eager, bitwise.
  • Kernels vs an fp64 emulated oracle: W4A4 and W4A16 GEMMs, fused/non-fused rotate+quantize, and Torch MacaqLinear match. Covered: M 1–5000, odd N, K tails, 3-D and non-contiguous inputs, bias, fp16/bf16/fp32, on sm_89, sm_120 and gfx1201 (wave32 included).
  • End to end (quantize → save → reload, wikitext-2 80×512):
    • Qwen2.5-0.5B W4A4: 22.71 on CUDA, 22.67 on ROCm. W4A16: 19.94–20.06. fp16 baseline 18.55.
    • Llama-3.2-1B W4A4: 22.45 on CUDA, 22.35 on ROCm. Baseline 18.97.
    • In-memory and reloaded logits are identical.
    • Dynamic -: and per-module overrides round-trip correctly, as do offload_to_disk, tied embeddings and CPU load.
  • ROCm: AUTO selects MACAQ_TRITON on gfx1201, and tl.dot_scaled compiles there, including BLOCK_K=32. 117 tests (MACaQ/GGUF/bnb/HIP staging) pass.

Plausible, not verified

  • On pre-Ampere NVIDIA (no bf16 mma), AUTO probably still selects Triton and permanently falls back, as in item 4.
  • With an inf activation, Triton produces finite 6·2^127 while Torch zeroes or keeps inf. The amax clamps also differ (1e-20 vs 1e-12).
  • _compiled_flip_sweep holds its RLock for every call, not just the first compile, which serializes quantization workers (performance only).

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions