Repository navigation
feat(nf12_ad): lossless 12-bit BF16 quantization (AlpinDale NF12) + RDNA4 HIP decode - #3573
Conversation
…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.
6fee836 to
332b3ea
Compare
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.
Rebased onto
|
| 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:
- Default width table now includes 12 —
valid_bit_widths = (*range(1, 9), 12). - Added the missing
METHOD_SUPPORTED_BITSentry —METHOD.NF12_AD: (12,)— without whichNF12ADConfig()raisedbits=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.
RDNA4 performance: decode-then-GEMM → fused kernelYou 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
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
Above Result — gfx1201 / R9700, 24 shapes
Full per-shape table (µs, lower is better):
CUDA is untouched — RTX 4090 still 19/24, best 3.77×, 0 violations. Three real bugs found by testing, not inspection
Also fixed an off-by-grid launch ( OutstandingThe fused kernel is still scalar-dot, not matrix-core. RDNA4 exposes Method for the above: |
…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.
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 undergptqmodel_ext/nf12/with the original Apache-2.0 headers.ADinnf12_adcredits AlpinDale's modified layout.What's included
METHOD.NF12_AD,FORMAT.NF12_AD,BACKEND.NF12_AD,NF12ADConfigNF12ADLinear(gptqmodel/nn_modules/qlinear/nf12_ad.py)gptqmodel/utils/nf12_codec.py— pure-Torch reference, CPU + ROCm fallbackgptqmodel_ext/nf12/— vendored from dphnAI/nf12, JIT-builtgptqmodel_ext/nf12_hip/— new, RDNA4gfx1200/gfx1201/gfx1250: decode, encode, small-M fused, and matrix-core fusedgptqmodel/rocm_llc.py— back-ports pytorch#203965scripts/validate_nf12_ad.py— full metric tables, no pass/fail reductiontests/test_nf12_ad_codec.py,tests/test_rocm_llc.pyStorage: checkpoints are never misread as dense weights
nf12_adpersists as quantized tensors, exactly like the other methods:State dict keys after a forward:
qweight, nf12_escapes, nf12_exp_base(+biaswhen present). No denseweightbuffer survives. Decode scratch is local to the consuming call.Builds: JIT from source only, never a packaged
.solibnf12_ad.soandlibnf12_ad_torch.soare always compiled from the vendored sources into a source-hashed cache.MANIFEST.inships sources only; a cleangit archiveof 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, nowgmma/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:m <= 16nf12_ad_linear_fused17 <= m <= 128nf12_ad_linear_wmmam > 128, or nowmma-128b-instsEncode kernel
nf12_ad_encode.hipports the CUDA analyze/count/scan/write pipeline with a hand-written block-wide exclusive scan (ROCm ships no CUB). It is byte-identical tonf12_codec.encode— sameexp_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.pynow callship.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.hipdecodes each 16×64 super-atom once into shared memory and feedsv_wmma_f32_16x16x16_bf16_w32_gfx12for 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):
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 fromm, som=32runs a 2-tile kernel instead of paying for 8 tiles of matrix-core work. A runtime loop defeated unrolling, spilledacc[], and measured 3–5× slower.grid.zwith 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, notm— splitting loses at N=11008 (86 CTAs).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. AtkMt=8that 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:
__byte_perm→v_perm_b32is not a transliteration. AMD uses one full byte per output byte where0..3selects the second argument and4..7the first — reversed vs NVIDIA's nibble semantics.nv_sel_to_amd()converts selectors at compile time.hip_bfloat16is not valid in a hipified.hipTU. A barehip_bfloat16silently degrades toint. Device code uses__hip_bfloat16; the host TU passes the output buffer asvoid*.__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 runtimegcnArchNametest. For the same reason a guard must not change a declaration between passes — different mangled names fail with "Cannot find Symbol" — soNF12_AD_HAS_WMMAgates only executable bodies.__builtin_amdgcn_fdot2is 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.gfx1250has nowmma-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_tcarries onlyl2CacheSizeandhipDeviceGetAttributehas no LLC enum. The R9700's 8 MiB L2 figure is correct but incomplete — a 64 MiB Infinity Cache (MALL) sits behind it, andamd-smi static --cachereports it asL3 = 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.pyback-ports the Python half of pytorch#203965: it addslast_level_cache_size(queries HSA's cache array via ctypes, no new link dependency), makes Inductor usemax(L2, LLC)for its flush buffer and CUDA-graph input pool, and is applied fromgptqmodel/__init__.pybefore any other Torch use.L2_cache_sizeis untouched. Costs ~370 ms on a 5.7 s import;GPTQMODEL_NO_ROCM_LLC=1skips 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|withatol = rtol = 2e-3, computed in float64. A baremax(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.35on an element whose absolute error was0.5ULP). Reported instead:max_abs,max_abs / ULP(scale),max_relrestricted to elements ≥ 1% ofmax|ref|, andrms(|err|)/rms(|ref|).Accuracy — all three GPUs
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-3at everym, 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).extremescovers ±0, subnormals, Inf and NaN payloads;wide_expspans 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.matmulis already compute-bound and the decode overhead is not amortized.Performance — RDNA4 (HIP)
R9700,
gfx1201, 32 CUs, wave32, versustorch.nn.functional.linearon 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):
Cold — several weights cycled, working set > 96 MiB (what a real multi-layer model does):
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..96band. Atm = 17..64the 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 = 96the CTA already covers 96–128 tokens and the kernel turns matrix-core/decode bound rather than bandwidth bound, sonf12_ad_wmma_max_m()returns 128 and larger M goes to rocBLAS.Decode throughput (NF12 → BF16):
Methodology notes
L2_cache_sizeunder-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 matchesamd-smi'sL3and the sweep.Testing
Plus
ruff checkclean, and the wmma and encode kernels gated byscripts/validate_nf12_ad.pyon the R9700.Known limitations
m ≤ 96) and loses at 4096², where BF16 is cache-resident. Both tables above are reported as-is.m > 96band andgfx1250stay on decode-then-rocBLAS.sm_89andsm_120a;sm_80/sm_90are compiled but not measured here.N % 16 == 0andK % 64 == 0are required by the format.rocm_llccudagraph patch declines cleanly if torch moves the expression it rewrites; it never rewrites unrecognized source.Credits
ADinnf12_adis for AlpinDale.