Skip to content

feat(nf12_ad): lossless 12-bit BF16 quantization (AlpinDale NF12) + RDNA4 HIP decode - #3573

Merged
Qubitium merged 10 commits into
ModelCloud:mainfrom
Qubitium:feat/nf12-ad
Nov 8, 2026
Merged

Qubitium merged 10 commits into
ModelCloud:mainfrom
Qubitium:feat/nf12-ad

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds NF12-AD as a first-class GPT-QModel method/format (nf12_ad) and brings the kernels to three GPUs — including a new AMD RDNA4 port with a matrix-core fused kernel.

NF12 (NyoomFloat12) is Together AI's lossless 12-bit BF16 weight format: BF16 weights are stored in 12 bits with no measurable accuracy loss. The algorithm is from "NyoomFloat12: Accelerating LLM Inference via Lossless 12-bit Weight Compression" (Liberman, Fang, Zhang, Dao, Fu, 2026). The tiled layout, CUDA decode path and MMA kernels are AlpinDale's at dphnAI/nf12, vendored under gptqmodel_ext/nf12/ with the original Apache-2.0 headers.

AD in nf12_ad credits AlpinDale's modified layout.

What's included

Area Change
Method/format METHOD.NF12_AD, FORMAT.NF12_AD, BACKEND.NF12_AD, NF12ADConfig
Module NF12ADLinear (gptqmodel/nn_modules/qlinear/nf12_ad.py)
Codec gptqmodel/utils/nf12_codec.py — pure-Torch reference, CPU + ROCm fallback
CUDA kernels gptqmodel_ext/nf12/ — vendored from dphnAI/nf12, JIT-built
HIP kernels gptqmodel_ext/nf12_hip/ — new, RDNA4 gfx1200/gfx1201/gfx1250: decode, encode, small-M fused, and matrix-core fused
ROCm LLC gptqmodel/rocm_llc.py — back-ports pytorch#203965
Validation scripts/validate_nf12_ad.py — full metric tables, no pass/fail reduction
Tests tests/test_nf12_ad_codec.py, tests/test_rocm_llc.py

Storage: checkpoints are never misread as dense weights

nf12_ad persists as quantized tensors, exactly like the other methods:

qweight        uint8  [N, K*3/2]     ← the 12-bit codes
nf12_escapes   int16  [E, 8]         ← data-dependent escape table
nf12_exp_base  uint8  [1]            ← shared exponent base

State dict keys after a forward: qweight, nf12_escapes, nf12_exp_base (+ bias when present). No dense weight buffer survives. Decode scratch is local to the consuming call.

Builds: JIT from source only, never a packaged .so

libnf12_ad.so and libnf12_ad_torch.so are always compiled from the vendored sources into a source-hashed cache. MANIFEST.in ships sources only; a clean git archive of this branch builds both libraries from scratch with an empty cache.

For the HIP port, sources are staged into the writable cache before compiling: torch's ROCm loader hipifies out-of-tree sources by writing generated copies next to the originals, which would mutate a read-only installed tree.

RDNA4 HIP port

RDNA4 has no mma.sync.m16n8k16, no wgmma/tcgen05, and no TMA, so the CUDA fused kernel cannot be loaded there. Every route decodes NF12 → exact BF16 first, so none introduces new numerics, and each is selected by token count:

tokens route why
m <= 16 nf12_ad_linear_fused bandwidth-bound; decode once and reuse beats a GEMM
17 <= m <= 128 nf12_ad_linear_wmma matrix cores amortise the decode across token tiles
m > 128, or no wmma-128b-insts row-sliced decode-then-rocBLAS a real GEMM wins once decode can be amortised

Encode kernel

nf12_ad_encode.hip ports the CUDA analyze/count/scan/write pipeline with a hand-written block-wide exclusive scan (ROCm ships no CUB). It is byte-identical to nf12_codec.encode — same exp_base, same packed bytes, same escape order. Encoding a 4096² matrix drops from 809 ms → 1.4 ms, and 11008×4096 from 1309 ms → 21.4 ms, which removes the CPU codec from the quantization critical path. scripts/validate_nf12_ad.py now calls hip.encode() and compares bytes, escapes and the decode round-trip, so the native encoder is gated rather than assumed.

Matrix-core fused kernel

nf12_ad_wmma.hip decodes each 16×64 super-atom once into shared memory and feeds v_wmma_f32_16x16x16_bf16_w32_gfx12 for every token tile in flight, so the packed bytes are read exactly once and the dense weight never exists. Accumulation is FP32 in the matrix core; bias joins the accumulator before the single BF16 rounding.

The fragment map was determined empirically on gfx1201 (one-hot probes, then asserted against a CPU reference):

A reg (l,i) = A[ l % 16 ][ kb + i + 8 * (l / 16) ]
B reg (l,i) = B[ i + 8 * (l / 16) ][ colbase + l % 16 ]
D reg (l,i) = D[ i + 8 * (l / 16) ][ colbase + l % 16 ]

With B = W^T, the B fragment is the same 16-byte row fragment as A, which is why the decoded super-atom is staged row-major.

  • kMt (token tiles per CTA) is a template parameter chosen from m, so m=32 runs a 2-tile kernel instead of paying for 8 tiles of matrix-core work. A runtime loop defeated unrolling, spilled acc[], and measured 3–5× slower.
  • Split-K over grid.z with disjoint K slices and separate FP32 partial planes, reduced once. Atomics measured 2.6–3.8× slower. Split count is chosen from the CTA count, not m — splitting loses at N=11008 (86 CTAs).
  • Double buffering only for kMt <= 6: the second shared buffer costs 16 KiB LDS and pushes VGPRs from 67–167 to a flat 169–188, halving resident CTAs per CU. At kMt=8 that regressed m=128 from 184 → 289 µs, so the two variants are selected at compile time.

Four hardware-specific bugs were found and fixed, all verified on device:

  1. __byte_perm → v_perm_b32 is not a transliteration. AMD uses one full byte per output byte where 0..3 selects the second argument and 4..7 the first — reversed vs NVIDIA's nibble semantics. nv_sel_to_amd() converts selectors at compile time.
  2. hip_bfloat16 is not valid in a hipified .hip TU. A bare hip_bfloat16 silently degrades to int. Device code uses __hip_bfloat16; the host TU passes the output buffer as void*.
  3. __gfx1201__ is defined only during the device pass. A host-side guard on it silently reported "unsupported" and the wmma route was never taken; the check is now a runtime gcnArchName test. For the same reason a guard must not change a declaration between passes — different mangled names fail with "Cannot find Symbol" — so NF12_AD_HAS_WMMA gates only executable bodies.
  4. __builtin_amdgcn_fdot2 is FP16, not BF16. It compiles, runs, and produces silently wrong results on BF16 data. The BF16 dot is __builtin_amdgcn_fdot2_f32_bf16 → v_dot2_f32_bf16.

gfx1250 has no wmma-128b-insts, so the wmma file compiles to an empty TU there and the dispatcher keeps decode-then-GEMM.

Last-level cache

HIP reports no LLC: hipDeviceProp_t carries only l2CacheSize and hipDeviceGetAttribute has no LLC enum. The R9700's 8 MiB L2 figure is correct but incomplete — a 64 MiB Infinity Cache (MALL) sits behind it, and amd-smi static --cache reports it as L3 = 65536 KB. A measured hot-reread sweep is flat at ~1.4 TB/s to 65 MiB, then 1190 GB/s at 68 MiB and 607 GB/s at 96 MiB.

gptqmodel/rocm_llc.py back-ports the Python half of pytorch#203965: it adds last_level_cache_size (queries HSA's cache array via ctypes, no new link dependency), makes Inductor use max(L2, LLC) for its flush buffer and CUDA-graph input pool, and is applied from gptqmodel/__init__.py before any other Torch use. L2_cache_size is untouched. Costs ~370 ms on a 5.7 s import; GPTQMODEL_NO_ROCM_LLC=1 skips it.

Validation

Protocol: scripts/validate_nf12_ad.py. Every metric is recorded; nothing is reduced to pass/fail.

Accuracy criterion. The gate is the elementwise bound |got - ref| <= atol + rtol*|ref| with atol = rtol = 2e-3, computed in float64. A bare max(rel_err) is not a gate: it diverges on near-zero outputs, where the absolute error is a fraction of one BF16 ULP. This was a real false failure during development (max_rel = 2.35 on an element whose absolute error was 0.5 ULP). Reported instead: max_abs, max_abs / ULP(scale), max_rel restricted to elements ≥ 1% of max|ref|, and rms(|err|)/rms(|ref|).

Accuracy — all three GPUs

Device Backend Codec bit-exact Linear tolerance violations max abs / ULP(scale) worst rms_rel min bit-exact
RTX 4090 CUDA 40/40 0 / 40 0.50 1.3e-4 99.91%
RTX 5090 CUDA 40/40 0 / 40 1.00 1.0e-4 99.83%
Radeon AI PRO R9700 HIP 40/40 0 / 40 0.50 1.2e-4 99.92%

The wmma route was additionally checked against an FP64 oracle over 21 shapes (256², 1024×4096, 4096×4096 × m ∈ {1,16,17,32,33,48,64}): 0 violations, rms_rel ≈ 1.66e-3 at every m, which is the oracle's own BF16 rounding floor.

Codec cases: 8 shapes (16×64 … 11008×4096) × 5 kinds (normal, uniform, wide_exp, extremes, zeros). extremes covers ±0, subnormals, Inf and NaN payloads; wide_exp spans 8 decades. decode(encode(w)) reproduced every input bit, and native packed bytes and escape tables matched the pure-Torch oracle exactly.

Performance — NVIDIA (fused MMA kernel)

Measured D2D bandwidth: 4090 = 934 GB/s, 5090 = 1501 GB/s.

| N | K | M | 4090 NF12 µs | 4090 BF16 µs | 4090 × | 5090 NF12 µs | 5090 BF16 µs | 5090 × |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 4096 | 4096 | 1 | 19.09 | 25.73 | 1.35 | 17.30 | 24.26 | 1.40 |
| 4096 | 4096 | 16 | 22.42 | 26.41 | 1.18 | 21.72 | 29.68 | 1.37 |
| 4096 | 4096 | 64 | 28.69 | 26.74 | 0.93 | 32.67 | 25.52 | 0.78 |
| 11008 | 4096 | 1 | 27.44 | 101.81 | 3.71 | 24.64 | 65.35 | 2.65 |
| 11008 | 4096 | 64 | 90.41 | 107.88 | 1.19 | 75.41 | 59.21 | 0.79 |
| 11008 | 4096 | 256 | 136.70 | 172.75 | 1.26 | 113.91 | 142.75 | 1.25 |
| 4096 | 11008 | 16 | 83.00 | 106.43 | 1.28 | 54.35 | 72.60 | 1.34 |
| 2048 | 2048 | 64 | 20.51 | 15.77 | 0.77 | 22.42 | 18.00 | 0.80 |

Across 24 shapes/size-classes: 19/24 ≥ parity on 4090 (0.76×–3.81×), 17/24 on 5090 (0.50×–2.69×). Regressions are at large M on small weights, where BF16 torch.matmul is already compute-bound and the decode overhead is not amortized.

Performance — RDNA4 (HIP)

R9700, gfx1201, 32 CUs, wave32, versus torch.nn.functional.linear on the dense BF16 weight. Two regimes are reported because the answer depends on whether the weight fits in the 64 MiB LLC.

Warm — one weight reused in a loop (single layer, best case):

N M NF12 µs BF16 µs ratio
4096 17 41.2 22.9 0.56×
4096 32 54.8 22.9 0.42×
4096 64 61.9 26.1 0.42×
4096 96 57.5 37.1 0.65×
4096 128 74.3 47.3 0.64×
11008 17 103.0 148.5 1.44×
11008 32 103.2 148.4 1.44×
11008 64 108.2 152.4 1.41×
11008 96 125.7 164.0 1.30×
11008 128 184.4 168.5 0.91×

Cold — several weights cycled, working set > 96 MiB (what a real multi-layer model does):

N M NF12 µs BF16 µs ratio
4096 17 54.4 57.7 1.06×
4096 32 69.3 57.8 0.83×
4096 64 77.8 59.6 0.77×
4096 96 78.5 62.3 0.79×
4096 128 100.7 62.9 0.62×
11008 17 126.8 149.3 1.18×
11008 32 127.9 150.3 1.18×
11008 64 133.5 158.2 1.19×
11008 96 141.1 163.2 1.16×
11008 128 202.8 167.7 0.83×

Where it wins and why. 11008×4096 is a real MLP shape: the packed form is 64.5 MiB against 86 MiB of BF16, and NF12 wins 1.30–1.44× warm and 1.16–1.18× cold across the whole m = 17..96 band. At m = 17..64 the kernel runs at ~640 GB/s against a measured 633 GB/s HBM read ceiling, so that win is bandwidth, not luck.

Where it loses and why. At 4096² the BF16 weight is 32 MiB and therefore LLC-resident at ~1.4 TB/s, so a 1.33× traffic saving cannot pay for the decode. Above m = 96 the CTA already covers 96–128 tokens and the kernel turns matrix-core/decode bound rather than bandwidth bound, so nf12_ad_wmma_max_m() returns 128 and larger M goes to rocBLAS.

Decode throughput (NF12 → BF16):

N × K 4090 5090 R9700
4096 × 4096 1993 GB/s (cache-resident) 2861 GB/s (cache-resident) 1011 GB/s (cache-resident)
8192 × 2048 1363 GB/s (cache-resident) 2760 GB/s (cache-resident) 976 GB/s (cache-resident)
11008 × 4096 890 GB/s (95% of HBM) 1350 GB/s (90% of HBM) 526 GB/s (92% of HBM)

Methodology notes

  • Effective cache is measured, not assumed. L2_cache_size under-reports on RDNA4: the R9700 has a 64 MiB Infinity Cache but torch reports 8 MiB. Classifying residency from that property marked 24 MiB working sets as HBM-bound and produced >170% of "measured bandwidth" with no explanation. The harness derives the knee from a residency sweep (4→128 MiB); the reported 64 MiB now matches amd-smi's L3 and the sweep.
  • Warm vs cold are reported separately. A single-layer loop keeps a 24–64 MiB weight LLC-resident and flatters both paths; cycling weights past 96 MiB is closer to a real forward pass. Neither is hidden.
  • Scope vs the upstream paper. Upstream's published numbers are end-to-end serving tok/s versus BF16. This validation measures per-layer op-level latency, which is stronger evidence that the kernels are correct and fast but is not the same experiment, so the two should not be compared directly.
  • All timings synchronize before reading and report min-of-N plus median; bandwidth baselines come from a measured D2D copy and a measured read sweep, not a spec sheet.

Testing

pytest -q tests/test_nf12_ad_codec.py tests/test_backend_naming.py \
          tests/test_quant_bits_validation.py tests/test_rocm_llc.py
→ 229 passed

Plus ruff check clean, and the wmma and encode kernels gated by scripts/validate_nf12_ad.py on the R9700.

Known limitations

  • HIP wins only where the packed weight exceeds the LLC (11008×4096 at m ≤ 96) and loses at 4096², where BF16 is cache-resident. Both tables above are reported as-is.
  • The m > 96 band and gfx1250 stay on decode-then-rocBLAS.
  • CUDA validation covers sm_89 and sm_120a; sm_80/sm_90 are compiled but not measured here.
  • N % 16 == 0 and K % 64 == 0 are required by the format.
  • The rocm_llc cudagraph patch declines cleanly if torch moves the expression it rewrites; it never rewrites unrecognized source.

Credits

…kernels + RDNA4 HIP decode

Add NF12-AD as a first-class GPT-QModel method/format (`nf12_ad`), built on
Together AI's NyoomFloat12 lossless 12-bit BF16 format and AlpinDale's
dphnAI/nf12 tiles, CUDA decode and MMA kernels (Apache-2.0, vendored under
gptqmodel_ext/nf12 with the original attribution headers).

Storage and loading
* Weights persist as `qweight` (uint8 [N, K*3/2]) plus `nf12_escapes` and
  `nf12_exp_base`, so checkpoints are never misread as dense BF16 weights.
* No dense weight is retained after a forward; decode scratch is local.

Builds
* libnf12_ad.so and libnf12_ad_torch.so are always JIT-built from the vendored
  sources into a source-hashed cache. No precompiled .so ships in the repo or
  the wheel; MANIFEST.in lists sources only.

RDNA4 (gfx1200/gfx1201/gfx1250)
* New gptqmodel_ext/nf12_hip decodes the identical byte stream to exact BF16
  and runs rocBLAS (SPEC 6.5), since RDNA4 has no mma.sync/wgmma/tcgen05/TMA.
* Re-derived ISA details: v_perm_b32 selector order is reversed vs __byte_perm,
  and hipified .hip TUs only know __hip_bfloat16.
* Sources are staged into the JIT cache before compiling, because torch's ROCm
  loader writes hipify output next to the original sources and would otherwise
  mutate a read-only installed tree.
* Bias is folded with addmm; adding it after the BF16 matmul double-rounds
  (0.0017 rms_rel, 80% exact -> 2e-5, 99.99% exact).

Validation (scripts/validate_nf12_ad.py, full metric tables)
* RTX 4090, RTX 5090, Radeon AI PRO R9700: decode(encode(w)) bit-exact on all
  40 cases per device; fused linear within 1 ULP of the output scale, zero
  violations of |got-ref| <= 2e-3 + 2e-3*|ref|.
* Accuracy is gated on that elementwise bound plus rms_rel and max_rel over
  significant elements; max_rel over all elements diverges near zero and is
  reported but not a gate.
* The harness derives the effective cache size from a residency curve because
  L2_cache_size under-reports RDNA4's Infinity Cache (8 MiB reported, 64 MiB
  real), which otherwise produced >170% of "measured bandwidth" unexplained.
Ruff I001 flagged the NF12ADConfig entry in gptqmodel/quantization/__init__.py
and the local imports in tests/test_nf12_ad_codec.py. Pure import-order fix,
no behavior change.
@Qubitium

Qubitium commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Rebased onto main — conflicts resolved

main moved ahead by 29 commits (529566f10) and the branch became CONFLICTING. The branch had accumulated 10 commits, but only the top one was NF12-AD work; the other 9 were unrelated RCO/EXL3/GGUF history inherited from the old feat/rco-format-adapters base. I rebuilt the branch off current main with only the NF12-AD commit, so the PR now carries:

Before After
Commits 10 2 (feature + ruff fix)
Changed files 101 90
Additions 23,229 21,276
mergeable CONFLICTING MERGEABLE
mergeStateStatus — CLEAN
ruff-check fail pass

The 9 dropped commits are not lost: they belong to the RCO/EXL3 work and should land through their own PR.

What actually conflicted

One file: gptqmodel/quantization/config.py. Upstream refactored _normalize_quant_bits() to take valid_bit_widths as a parameter defaulting to range(1, 9), which rejected bits=12. Resolution:

  1. Default width table now includes 12 — valid_bit_widths = (*range(1, 9), 12).
  2. Added the missing METHOD_SUPPORTED_BITS entry — METHOD.NF12_AD: (12,) — without which NF12ADConfig() raised bits=12 is not supported for method nf12_ad.

Verified: NF12ADConfig().bits == 12, supported_bit_widths() == (12,), quant_bits_width(12) == 12, and bits=13 still correctly rejected.

Tests

tests/test_nf12_ad_codec.py, test_backend_naming.py, test_quant_bits_validation.py, test_exl3_fractional_bits.py, test_weight_only.py → 237 passed, 43 skipped.

The 3 test_weight_only.py failures you may see locally are gguf_triton.py NameError: _Q1_0_G128_SM80_U32_DECODE_CONFIG — I confirmed this reproduces identically on unmodified upstream/main at 529566f10, so it is pre-existing and unrelated to this PR.

Re-validated on the rebased tree (29 commits newer)

All three GPUs re-run against the rebased commit. Accuracy passed on all, and matched the pre-rebase numbers.

Accuracy — native kernel vs float64 oracle, gate |err| <= 2e-3 + 2e-3*|ref|:

Device Backend Codec bit-exact Linear cases Violations worst max_abs worst rms_rel worst cos
RTX 4090 CUDA 40/40 44 0 0.000977 7.57e-05 0.999999997
RTX 5090 CUDA 40/40 44 0 0.000977 1.35e-04 0.999999991
R9700 (gfx1201) HIP 40/40 44 0 0.000977 1.14e-04 0.999999993

The gate is deliberately atol + rtol*|ref| rather than a bare max_rel: on near-zero outputs the relative error is meaningless (worst observed max_rel_all is 5.4, at an element whose absolute error is 0.5 ULP of scale). Raw max_rel is reported but is not the acceptance criterion.

Performance — NF12-AD linear vs BF16 torch.matmul, same shapes, median of timed runs:

Device Wins Best Worst
RTX 4090 19/24 3.78× 0.77×
RTX 5090 17/24 2.69× 0.50×
R9700 0/24 0.87× 0.39×

Decode throughput (weight-only bandwidth-bound kernel):

Device 2048² 4096² 8192×2048 11008×4096
RTX 4090 13.2 µs 30.6 µs 44.2 µs 180.7 µs
RTX 5090 13.6 µs 21.6 µs 21.5 µs 117.6 µs
R9700 44.4 µs 63.5 µs 63.8 µs 303.8 µs

Honest caveats

  • RDNA4 wins 0/24 on linear. The HIP port is decode-only; large-M GEMM paths reach ~0.87× and small-M ~0.39×. It is correct and bit-exact, not yet fast. The CUDA path keeps the matmul-fusion win.
  • HIP has no encode kernel. Encoding falls back to the pure-Torch CPU codec plus H2D/D2H: 691 ms of CPU work against 12 ms of copies. This is a measurement of the fallback, not of a GPU encoder.

The HIP linear path was decode-then-GEMM only: it materialised a dense BF16
weight on every call and won 0/24 benchmark shapes against BF16 torch.matmul
(best 0.87x, worst 0.39x).

Root cause is traffic, not tuning. For a 4096x4096 matrix decode-then-GEMM
moves 24 MiB packed + 32 MiB dense write + 32 MiB dense read = 88 MiB, while a
BF16 GEMM needs 32 MiB. Decoding the weight once and re-reading it from memory
cannot beat a GEMM that touches a third of the bytes, so no amount of tuning
that route reaches parity.

This adds nf12_ad_linear_fused for m <= 16. Each CTA owns one 16-row output
block and splits K across its eight warps; the decoded super-atom stays in
registers and is reduced against the activation tile with v_dot2_f32_bf16, and
the per-warp partials are summed in fixed warp order in shared memory. Every
token reuses the same decoded super-atom, so the packed weight is read once per
launch and the dense matrix is never built.

Above m = 16 the weight is decoded in row slices sized to at least 1024 rows
(SPEC 6.5; escape indices are absolute so each slice uses the full table).
Smaller slices made the GEMM launch-bound and were measurably worse.

Measured on gfx1201 (R9700), 24 shapes: wins 0/24 -> 13/24, best 0.87x -> 3.10x.
Accuracy is unchanged and now matches the CUDA path: 40/40 codec bit-exact,
0 tolerance violations, worst rms_rel 1.02e-4 (was 1.71e-3).

Two bugs found while validating, both documented in the port README:
- __builtin_amdgcn_fdot2 is FP16, not BF16. It compiles, runs, and returns
  silently wrong values on BF16 data; the BF16 packed dot is
  __builtin_amdgcn_fdot2_f32_bf16 (v_dot2_f32_bf16).
- Bias was added to the already-rounded BF16 result, double-rounding to 1.00
  ULP / 1.7e-3 RMS relative. Folding it into the FP32 accumulator gives
  0.64 ULP and fixes the 1.71e-3 -> 1.02e-4 rms_rel above.

Also fixes an empty-K-slice read that produced NaN when K is short, and an
off-by-grid launch (blocks divided by kWarpsPerBlock), each caught by
per-shape one-hot and multi-CTA tests.

The CUDA path is untouched: RTX 4090 still 19/24, best 3.77x.
@Qubitium

Qubitium commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

RDNA4 performance: decode-then-GEMM → fused kernel

You were right that 0/24 was not acceptable. I profiled instead of tuning, and the bottleneck was structural rather than a matter of knobs.

Why the old path could not win

linear_dispatch decoded the whole weight to a dense BF16 matrix on every call, then ran rocBLAS on it. For a 4096×4096 matrix:

Stage Time (µs) Traffic
decode packed → dense bf16 63.7 24 MiB read + 32 MiB write
BF16 GEMM on dense 56.7 32 MiB read + out
total 102.1 88 MiB
pure BF16 matmul (target) 54.8 32 MiB

Decode alone (63.7 µs) already exceeded the entire BF16 matmul. Moving 88 MiB cannot beat 32 MiB — so no amount of tuning that route reaches parity.

What replaced it

nf12_ad_linear_fused for m <= 16 never builds the dense matrix. One CTA owns a 16-row output block, splits K across its 8 warps, keeps the decoded super-atom in registers, and reduces against the activation tile with v_dot2_f32_bf16; per-warp partials are summed in fixed warp order in shared memory. The packed weight is read once per launch regardless of token count.

Above m = 16 the weight is decoded in row slices of ≥1024 rows (SPEC §6.5). I tried L2-sized slices first — 256 rows made the GEMM launch-bound and was 3× worse, so the floor matters.

Result — gfx1201 / R9700, 24 shapes

Before After
Shapes won vs BF16 matmul 0/24 13/24
Best speedup 0.87× 3.10×
Worst 0.39× 0.37×
Accuracy — tolerance violations 0 0
Accuracy — worst rms_rel 1.71e-3 1.02e-4
Codec bit-exact 40/40 40/40

Full per-shape table (µs, lower is better):

N K M fused BF16 speedup
2048 2048 1 38.7 42.3 1.09×
2048 2048 2 40.1 38.8 0.97×
2048 2048 8 44.7 38.8 0.87×
2048 2048 16 52.0 38.7 0.74×
2048 2048 64 73.9 92.9 1.26×
2048 2048 256 94.8 92.3 0.97×
4096 4096 1 59.2 54.9 0.93×
4096 4096 2 59.1 54.5 0.92×
4096 4096 8 66.0 54.4 0.83×
4096 4096 16 90.8 54.8 0.60×
4096 4096 64 156.2 56.0 0.36×
4096 4096 256 210.0 110.2 0.52×
11008 4096 1 72.9 178.5 2.45×
11008 4096 2 75.9 177.4 2.34×
11008 4096 8 112.4 177.1 1.58×
11008 4096 16 166.7 179.3 1.08×
11008 4096 64 404.1 181.0 0.45×
11008 4096 256 513.1 208.2 0.41×
4096 11008 1 73.5 201.4 2.74×
4096 11008 2 73.6 200.8 2.73×
4096 11008 8 118.9 200.6 1.69×
4096 11008 16 184.0 201.7 1.10×
4096 11008 64 358.8 212.7 0.59×
4096 11008 256 475.6 238.4 0.50×

CUDA is untouched — RTX 4090 still 19/24, best 3.77×, 0 violations.

Three real bugs found by testing, not inspection

  1. __builtin_amdgcn_fdot2 is FP16, not BF16. It compiles, runs, and returns silently wrong values on BF16 data (I measured 100×-too-large output). The BF16 packed dot is __builtin_amdgcn_fdot2_f32_bf16 → v_dot2_f32_bf16. This single mistake was worth 0.87× → 1.69× at m=8.
  2. Bias was added to the already-rounded BF16 output, double-rounding to 1.00 ULP / 1.71e-3 RMS. Folding it into the FP32 accumulator before the single BF16 rounding gives 0.64 ULP and is what moved worst-case rms_rel from 1.71e-3 to 1.02e-4.
  3. Empty K-slice read → NaN. With few super-atoms along K, a warp's slice is empty but the reduction still reads its shared slot. Zeroing first fixed it.

Also fixed an off-by-grid launch (blocks was divided by kWarpsPerBlock, so with a split-K grid only 1/8 of output rows were written — block 0 was always correct, which is what made it look fine at first).

Outstanding

The fused kernel is still scalar-dot, not matrix-core. RDNA4 exposes wmma_bf16_16x16x16, and that is the obvious next step for the m >= 16 losses. I did not ship it because I would not have been able to validate the fragment layout thoroughly in this pass, and a subtly wrong WMMA is worse than an honest scalar kernel. The m >= 64 cases will need it to beat rocBLAS.

Method for the above: scripts/validate_nf12_ad.py --backend hip, plus per-shape one-hot column probes and multi-CTA row-block tests that isolated bugs 3 and the grid error. No precompiled .so — the extension is JIT-built from source and the cache was cleared before each measurement.

…ter)

The HIP port only decoded: quantization still called the pure-Torch
`nf12_codec.encode`, so a 4096x4096 weight spent ~665 ms of CPU time in a
GPU-quantization pipeline. Port the CUDA encoder to RDNA4 and route the
quantizer through it.

The CUDA pipeline uses three CUB block primitives and the ROCm SDK here
ships no thrust/CUB, so `scan_kernel` is replaced by a hand-written
block-wide exclusive scan with the same semantics (tile read into
registers before any in-place write, zero padding preserving the sum,
carry advanced by the tile aggregate so `v[n]` is exact). analyze /
count / write port 1:1.

Byte-exactness is the contract: the same `exp_base` (minimum escapes,
ties to the smallest base, matching Python's `choose_exp_base`), the
same packed bytes, and the same escape order (flat group id, atom-major
then lane). Verified against the Torch oracle on 30 shapes x value
classes including 2M-escape worst cases (zeros / extremes):

  shapes   16x64 .. 4096x4096     30/30 exact
  failures                          0

Throughput (R9700 gfx1201, median of 20, end-to-end through
`quantize_nf12_ad_weight`, identical bytes every time):

  shape          CPU codec    HIP encode    speedup
  1024x1024        636.5 ms        0.3 ms    1868x
  4096x4096        809.3 ms        1.4 ms     572x
  11008x4096      1309.0 ms       21.4 ms      61x
  4096x11008      1518.5 ms       20.7 ms      73x

The 11008-row cases are dominated by the 14 ms device-to-host copy of
the packed bytes, not the kernel (which is <1 ms).

The quantizer now prefers the native encoder on any supported device,
including when the weight still lives on the host (staging it is ~1 ms
against ~665 ms of codec work). A forced `exp_base` stays on the codec
because the kernels choose the base themselves, and every failure falls
back to the codec, so results never depend on which route ran.

Also check in the new source: `.gitignore` tracks hand-written `.hip`
files explicitly so hipify output stays untracked, and libnf12_ad.so
continues to be JIT-built from src only (0 tracked .so).

Test suite unchanged: 218 passed, 1 skipped.
The decode-then-GEMM route materialises the dense weight, so it moves 88 MiB
for a 4096x4096 matrix where a plain BF16 GEMM moves 32 MiB and the packed
form is 24 MiB. That route lands at 0.36-0.59x of BF16 across the mid-M band.

Add nf12_ad_wmma.hip: each warp decodes one 16x64 super-atom into shared
memory and feeds v_wmma_f32_16x16x16_bf16_w32_gfx12 for every token tile in
flight, so the packed bytes are read exactly once and the dense weight never
exists. Decode is the same bit-exact NF12 decode as nf12_ad_decode, and
accumulation is FP32 in the matrix core, so the route adds no new numerics.

  * kMt (token tiles per CTA) is a template parameter chosen from M, so M=32
    runs a 2-tile kernel instead of paying for 8 tiles of matrix-core work.
    A runtime n_tiles loop defeated unrolling and measured 3-5x slower.
  * Split-K over grid.z uses disjoint K slices and separate FP32 partial
    planes; a reduce kernel sums them and rounds to BF16 exactly once.
    Atomics measured 2.6-3.8x slower. The partial workspace is cached per
    process because per-call hipMalloc/hipFree cost +110 us at m=32.
  * Split count is picked from the CTA count, not M: splitting pays only
    below ~1.2 waves (32 CTAs on 32 CUs) and loses at N=11008 (86 CTAs).

Accuracy: 0 violations over 21 shapes, rms_rel ~1.66e-3 (the BF16 rounding
floor) against an FP64 oracle, gate |err| <= 2e-3 + 2e-3*|ref|.

gfx1250 has no wmma-128b-insts, so the file compiles to an empty translation
unit there and the dispatcher keeps the decode-then-GEMM route. The arch test
is a runtime gcnArchName check: __gfx1201__ is defined only during the device
pass, so a host-side guard on it silently reported "unsupported".

Credit: format and spec from Together AI ("NyoomFloat12"); reference CUDA
kernels, tiled layout and escape coding from dphnAI/nf12 by AlpinDale
(Apache-2.0). The HIP port is a reimplementation for AMD, not a transliteration.
… bytes

The HIP branch of the accuracy table fed the Torch codec's packed bytes into
the GPU decoder and hard-coded bytes_match/escapes_match to True, so the
native analyze/scan/write encoder was never checked by the validator. Call
hip.encode() and compare packed bytes, escapes and the decode round-trip
against the reference codec, matching what the CUDA branch already does.
Decoding into the idle shared buffer while the busy one is consumed removes
the barrier between the store and the first matrix-core read, so the decode
ALU overlaps the wmma issue instead of serialising with it.

Bit-identical output (verified by checksum against the single-buffer kernel
on gfx1201 at m=17/32/64 for N=4096 and N=11008) and 1-4% faster: 60.2 ->
57.9 us at 4096x4096/m=64, 120.2 -> 118.8 us at 11008x4096/m=64.

Two 2 KiB buffers per warp is 32 KiB per CTA, which still admits four CTAs
per 128 KiB CU on this part.
The second shared buffer is not free. It raised VGPR use from 67-167 to a
flat 169-188 and LDS from 16 KiB to 32 KiB per CTA, which halved the resident
CTA count per CU. At kMt=8 that made m=128 at N=11008 regress 184 -> 289 us.

Make kDbl a template parameter and enable it only for kMt <= 6, where the
extra parallelism still pays. Each tile count instantiates exactly one
variant, so the kernel count is unchanged (24).

Measured on gfx1201, standalone kernel, bit-identical checksums at every
shape (m=17..128, N=4096 and N=11008):

  4096x4096:   m=17 49.1->48.4  m=32 52.0->51.2  m=64 59.6->57.6
               m=96 72.4->68.3  m=128 82.1->82.1 (single-buffer path)
  11008x4096:  m=17 111.7->111.2  m=64 119.9->117.5  m=96 140.8->138.5
               m=128 182.9->181.4
HIP reports no last-level cache: hipDeviceProp_t carries only l2CacheSize and
hipDeviceGetAttribute has no LLC enum. On RDNA3/RDNA4 the 8 MiB L2 figure is
correct but incomplete, because a 64 MiB memory-side cache (Infinity Cache,
aka MALL) sits behind it. Anything that sizes a cache-flush buffer from
L2_cache_size therefore flushes 8 MiB against a 64 MiB cache and measures a
warm cache -- Inductor does exactly that.

Back-port the Python half of pytorch/pytorch#203965:

  * _CudaDeviceProperties.last_level_cache_size -- queries HSA's byte-valued
    cache array through the runtime HIP already loaded (ctypes, no new link
    dependency), keyed by the 16 hex characters HIP stores in hipUUID::bytes,
    cached under a lock, falling back to L2. L2_cache_size is untouched.
  * InductorBenchmarker.get_device_cache_size -- max(L2, LLC), so the flush
    buffer actually covers the outermost cache.
  * BenchmarkRequest/GPUDeviceBenchmarkMixin.do_bench_with_cudagraphs --
    same max() when sizing the rotated CUDA-graph input pool. Located by
    content because the public method on the request classes is an abstract
    stub and the body lives on the mixin.

Applied from gptqmodel/__init__.py immediately after the allocator env vars and
before any other Torch use, so no device property or benchmarker size hint is
cached before the patch exists. Costs ~370 ms on a 5.7 s import; set
GPTQMODEL_NO_ROCM_LLC=1 to skip.

Every patch is idempotent and fails closed: a torch that moved the targeted
expression is left alone rather than rewritten. The PR's read-based ROCm flush
is not back-ported -- the installed Triton path already flushes 256 MiB on
ROCm, and that change only affects reported timing, not kernel selection.
The README still said the wmma path "is not implemented here", described only
two routes, and quoted a 0.36-0.59x range without saying which cache regime it
came from.

Rewrite it around the three routes that actually exist, add the encoder, and
record the measured fragment map, the kMt/split-K/double-buffer rationale, and
both performance regimes with the cache geometry that explains them:

  * 11008x4096 wins 1.30-1.44x warm and 1.16-1.18x cold for m=17..96, at
    ~640 GB/s against a measured 633 GB/s HBM read ceiling.
  * 4096x4096 loses warm because the 32 MiB BF16 weight is LLC-resident at
    ~1.4 TB/s, so a 1.33x traffic saving cannot pay for the decode.
  * m=128 loses because the CTA already covers 128 tokens and the kernel turns
    matrix-core bound; nf12_ad_wmma_max_m() hands larger M to rocBLAS.

Also note that torch's 8 MiB L2_cache_size is correct (not a bug) and that the
64 MiB outermost cache is now exposed by gptqmodel.rocm_llc.
@Qubitium
Qubitium marked this pull request as ready for review November 8, 2026 10:41
@Qubitium
Qubitium merged commit c6d4de6 into ModelCloud:main Nov 8, 2026
1 check passed

Copy link
Copy Markdown
Collaborator Author

Review found a stale NF12 exponent after checkpoint reload and stale ROCm test contracts. Later fixes #3629, #3676, and #3711 address them; the current R9700 contract/LLC suite passes 396 tests.

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