From 73f3683c637a314b4500964a30b72293fbc03275 Mon Sep 17 00:00:00 2001 From: sstamenk Date: Mon, 16 Nov 2026 15:33:13 +0100 Subject: [PATCH 01/10] [ROCm] Add a WMMA kernel for the fused 4-bit GEMM on RDNA3, RDNA3.5 and RDNA4 Adds csrc/gemm_4bit_wmma.cu, a WMMA-based fused 4-bit (NF4/FP4) GEMM for Radeon GPUs, and dispatches to it from the existing ROCm SIMT/dequant path. It extends the fused path's advantage over dequant+F.linear from a few rows to several hundred, mirroring the CUDA SIMT > MMA > dequant+BLAS dispatch. Kernel - gfx11 (RDNA3/RDNA3.5) v_wmma_f32_16x16x16_{f16,bf16}: a wave32 WMMA runs as two independent 8x16x16 half-wave products, so each half-wave takes its own 32-K slice (summed with permlanex16); 8 real rows per WMMA. - gfx12 (RDNA4) _w32_gfx12 WMMAs: one full 16x16x16 product; each half-wave supplies its own K slice, summed inside the WMMA. - Weights decoded through a 256-entry LDS byte -> centroid-pair table; absmax applied in fp32 after the WMMAs (gfx11 fp16 large tiles pre-scale the B operand with packed half math instead; nested statistics keep the fp32 path). A is double-buffered in LDS, split-K across warps with a deterministic LDS reduction, per-block K-chunk rotation against DRAM channel camping, and row-tiles-first block order so row tiles of the same columns share B in L2. - fp32 is emulated with 3-way split bf16 operands (6 WMMAs per tile) and stays fp32-accurate (~3-5e-6 relative error vs a float64 reference). Dispatch (K % 64 == 0, blocksize >= 32) - Tile rules per target (gfx110x, gfx1103, gfx1151, gfx1201), fitted from tile sweeps over 40 LLM linear-layer shapes at a pinned GPU performance level. - SIMT vs WMMA in csrc/gemm_4bit.cu: bf16/fp16 WMMA from M = 1 (gfx11/gfx115x) or M = 2 (gfx1201); fp32 picks SIMT or WMMA by M and N. - Fused vs dequant+F.linear in _gemm_4bit_use_custom_rocm: gfx110x bf16/fp16 through M = 384 and fp32 through 128; gfx1103 through 384 for all dtypes; gfx1151 through 512; gfx1201 bf16/fp16 through 384 and fp32 through 512. gfx1101/gfx1102, gfx1150/gfx1152/gfx1153 and gfx1200 use the rules of their family's measured chip (gfx1100, gfx1151, gfx1201): same WMMA instructions, not measured. Performance (speedup of the total time over 40 LLM linear-layer shapes vs the previous dispatch, SIMT for M <= 8 and dequant+F.linear above; NF4 blocksize 64, weights streamed from DRAM, pinned clocks; bf16/fp16 at M = 8 / 16 / 128 / 256): - Radeon Pro W7900 (gfx1100): 2.8-2.9x / 5.2-5.8x / 1.6x / 1.2x - Radeon AI PRO R9700 (gfx1201): 2.7x / 5.9x / 2.0x / 1.3x - Radeon 8060S (gfx1151): 2.6-3.0x / 6.5-7.1x / 2.8-3.0x / 2.0-2.2x - Radeon 760M (gfx1103): 2.3-2.5x / 8.6x / 2.7-2.8x / 1.6-1.7x fp32 gains 1.5-2.1x at M = 8 and 4.4-9.2x at M = 16. At M = 1-2 the gain is small and some shapes lose (up to 16% at M = 1 on gfx11; on gfx1201 at M = 2, 6-7 of 40 shapes by up to 0.6x). Within the caps the default dispatch's total time is within ~2% of a per-shape oracle over SIMT, WMMA and dequant+F.linear at most M (largest gap 6.3%, gfx1151 fp32 M = 3). Tests: extra odd shapes for the 4-bit GEMM and an fp32 precision test. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 4 +- bitsandbytes/backends/cuda/ops.py | 41 +- csrc/gemm_4bit.cu | 70 +- csrc/gemm_4bit_wmma.cu | 1036 +++++++++++++++++++++++++++++ csrc/gemm_4bit_wmma.cuh | 21 + tests/test_functional.py | 32 + 6 files changed, 1184 insertions(+), 20 deletions(-) create mode 100644 csrc/gemm_4bit_wmma.cu create mode 100644 csrc/gemm_4bit_wmma.cuh diff --git a/CMakeLists.txt b/CMakeLists.txt index 0066d086f..0de2a627a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -277,8 +277,8 @@ elseif(BUILD_HIP) list(APPEND SRC_FILES ${GPU_FILES}) # 4-bit GEMM: build the SIMT kernel + C dispatch on ROCm. - set_source_files_properties(csrc/gemm_4bit_simt.cu csrc/gemm_4bit.cu PROPERTIES LANGUAGE HIP) - list(APPEND SRC_FILES csrc/gemm_4bit_simt.cu csrc/gemm_4bit.cu) + set_source_files_properties(csrc/gemm_4bit_simt.cu csrc/gemm_4bit_wmma.cu csrc/gemm_4bit.cu PROPERTIES LANGUAGE HIP) + list(APPEND SRC_FILES csrc/gemm_4bit_simt.cu csrc/gemm_4bit_wmma.cu csrc/gemm_4bit.cu) string(APPEND BNB_OUTPUT_NAME "_rocm") diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index a0d9ffe83..122b1cef3 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -814,21 +814,33 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): @functools.cache def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): """ - Fused SIMT kernel vs dequant+F.linear heuristic for ROCm. - - RDNA3/RDNA4 calibration keeps the SIMT kernel through ~M=8. - gfx125x (CDNA5) is Wave32 but lacks the v_dot2 SIMT - instructions, so its kernel takes the fp32-FMA CDNA math path. The crossover - below is left at the gfx12 default (M<=8) pending dedicated calibration. - CDNA/gfx9 is calibrated on MI308X (gfx942): bf16/fp16 win through M<=4 - after the SIMT math-path tuning, while fp32 only has a broad win through M<=2. - - TODO: revisit once WMMA/MFMA kernels land; calibrate the gfx125x crossover. + Fused custom kernel vs dequant+F.linear heuristic for ROCm. + + RDNA3/RDNA3.5/RDNA4 with K % 64 == 0 have a WMMA kernel (the C dispatch picks SIMT or WMMA), + which stays ahead of dequant+F.linear up to these M limits: + - gfx110x: bf16/fp16 through M=384, fp32 through M=128. + - gfx1103: all dtypes through M=384. + - gfx115x: all dtypes through M=512. + - gfx120x: bf16/fp16 through M=384, fp32 through M=512. + Otherwise (K % 64 != 0) gfx11/gfx12 keep SIMT through M=8. gfx125x (CDNA5) is Wave32 but lacks the v_dot2 + SIMT instructions, so its kernel takes the fp32-FMA CDNA math path; it keeps the gfx12 default + (M<=8) pending calibration. CDNA/gfx9 is calibrated on MI308X (gfx942): bf16/fp16 win through + M<=4 after the SIMT math-path tuning, fp32 only through M<=2. + + TODO: add MFMA kernels for CDNA; calibrate the gfx125x crossover. """ if M <= _GEMM_4BIT_CUSTOM_FLOOR_M and dtype != torch.float32: return True arch = _rocm_gfx_arch(device_index) + if arch == "gfx1103" and K % 64 == 0: # RDNA3 iGPU WMMA + return M <= 384 + if arch.startswith("gfx110") and K % 64 == 0: # RDNA3 WMMA + return M <= (128 if dtype == torch.float32 else 384) + if arch.startswith("gfx115") and K % 64 == 0: # RDNA3.5 WMMA (gfx1151 values) + return M <= 512 + if arch.startswith("gfx120") and K % 64 == 0: # RDNA4 WMMA (gfx1201 values) + return M <= (512 if dtype == torch.float32 else 384) if arch.startswith("gfx11") or arch.startswith("gfx12"): # RDNA3 / RDNA4 / CDNA5 (gfx125x) return M <= 8 if arch.startswith("gfx9"): # CDNA1-4 / MI-series (Wave64) @@ -917,7 +929,7 @@ def _dequant_linear_fallback( # Unified CUDA/ROCm dispatch for bitsandbytes::gemm_4bit. The choice *among* custom -# kernels (CUDA SIMT vs MMA; ROCm SIMT) is made in the C dispatch (csrc/gemm_4bit.cu). +# kernels (CUDA SIMT vs MMA; ROCm SIMT vs WMMA) is made in the C dispatch (csrc/gemm_4bit.cu). _GEMM_4BIT_CUSTOM_FLOOR_M = 4 if torch.version.hip is None: _gemm_4bit_use_custom_fn = _gemm_4bit_use_custom_cuda @@ -926,9 +938,10 @@ def _dequant_linear_fallback( _gemm_4bit_custom_max_m = 1536 else: _gemm_4bit_use_custom_fn = _gemm_4bit_use_custom_rocm - # ROCm: the custom path is SIMT-only today; the per-arch heuristic above owns - # RDNA/CDNA thresholds. Keep a hard upper cap while WMMA/MFMA paths are absent. - _gemm_4bit_custom_max_m = 256 + # ROCm: the per-arch heuristic above owns RDNA/CDNA thresholds; gfx110x/gfx1201 bf16/fp16 + # keep the custom kernel through M=384, gfx1103 fp32 through M=384, gfx1151 (all dtypes) + # and gfx1201 fp32 through M=512. + _gemm_4bit_custom_max_m = 512 @register_kernel("bitsandbytes::gemm_4bit", "cuda") diff --git a/csrc/gemm_4bit.cu b/csrc/gemm_4bit.cu index ff2f011a2..edb1fdc17 100644 --- a/csrc/gemm_4bit.cu +++ b/csrc/gemm_4bit.cu @@ -1,12 +1,16 @@ // C API for the custom 4-bit GEMM. -// Dispatches to SIMT or MMA kernels based on GPU architecture and shape. +// Dispatches to SIMT, MMA (CUDA) or WMMA (ROCm RDNA3/RDNA4) kernels based on GPU architecture and shape. // Computes out[M, N] = A[M, K] @ B[N, K]^T. All pointers are device memory. +#include #include #include #include "compat.cuh" #include "gemm_4bit_simt.cuh" +#if BNB_HIP +#include "gemm_4bit_wmma.cuh" +#endif #if defined(BNB_HAS_GEMM4BIT_SM75) || defined(BNB_HAS_GEMM4BIT_SM80) // Included only when an MMA-capable arch (sm75/sm80+) is in the build. #include "gemm_4bit_common.cuh" // GpuProps, used only by the MMA dispatch below @@ -38,8 +42,9 @@ GpuProps get_gpu_props() { /// @brief Fused 4-bit dequantize + GEMM. Computes out[M,N] = A[M,K] @ B[N,K]^T + bias. /// -/// Dispatches to SIMT (sm60+) or MMA (sm75 fp16, sm80+ bf16/fp16) based on GPU arch and shape. -/// fp32 always uses SIMT. Supports single-level and double-quantized (nested) absmax. +/// Dispatches to SIMT (sm60+, all ROCm), MMA (sm75 fp16, sm80+ bf16/fp16) or WMMA (RDNA3/RDNA4 +/// bf16/fp16/fp32) based on GPU arch and shape. fp32 uses SIMT except on RDNA3/RDNA4. Supports +/// single-level and double-quantized (nested) absmax. /// /// @tparam T Input/output dtype (`bnb_bfloat16`, `half`, or `float`) template @@ -61,7 +66,64 @@ static void gemm_4bit( ) { constexpr bool is_fp32 = std::is_same_v; - // fp32 and M<=3 are always SIMT regardless of GPU -- skip the props lookup. +#if BNB_HIP + // WMMA needs K % 64 == 0 and at least 32-element quantization blocks. + // RDNA3 (gfx110x) and RDNA3.5 (gfx115x, gfx11 kernels): on the 40 calibrated LLM shapes + // WMMA beats SIMT for bf16/fp16 at every M (gfx1100: at M=1 by ~8% in total time, mostly + // on the larger weights). + // RDNA4 (gfx1201): each WMMA covers 16 rows (gfx11: 8), so SIMT keeps the smallest M. + // On gfx1201 WMMA is 7-10% faster than SIMT in total time over the 40 shapes from M=2 + // for bf16/fp16 (2-3% slower at M=1). + // fp32 (six split-bf16 WMMAs per tile) picks by M and N, see below. + constexpr int GFX12_MIN_M_16BIT = 2; + const int wmma_arch = K % 64 == 0 && blocksize >= 32 ? gemm_4bit_wmma_arch() : 0; + bool use_wmma = + (wmma_arch == 11 || wmma_arch == 113 || wmma_arch == 115) || (wmma_arch == 12 && M >= GFX12_MIN_M_16BIT); + if (wmma_arch != 0 && is_fp32) { + // fp32: with few output columns the split-bf16 WMMA tiles leave too few blocks to + // stream the weights, so SIMT stays faster up to a few rows (gfx12's 16-row tiles: a + // few dozen). The first row with M <= max_m decides: WMMA iff N >= min_n; past the + // last row WMMA always. Fitted per target from SIMT and WMMA timings at every M up + // to 32: + // - gfx1100 (W7900, pinned clocks): within 2.6% of the per-shape faster kernel in total + // time at M = 4-5 and within 1.7% from M = 6 (SIMT through M = 5 was 1.10x slower at + // M = 5); WMMA at M = 4 lost to SIMT on tall-K shapes by up to 1.34x. + // - gfx1201 (R9700, pinned clocks): within 0.8% in total at M = 5-32; single shapes up + // to 1.14x slower near the N cutoffs (WMMA alone was up to 1.6x slower at M = 6). + struct Cutoff { + int max_m, min_n; + }; + + // Narrow weights stay on SIMT longer (dense M scan, pinned clocks): with N <= 1024 the + // split-bf16 WMMA tiles leave too few blocks, up to 2.4x slower than SIMT at M = 52. + static constexpr Cutoff gfx11_fp32_wmma[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, + {8, 2048}, {12, 2816}, {64, 1024}}; + static constexpr Cutoff gfx115_fp32_wmma[] = {{3, INT_MAX}, {5, 2560}, {7, 1024}}; + // gfx1103 (Radeon 760M, 8 CUs, pinned clocks): SIMT through M = 2, WMMA from M = 3 (by N + // through M = 4): 1.12x faster in total at M = 3 and 1.29x at M = 4 than the gfx1100 table, + // which kept SIMT through M = 4. WMMA for wide N at M = 2 measured 2% slower. + static constexpr Cutoff gfx1103_fp32_wmma[] = {{2, INT_MAX}, {4, 3840}}; + static constexpr Cutoff gfx12_fp32_wmma[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, + {9, 2048}, {15, 1408}, {31, 1024}}; + auto pick = [&](const auto& table) { + for (const auto& row : table) + if (M <= row.max_m) + return N >= row.min_n; + return true; + }; + use_wmma = wmma_arch == 12 ? pick(gfx12_fp32_wmma) + : wmma_arch == 115 ? pick(gfx115_fp32_wmma) + : wmma_arch == 113 ? pick(gfx1103_fp32_wmma) + : pick(gfx11_fp32_wmma); + } + if (use_wmma && launch_gemm_4bit_wmma( + wmma_arch, A, B, absmax, absmax_8bit, absmax_code, absmax_offset, out, bias, M, N, K, blocksize, + quant_type, stream + )) + return; +#endif + + // Otherwise fp32 and M<=3 are always SIMT -- skip the props lookup. if (is_fp32 || M <= 3) { launch_gemm_4bit_simt( A, B, absmax, absmax_8bit, absmax_code, absmax_offset, out, bias, M, N, K, blocksize, quant_type, stream diff --git a/csrc/gemm_4bit_wmma.cu b/csrc/gemm_4bit_wmma.cu new file mode 100644 index 000000000..4a94106bd --- /dev/null +++ b/csrc/gemm_4bit_wmma.cu @@ -0,0 +1,1036 @@ +// AMD WMMA 4-bit GEMM kernel for RDNA3 (gfx110x) and RDNA4 (gfx120x), wave32. +// Computes C[M,N] = A[M,K] @ B[N,K]^T + bias with fused 4-bit dequantization. + +#include +#include +#include +#include + +#include "common.cuh" +#include "gemm_4bit_common.cuh" +#include "gemm_4bit_wmma.cuh" + +// RDNA3.5 (gfx115x) shares the gfx11 WMMA encoding and half-wave behaviour +//, so it runs the gfx11 kernels. +#define BNB_WMMA_RDNA3 (IS_RDNA3 || IS_RDNA3_5) +#define BNB_WMMA_RDNA4 IS_RDNA4 + +// WMMA generation the current device pass compiles kernel bodies for (0 = none, +// including the host pass). Kernels are templated on the generation so the host +// can size tiles for the device it runs on. +#if BNB_WMMA_RDNA3 +#define BNB_WMMA_DEVICE_ARCH 11 +#elif BNB_WMMA_RDNA4 +#define BNB_WMMA_DEVICE_ARCH 12 +#else +#define BNB_WMMA_DEVICE_ARCH 0 +#endif + +// Which kernel generations a compilation pass instantiates: the host pass needs every +// launch stub, a device pass only the kernels of its own generation, so no target's code +// object carries empty kernels for the other one (non-WMMA targets carry none). +#ifdef __HIP_DEVICE_COMPILE__ +#define BNB_WMMA_EMIT_11 (BNB_WMMA_DEVICE_ARCH == 11) +#define BNB_WMMA_EMIT_12 (BNB_WMMA_DEVICE_ARCH == 12) +#else +#define BNB_WMMA_EMIT_11 1 +#define BNB_WMMA_EMIT_12 1 +#endif + +namespace { + +// K elements per warp per 64-K unit: each half-wave takes 32 contiguous K. +// A main-loop iteration consumes KCH units, i.e. 64*KCH K per warp. +constexpr int WMMA_KC = 64; + +// Native vector types: HIP's uint4 is a class, and copying it through private +// arrays lowers to memcpy that stays in scratch memory. +using wmma_v2u = uint32_t __attribute__((ext_vector_type(2))); +using wmma_v4u = uint32_t __attribute__((ext_vector_type(4))); +using wmma_v8f = float __attribute__((ext_vector_type(8))); +using wmma_v8u = uint32_t __attribute__((ext_vector_type(8))); +using wmma_v8h = _Float16 __attribute__((ext_vector_type(8))); +using wmma_v8s = short __attribute__((ext_vector_type(8))); +using wmma_v16h = _Float16 __attribute__((ext_vector_type(16))); +using wmma_v16s = short __attribute__((ext_vector_type(16))); + +// Output rows per WMMA that carry real data: gfx11 runs two 8-row half-wave +// products (see wmma_16x16x16), gfx12 one full 16x16x16 product. +constexpr int wmma_rows(int arch) { return arch == 12 ? 16 : 8; } + +// Tuning targets returned by gemm_4bit_wmma_arch(): 11 (gfx110x), 115 (gfx115x, RDNA3.5) +// and 12 (gfx120x). gfx115x runs the gfx11 kernels with its own tile rules. +constexpr int WMMA_TARGET_GFX115X = 115; +// gfx1103 (Radeon 760M/780M iGPU): gfx110x kernels and tile rules, own fp32 dispatch (see +// csrc/gemm_4bit.cu and the Python cutover). +constexpr int WMMA_TARGET_GFX1103 = 113; + +constexpr int wmma_gen(int target) { + return target == WMMA_TARGET_GFX115X || target == WMMA_TARGET_GFX1103 ? 11 : target; +} + +// Per-lane operand fragment: 16 (gfx11) or 8 (gfx12) 16-bit values. +template using wmma_frag = std::conditional_t; + +/// @brief One v_wmma_f32_16x16x16_{f16,bf16} on 16-bit operand bits (bf16 for +/// T = bnb_bfloat16 and for the split fp32 path). +/// +/// gfx11 executes a wave32 WMMA as two independent 8x16x16 products: lanes 0-15 +/// produce the even output rows from their own B copy and the A rows held by the +/// even lanes, lanes 16-31 produce the odd rows from their own B copy and the odd +/// lanes' A rows. The ISA asks for replicated operands, but because each half only +/// reads its own copy, the kernel feeds the two halves different K slices and sums +/// the halves once at the end. Every weight nibble is decoded exactly once. +/// +/// gfx12 has no replication: lane L holds A row L%16 (B column L%16) at K +/// 8*(L/16) + e for its 8 elements e, and accumulator element j holds row +/// j + 8*(L/16), column L%16. +/// Since only the pairing of A and B K indices matters, each half-wave again +/// supplies its own K slice, now summed inside the WMMA. +template +__device__ __forceinline__ wmma_v8f wmma_16x16x16(wmma_frag a, wmma_frag b, wmma_v8f c) { + if constexpr (ARCH == 11) { +#if BNB_WMMA_RDNA3 + if constexpr (std::is_same_v) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32( + __builtin_bit_cast(wmma_v16h, a), __builtin_bit_cast(wmma_v16h, b), c + ); + } else { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32( + __builtin_bit_cast(wmma_v16s, a), __builtin_bit_cast(wmma_v16s, b), c + ); + } +#endif + } else { +#if BNB_WMMA_RDNA4 + if constexpr (std::is_same_v) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12( + __builtin_bit_cast(wmma_v8h, a), __builtin_bit_cast(wmma_v8h, b), c + ); + } else { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12( + __builtin_bit_cast(wmma_v8s, a), __builtin_bit_cast(wmma_v8s, b), c + ); + } +#endif + } + return c; +} + +// fp32 operands are split into this many bf16 parts (~24 mantissa bits). +constexpr int WMMA_F32_PARTS = 3; + +// Split an fp32 value into P bf16 parts (bit patterns in the low 16 bits) whose sum +// is x to ~2^-(8P) relative: every part but the last truncates, so each remainder +// is exact in fp32; the last rounds to nearest even. Inf/NaN keep the lower parts at +// zero so they propagate through the leading part alone. +template __device__ __forceinline__ void split_bf16(float x, uint32_t (&parts)[P]) { + const bool finite = (__builtin_bit_cast(uint32_t, x) & 0x7f800000u) != 0x7f800000u; + float r = x; +#pragma unroll + for (int p = 0; p < P - 1; p++) { + const uint32_t bits = __builtin_bit_cast(uint32_t, r); + parts[p] = bits >> 16; + r = r - __builtin_bit_cast(float, bits & 0xffff0000u); + } + const uint32_t bits = __builtin_bit_cast(uint32_t, r); + parts[P - 1] = (bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16; + if (!finite) { +#pragma unroll + for (int p = 1; p < P; p++) + parts[p] = 0u; + } +} + +// Add the value held by the lane 16 positions away (the other half-wave). +__device__ __forceinline__ float half_wave_sum(float v) { +#if BNB_WMMA_RDNA3 + const uint32_t other = __builtin_amdgcn_permlanex16( + __builtin_bit_cast(uint32_t, v), __builtin_bit_cast(uint32_t, v), 0x76543210u, 0xfedcba98u, false, false + ); + return v + __builtin_bit_cast(float, other); +#else + return v; +#endif +} + +// LDS bytes for the A stages (two stages of `planes` 16-bit tiles: 1, or WMMA_F32_PARTS = 3 +// for the fp32 hi/mid/lo split) or, reusing the same space, the split-K reduction tile, +// whichever is larger. The staged A rows are padded by 8 elements: keeps 16-byte +// alignment and spreads rows across LDS banks. +constexpr int wmma_smem_bytes(int mt, int nt, int ksplit, int kch, int planes) { + const int a_bytes = 2 * planes * ksplit * mt * (WMMA_KC * kch + 8) * 2; + const int red_bytes = ksplit > 1 ? ksplit * mt * nt * 4 : 0; + return a_bytes > red_bytes ? a_bytes : red_bytes; +} + +} // namespace + +/// @brief Fused 4-bit dequantize + WMMA GEMM for RDNA3 and RDNA4 (bf16, fp16 and fp32). +/// +/// fp32 has no WMMA operand type, so A and the centroids are split into three bf16 +/// parts (hi + mid + lo, ~24 mantissa bits) and each tile accumulates the six +/// products whose part indices sum to < 3 in fp32 -- six WMMAs per 16-bit one, +/// with fp32-level accuracy. +/// +/// Block: KSPLIT x WARPS_M x WARPS_N warps; block tile MT = WARPS_M*R*WM rows x +/// NT = WARPS_N*16*WN columns, R = wmma_rows(ARCH). Each warp owns an (R*WM) x +/// (16*WN) sub-tile; the KSPLIT warp groups split K in interleaved KC = 64*KCH +/// chunks and are reduced through LDS in a fixed order (deterministic). A gfx11 +/// WMMA covers 8 real rows x 16 columns x 32 K (16 K per half-wave), a gfx12 WMMA +/// 16 rows x 16 columns x 16 K (8 K per half-wave). +/// +/// Per iteration the block stages the A tile of its KSPLIT current chunks in LDS +/// (double-buffered, shared by all warps of a K group). Each lane (half h = +/// lane/16, c = lane%16) streams its own B columns straight from global memory, +/// 32 K per 64-K unit u = 0..KCH-1 of the chunk starting at k0: +/// B: column n; gfx11: K [k0 + 32*KCH*h + 32*u, +32), one 16-byte load per unit +/// (each half-wave is its own product, so it may use its own absmax); +/// gfx12: K [k0 + 64*u + 32*h, +32), one 16-byte load, or for blocksize 32 +/// K [k0 + 64*u + 16*h, +16) and [k0 + 64*u + 32 + 16*h, +16), two 8-byte +/// loads (both halves feed every WMMA, so their K must share an absmax). +/// Decoded through a 256-entry LDS LUT (byte -> packed pair of centroids). +/// A: row c/2 (gfx11) or c (gfx12) of each R-row sub-tile, same K range, from LDS. +/// Scale: absmax for that column/K range, applied to the fp32 accumulator after +/// the chunk's WMMAs (centroids enter the WMMA unscaled). +/// The next iteration's A and B loads are issued before the current chunk is +/// consumed; A is issued first so storing it to LDS never waits on the B loads. +/// +/// Requires K % (64*KCH) == 0 and blocksize >= 32. +/// +/// @tparam ARCH WMMA generation: 11 (gfx110x) or 12 (gfx120x) +/// @tparam T Input/output dtype (`bnb_bfloat16`, `half`, or `float`) +/// @tparam WM R-row M sub-tiles per warp +/// @tparam WN 16-column N sub-tiles per warp +/// @tparam WARPS_M Warps along M +/// @tparam WARPS_N Warps along N +/// @tparam KSPLIT Warp groups along K +/// @tparam KCH 64-K units per main-loop iteration +/// @tparam PRESCALE gfx11 fp16: round scaled B operands to half and accumulate across groups. +/// @tparam GS Consecutive WMMAs (per chain) sharing one absmax: each group's WMMAs +/// chain into one fp32 tile that is scaled once. +template < + int ARCH, typename T, int WM, int WN, int WARPS_M, int WARPS_N, int KSPLIT, int KCH, int GS, bool PRESCALE = false> +__device__ __forceinline__ void gemm_4bit_wmma_body( + // clang-format off + const T* __restrict__ A, // inputs [M, K] + const uint8_t* __restrict__ B, // packed 4-bit weights [N, K/2] + const float* __restrict__ absmax, // fp32 absmax [N, K/blocksize] or + // [ceil(N*K/(blocksize*256))] when nested + const uint8_t* __restrict__ absmax_8bit, // [N, K/blocksize] uint8 compressed absmax; + // nullptr = non-nested + const float* __restrict__ absmax_code, // [256] codebook for 8bit absmax + const float* __restrict__ absmax_offset, // scalar; nullptr = non-nested + T* __restrict__ C, // [M, N] + const T* __restrict__ bias, // [N] optional, nullptr = no bias + int M, int N, int K, // problem shape + int blocksize, // elements per quantization block + int quant_type, // 1 = FP4, 2 = NF4 + bool row_tiles_first // block order, see below + // clang-format on +) { + constexpr bool GFX12 = ARCH == 12; + constexpr int R = wmma_rows(ARCH); + constexpr int MT = WARPS_M * R * WM; + constexpr int NT = WARPS_N * 16 * WN; + constexpr int NUM_THREADS = KSPLIT * WARPS_M * WARPS_N * 32; + constexpr int KC = WMMA_KC * KCH; // K per warp per iteration + constexpr int A_STRIDE = KC + 8; // LDS row stride (elements) + constexpr bool F32 = std::is_same_v; + static_assert(!PRESCALE || (ARCH == 11 && std::is_same_v)); + constexpr int PLANES = F32 ? WMMA_F32_PARTS : 1; // fp32: one bf16 tile per split part + constexpr int A_PLANE = KSPLIT * MT * A_STRIDE; // elements per A tile + constexpr int A_STAGE = PLANES * A_PLANE; // elements per A stage + + // byte -> {centroid[hi nibble] (lower K), centroid[lo nibble] (higher K)} as + // 16-bit operand bits; fp32 keeps one table per bf16 split part. + __shared__ uint32_t lut[PLANES][256]; + // Codebook for the nested (8-bit) absmax, so the per-chunk scale needs no + // dependent global load. + __shared__ float code_lds[256]; + // A stages [2][KSPLIT][MT][A_STRIDE]; reused for the split-K reduction. + __shared__ __attribute__((aligned(16))) uint8_t smem[wmma_smem_bytes(MT, NT, KSPLIT, KCH, PLANES)]; + uint16_t* a_lds = reinterpret_cast(smem); + + const bool nested = absmax_8bit != nullptr; + { + const float* centroids = (quant_type == 1) ? FP4_LUT_F32 : NF4_LUT_F32; + for (int i = threadIdx.x; i < 256; i += NUM_THREADS) { + if constexpr (F32) { + uint32_t c0[PLANES], c1[PLANES]; + split_bf16(centroids[i >> 4], c0); + split_bf16(centroids[i & 0x0f], c1); +#pragma unroll + for (int p = 0; p < PLANES; p++) + lut[p][i] = c0[p] | (c1[p] << 16); + } else { + const T lo = static_cast(centroids[i >> 4]); + const T hi = static_cast(centroids[i & 0x0f]); + lut[0][i] = (uint32_t)(*reinterpret_cast(&lo)) | + ((uint32_t)(*reinterpret_cast(&hi)) << 16); + } + if (nested) + code_lds[i] = __ldg(&absmax_code[i]); + } + } + + const float absmax_offset_f = nested ? __ldg(absmax_offset) : 0.0f; + const int blocksize_log2 = __ffs(blocksize) - 1; + const int blocks_per_row = K >> blocksize_log2; + + const int lane = threadIdx.x & 31; + const int warp = threadIdx.x >> 5; + const int warp_n = warp % WARPS_N; + const int warp_m = (warp / WARPS_N) % WARPS_M; + const int warp_k = warp / (WARPS_N * WARPS_M); + const int half_id = lane >> 4; + const int col = lane & 15; + + // Block order. Walking N first makes every row tile stream all of B from DRAM again + // once B no longer fits in the last-level cache. With row_tiles_first, the row tiles of + // the same N columns get consecutive block ids, so they are resident together and share + // each B chunk through L2 (see wmma_row_tiles_first). + int bx = blockIdx.x, by = blockIdx.y; + if (row_tiles_first) { + const int lin = blockIdx.x + gridDim.x * blockIdx.y; + bx = lin / gridDim.y; + by = lin % gridDim.y; + } + const int bn = bx * NT; + const int bm = by * MT; + + // Per-lane weight rows (clamped so tail lanes read valid memory; never stored). + const uint8_t* b_row[WN]; + int blk_row[WN]; +#pragma unroll + for (int wn = 0; wn < WN; wn++) { + const int n = min(bn + (warp_n * WN + wn) * 16 + col, N - 1); + b_row[wn] = B + (size_t)n * (K / 2); + blk_row[wn] = n * blocks_per_row; + } + + const int num_chunks = K / KC; + const int num_iters = (num_chunks + KSPLIT - 1) / KSPLIT; + + // Blocks start at different K chunks so that concurrently resident blocks + // stream different K offsets of their rows. With power-of-two row strides + // (K/2 bytes), lock-stepped blocks otherwise camp on a few DRAM channels. + const int chunk_rot = bx % num_chunks; + // First K element of warp group g's chunk at iteration i. Past-the-end chunks + // (last iteration when KSPLIT does not divide num_chunks) alias a valid chunk: + // they are loaded but never consumed, which keeps every load unconditional. + auto chunk_valid = [&](int i, int g) { return i * KSPLIT + g < num_chunks; }; + auto chunk_k0 = [&](int i, int g) { + int ch = i * KSPLIT + g + chunk_rot; + while (ch >= num_chunks) + ch -= num_chunks; + return ch * KC; + }; + + // Cooperative A tile copy: KSPLIT x MT rows x KC/VEC_ELEMS 16-byte vectors per + // stage (fp32 vectors are split into the hi/lo tiles on the way to LDS). Rows + // past M are clamped to a valid row: WMMA output rows only depend on their own A + // row, and those rows are never stored. + constexpr int VEC_ELEMS = 16 / (int)sizeof(T); + constexpr int ROW_VECS = KC / VEC_ELEMS; + constexpr int A_VECS = KSPLIT * MT * ROW_VECS; + constexpr int A_VECS_PER_THREAD = (A_VECS + NUM_THREADS - 1) / NUM_THREADS; + wmma_v4u a_stage[A_VECS_PER_THREAD]; + auto issue_a = [&](int i) { +#pragma clang loop unroll(full) + for (int j = 0; j < A_VECS_PER_THREAD; j++) { + const int v = threadIdx.x + j * NUM_THREADS; + if (A_VECS % NUM_THREADS == 0 || v < A_VECS) { + const int part = v % ROW_VECS; + const int row = (v / ROW_VECS) % MT; + const int g = (v / ROW_VECS) / MT; + a_stage[j] = *reinterpret_cast( + A + (size_t)min(bm + row, M - 1) * K + chunk_k0(i, g) + part * VEC_ELEMS + ); + } + } + }; + auto store_a = [&](int buf) { +#pragma clang loop unroll(full) + for (int j = 0; j < A_VECS_PER_THREAD; j++) { + const int v = threadIdx.x + j * NUM_THREADS; + if (A_VECS % NUM_THREADS == 0 || v < A_VECS) { + const int part = v % ROW_VECS; + const int rg = v / ROW_VECS; // g * MT + row + uint16_t* dst = &a_lds[buf * A_STAGE + rg * A_STRIDE + part * VEC_ELEMS]; + if constexpr (F32) { + uint32_t parts[4][PLANES]; +#pragma unroll + for (int e = 0; e < 4; e++) { + // Copy the element out first: __builtin_bit_cast on a vector element + // lvalue reads element 0 with this clang. + const uint32_t bits = a_stage[j][e]; + split_bf16(__builtin_bit_cast(float, bits), parts[e]); + } +#pragma unroll + for (int p = 0; p < PLANES; p++) + *reinterpret_cast(dst + p * A_PLANE) = + wmma_v2u{parts[0][p] | (parts[1][p] << 16), parts[2][p] | (parts[3][p] << 16)}; + } else { + *reinterpret_cast(dst) = a_stage[j]; + } + } + } + }; + + // Each lane decodes 32 K (16 bytes) of its column per 64-K unit u, as SUBS + // WMMAs of 16-bit words (FRAG_WORDS per operand fragment): + // gfx11: half h takes K [32*KCH*h + 32*u, +32), 2 WMMAs of 16 K; the halves + // are separate products, so each half may use its own absmax. + // gfx12: both halves feed every WMMA, so their K must share an absmax. Half h + // takes K [64*u + 32*h, +32) when blocksize >= 64 (one 16-byte load), + // or K [64*u + 16*h, +16) and [64*u + 32 + 16*h, +16) when blocksize + // is 32 (two 8-byte loads; WMMAs 0-1 then read the first 32-K block, + // WMMAs 2-3 the second). 4 WMMAs of 8 K per lane. + using Frag = wmma_frag; + constexpr int SUBS = GFX12 ? 4 : 2; + constexpr int FRAG_WORDS = 16 / SUBS; + constexpr bool SPLIT32 = GFX12 && GS < SUBS; // gfx12, blocksize 32 + constexpr int NG = KCH * SUBS / GS; // scale groups per iteration + // WMMAs per group within one unit. gfx12 fp32 (split bf16) decodes one fragment at a + // time to save registers; other paths decode the whole group. + constexpr int GROUP_SUBS = ARCH == 12 && F32 ? 1 : (GS < SUBS ? GS : SUBS); + constexpr int UNIT_K = GFX12 ? 64 : 32; // K between a lane's consecutive units + // First K of the lane's slice in unit 0 (relative to the chunk start). + const int k_lane = GFX12 ? (SPLIT32 ? 16 : 32) * half_id : 32 * KCH * half_id; + // K offset of the lane's WMMA t (flat index u * SUBS + s) from k_lane. + auto k_sub = [](int t) { + const int s = t % SUBS; + return UNIT_K * (t / SUBS) + (SPLIT32 && s >= 2 ? 16 : 0) + s * (32 / SUBS); + }; + + struct BStage { + wmma_v4u b[WN][KCH]; + float scale[WN][NG]; // absmax, or the fp32 state2 absmax when nested + uint32_t qidx[WN][NG]; // nested: 8-bit absmax code index + }; + + auto issue_b = [&](int i, BStage& st) { + const int k_half = chunk_k0(i, warp_k) + k_lane; +#pragma unroll + for (int wn = 0; wn < WN; wn++) { +#pragma unroll + for (int u = 0; u < KCH; u++) { + const uint8_t* p = b_row[wn] + (k_half + u * UNIT_K) / 2; + if constexpr (SPLIT32) { + const wmma_v2u lo = *reinterpret_cast(p); + const wmma_v2u hi = *reinterpret_cast(p + 16); + st.b[wn][u] = wmma_v4u{lo.x, lo.y, hi.x, hi.y}; + } else { + st.b[wn][u] = *reinterpret_cast(p); + } + } +#pragma unroll + for (int g = 0; g < NG; g++) { + const int blk = blk_row[wn] + ((k_half + k_sub(g * GS)) >> blocksize_log2); + st.qidx[wn][g] = nested ? absmax_8bit[blk] : 0u; + st.scale[wn][g] = __ldg(&absmax[nested ? blk >> 8 : blk]); + } + } + }; + + wmma_v8f acc[WM][WN]; +#pragma unroll + for (int wm = 0; wm < WM; wm++) +#pragma unroll + for (int wn = 0; wn < WN; wn++) + acc[wm][wn] = wmma_v8f{}; + + auto compute = [&](int buf, const BStage& st) { + const uint16_t* a_base = + a_lds + buf * A_STAGE + (warp_k * MT + warp_m * R * WM + (GFX12 ? col : col >> 1)) * A_STRIDE + k_lane; +#pragma unroll + for (int g = 0; g < NG; g++) { + float scale[WN]; +#pragma unroll + for (int wn = 0; wn < WN; wn++) + scale[wn] = nested ? code_lds[st.qidx[wn][g]] * st.scale[wn][g] + absmax_offset_f : st.scale[wn][g]; + + // Issue order keeps WM*WN independent WMMA chains in flight; the group's + // GS WMMAs per chain accumulate unscaled and are scaled once. A fragments + // stream from LDS one R-row sub-tile at a time. + wmma_v8f tmp[WM][WN]; +#pragma unroll + for (int t0 = g * GS; t0 < (g + 1) * GS; t0 += GROUP_SUBS) { + const int u = t0 / SUBS; + Frag b_frag[PLANES][WN][GROUP_SUBS]; +#pragma unroll + for (int wn = 0; wn < WN; wn++) +#pragma unroll + for (int s = 0; s < GROUP_SUBS; s++) +#pragma unroll + for (int i = 0; i < FRAG_WORDS; i++) { + const int b = (t0 % SUBS + s) * FRAG_WORDS + i; // byte within the 16-byte load + const int byte = (st.b[wn][u][b / 4] >> (8 * (b % 4))) & 0xff; +#pragma unroll + for (int p = 0; p < PLANES; p++) { + uint32_t pair = lut[p][byte]; + if constexpr (PRESCALE) { + // Shared across WM row tiles; avoids their temporary scaled sums. + const half2 v = __builtin_bit_cast(half2, pair); + const half2 factor = __float2half2_rn(scale[wn]); + pair = __builtin_bit_cast(uint32_t, __hmul2(v, factor)); + } + b_frag[p][wn][s][i] = pair; + } + } +#pragma unroll + for (int s = 0; s < GROUP_SUBS; s++) +#pragma unroll + for (int wm = 0; wm < WM; wm++) { + const uint16_t* ap = a_base + wm * R * A_STRIDE + k_sub(t0 + s); + const Frag a_frag = *reinterpret_cast(ap); + const bool first = t0 == g * GS && s == 0; +#pragma unroll + for (int wn = 0; wn < WN; wn++) { + wmma_v8f c = PRESCALE ? acc[wm][wn] : (first ? wmma_v8f{} : tmp[wm][wn]); + if constexpr (F32) { + // Products of split parts whose indices sum to < 3, smallest + // first; the leading hi*hi product comes last (below). + const Frag a_mid = *reinterpret_cast(ap + A_PLANE); + const Frag a_lo = *reinterpret_cast(ap + 2 * A_PLANE); + c = wmma_16x16x16(a_lo, b_frag[0][wn][s], c); + c = wmma_16x16x16(a_frag, b_frag[2][wn][s], c); + c = wmma_16x16x16(a_mid, b_frag[1][wn][s], c); + c = wmma_16x16x16(a_mid, b_frag[0][wn][s], c); + c = wmma_16x16x16(a_frag, b_frag[1][wn][s], c); + } + if constexpr (PRESCALE) + acc[wm][wn] = wmma_16x16x16(a_frag, b_frag[0][wn][s], c); + else + tmp[wm][wn] = wmma_16x16x16(a_frag, b_frag[0][wn][s], c); + } + } + } +#pragma unroll + for (int wm = 0; wm < WM; wm++) +#pragma unroll + for (int wn = 0; wn < WN; wn++) + if constexpr (!PRESCALE) + acc[wm][wn] += tmp[wm][wn] * scale[wn]; + } + }; + + BStage b_cur, b_nxt; + issue_a(0); + issue_b(0, b_cur); + store_a(0); + __syncthreads(); + + for (int it = 0; it < num_iters; it++) { + const bool has_next = it + 1 < num_iters; + if (has_next) { + issue_a(it + 1); + issue_b(it + 1, b_nxt); + } + if (chunk_valid(it, warp_k)) + compute(it & 1, b_cur); + if (has_next) + store_a((it + 1) & 1); + __syncthreads(); + b_cur = b_nxt; + } + + // gfx11: combine the two half-wave K slices, so every lane holds full-K sums + // for rows j (element j) and column `col`; the upper half-wave stores nothing. + // gfx12: element j of lane (h, c) already holds the full sum for row j + 8h. + if constexpr (!GFX12) { +#pragma unroll + for (int wm = 0; wm < WM; wm++) +#pragma unroll + for (int wn = 0; wn < WN; wn++) +#pragma unroll + for (int j = 0; j < 8; j++) + acc[wm][wn][j] = half_wave_sum(acc[wm][wn][j]); + } + const bool stores = GFX12 || half_id == 0; + const int row_lane = GFX12 ? 8 * half_id : 0; // row of element 0 within a sub-tile + + const int m_warp = warp_m * R * WM + row_lane; // lane's first row within the block tile + const int n_warp = warp_n * 16 * WN; + if constexpr (KSPLIT == 1) { + if (stores) { +#pragma unroll + for (int wn = 0; wn < WN; wn++) { + const int n = bn + n_warp + wn * 16 + col; + if (n >= N) + continue; + const float bias_f = bias ? static_cast(bias[n]) : 0.0f; +#pragma unroll + for (int wm = 0; wm < WM; wm++) +#pragma unroll + for (int j = 0; j < 8; j++) { + const int m = bm + m_warp + wm * R + j; + if (m < M) + C[(size_t)m * N + n] = static_cast(acc[wm][wn][j] + bias_f); + } + } + } + } else { + // Partial tiles [KSPLIT][MT][NT] in LDS (the A stages are no longer needed; + // the loop's trailing barrier ordered all reads before these writes). + float* red = reinterpret_cast(smem); + if (stores) { +#pragma unroll + for (int wm = 0; wm < WM; wm++) +#pragma unroll + for (int wn = 0; wn < WN; wn++) +#pragma unroll + for (int j = 0; j < 8; j++) + red[(warp_k * MT + m_warp + wm * R + j) * NT + n_warp + wn * 16 + col] = acc[wm][wn][j]; + } + __syncthreads(); + + for (int o = threadIdx.x; o < MT * NT; o += NUM_THREADS) { + const int m = bm + o / NT; + const int n = bn + o % NT; + if (m >= M || n >= N) + continue; + float sum = 0.0f; +#pragma unroll + for (int g = 0; g < KSPLIT; g++) + sum += red[g * MT * NT + o]; + if (bias) + sum += static_cast(bias[n]); + C[(size_t)m * N + n] = static_cast(sum); + } + } +} + +/// Kernel entry: the body is only emitted in the device pass of the matching WMMA +/// generation (see gemm_4bit_wmma_body for the parameters). +template < + int ARCH, typename T, int WM, int WN, int WARPS_M, int WARPS_N, int KSPLIT, int KCH, int GS, bool PRESCALE = false> +__global__ void __launch_bounds__(KSPLIT* WARPS_M* WARPS_N * 32) gemm_4bit_wmma( + const T* __restrict__ A, const uint8_t* __restrict__ B, const float* __restrict__ absmax, + const uint8_t* __restrict__ absmax_8bit, const float* __restrict__ absmax_code, + const float* __restrict__ absmax_offset, T* __restrict__ C, const T* __restrict__ bias, int M, int N, int K, + int blocksize, int quant_type, bool row_tiles_first +) { +#if BNB_WMMA_DEVICE_ARCH + if constexpr (ARCH == BNB_WMMA_DEVICE_ARCH) + gemm_4bit_wmma_body( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, + row_tiles_first + ); +#endif +} + +namespace { + +// WMMA tuning target for a gcnArchName ("gfx1201" or "gfx1201:xnack-"): 11, 113, 115, 12, or 0. +// The chips must be ones whose device pass emits the kernel body (IS_RDNA3 / IS_RDNA4 in +// common.cuh); any other device would launch an empty kernel. Measured: gfx1100, gfx1103, +// gfx1151 and gfx1201. gfx1101/gfx1102, gfx1150/gfx1152/gfx1153 and gfx1200 share the WMMA +// instructions of their family and use its rules (gfx1100, gfx1151, gfx1201) unmeasured. +int wmma_arch_of(const char* name) { + static constexpr struct { + const char* chip; + int arch; + } chips[] = { + {"gfx1100", 11}, + {"gfx1101", 11}, + {"gfx1102", 11}, + {"gfx1103", WMMA_TARGET_GFX1103}, + {"gfx1150", WMMA_TARGET_GFX115X}, + {"gfx1151", WMMA_TARGET_GFX115X}, + {"gfx1152", WMMA_TARGET_GFX115X}, + {"gfx1153", WMMA_TARGET_GFX115X}, + {"gfx1200", 12}, + {"gfx1201", 12} + }; + + for (const auto& c : chips) { + const size_t n = std::strlen(c.chip); + if (std::strncmp(name, c.chip, n) == 0 && (name[n] == '\0' || name[n] == ':')) + return c.arch; + } + return 0; +} + +// Cached per device (devices 0-15; later ones are queried on every call). +int wmma_device_arch() { + static std::atomic cache[16] = {}; // 0 = unknown, else arch + 1 + int dev = 0; + (void)hipGetDevice(&dev); + if (dev < 16) { + const int cached = cache[dev].load(std::memory_order_relaxed); + if (cached != 0) + return cached - 1; + } + hipDeviceProp_t prop; + const int arch = hipGetDeviceProperties(&prop, dev) == hipSuccess ? wmma_arch_of(prop.gcnArchName) : 0; + if (dev < 16) + cache[dev].store(arch + 1, std::memory_order_relaxed); + return arch; +} + +/// Whether blocks walk the row tiles of the same N columns first, so they share B in L2 +/// (see gemm_4bit_wmma_body). Only matters with two or more row tiles. fp32 on gfx110x +/// stays N-first. The tile rules are fitted with this order. +bool wmma_row_tiles_first(int target, bool fp32) { + if (target == 11 || target == WMMA_TARGET_GFX1103) + return !fp32; + return target == 12 || target == WMMA_TARGET_GFX115X; +} + +/// Launch one tile configuration. KCH_MAX is lowered to 1 when K is not a multiple +/// of 128; one absmax covers each half-wave's per-iteration K slice when +/// blocksize >= 32 * KCH. +template < + int ARCH, typename T, int WM, int WN, int WARPS_M, int WARPS_N, int KSPLIT, int KCH_MAX, bool PRESCALE = false> +void launch_wmma_tile_impl( + const T* A, const uint8_t* B, const float* absmax, const uint8_t* absmax_8bit, const float* absmax_code, + const float* absmax_offset, T* C, const T* bias, int M, int N, int K, int blocksize, int quant_type, + bool row_tiles_first, bnb_stream_t stream +) { + constexpr int MT = WARPS_M * wmma_rows(ARCH) * WM; + constexpr int NT = WARPS_N * 16 * WN; + constexpr int THREADS = KSPLIT * WARPS_M * WARPS_N * 32; + static_assert( + wmma_smem_bytes(MT, NT, KSPLIT, KCH_MAX, std::is_same_v ? WMMA_F32_PARTS : 1) <= 48 * 1024, + "tile exceeds the LDS budget" + ); + const dim3 grid((N + NT - 1) / NT, (M + MT - 1) / MT); + auto launch = [&](auto kernel) { + kernel<<>>( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, + row_tiles_first + ); + }; + // WMMAs per absmax group: gfx11 2 per 32-K slice of a lane, + // gfx12 4 per 64-K unit (2 when blocksize is 32). + if constexpr (KCH_MAX == 2) { + if (K % 128 == 0) { + if (blocksize >= 64) + launch(gemm_4bit_wmma); + else + launch(gemm_4bit_wmma); + return; + } + } + if constexpr (ARCH == 12) { + if (blocksize >= 64) { + launch(gemm_4bit_wmma); + return; + } + } + launch(gemm_4bit_wmma); +} + +template +void launch_wmma_tile( + const T* A, const uint8_t* B, const float* absmax, const uint8_t* absmax_8bit, const float* absmax_code, + const float* absmax_offset, T* C, const T* bias, int M, int N, int K, int blocksize, int quant_type, + bool row_tiles_first, bnb_stream_t stream +) { + // Prescaling shares B multiplies across row tiles. Short-K-chunk tiles and large-M + // contraction layers keep the accumulator-scaled kernel, which every tile has. + if constexpr (ARCH == 11 && std::is_same_v) { + bool prescale = M >= 96 && WM >= 2 && KCH_MAX == 2 && (M <= 128 || K <= N); + // Nested reconstruction can exceed 65504 even for finite fp16 source weights. + // Rounding that scale to half would contaminate otherwise finite products. + prescale = prescale && absmax_8bit == nullptr; + if (prescale) { + launch_wmma_tile_impl( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, + row_tiles_first, stream + ); + return; + } + } + launch_wmma_tile_impl( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, row_tiles_first, + stream + ); +} + +/// @brief Tile selection for one WMMA generation (parameters as launch_gemm_4bit_wmma). +/// +/// gfx11: calibrated on gfx1100 (W7900) at pinned clocks (perf level high) over 40 LLM +/// linear-layer shapes with row-tiles-first block order and fp16 prescaling: up to three +/// leaves on N or K/N per M bucket, fp16 total +/// time within 0.3-4.4% of the best swept tile per shape (fp32 within 1.5%). Sweeps at default (auto) clocks +/// are bimodal by ~10% and picked wrong small-M tiles. Narrow N keeps 16-column warp tiles and deeper +/// split-K so enough warps stream B; wide N uses 32-column warp tiles and 128-K +/// iterations. +template +void launch_gemm_4bit_wmma_arch( + // clang-format off + const T* A, // inputs [M, K] + const uint8_t* B, // packed 4-bit weights [N, K/2] + const float* absmax, // fp32 absmax [N*K/blocksize] or [ceil(N*K/(blocksize*256))] when nested + const uint8_t* absmax_8bit, // [N*K/blocksize] uint8 compressed absmax; nullptr = non-nested + const float* absmax_code, // [256] codebook for 8bit absmax + const float* absmax_offset, // scalar; nullptr = non-nested + T* C, // output [M, N] + const T* bias, // [N] optional, nullptr = no bias + int M, int N, int K, // problem shape + int blocksize, // elements per quantization block + int quant_type, // 1 = FP4, 2 = NF4 + bnb_stream_t stream // HIP stream + // clang-format on +) { + constexpr int ARCH = wmma_gen(TARGET); + const bool row_tiles_first = wmma_row_tiles_first(TARGET, std::is_same_v); + // clang-format off +#define LAUNCH_WMMA(WM, WN, WARPS_M, WARPS_N, KSPLIT, KCH_MAX) \ + launch_wmma_tile( \ + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, \ + row_tiles_first, stream) + + if constexpr (ARCH == 12) { + // gfx12 (16-row WMMA): calibrated on gfx1201 (R9700) at pinned clocks over the same + // 40 shapes, within ~2-6% (bf16/fp16) and ~0-2% (fp32) geomean of the best swept tile. + // One 16-row tile covers M <= 16, where the kernel is bandwidth-bound; larger M adds + // warps along N and rows per warp rather than warps along M. + if constexpr (std::is_same_v) { + // Refitted at pinned clocks on the one-fragment fp32 kernel: total time within + // 0.0-1.4% of the best swept tile per shape. + if (M <= 16) { + if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 2, 1); + else if (N < 4608) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); + else LAUNCH_WMMA(1, 2, 1, 2, 2, 1); + } else if (M <= 48) { + if (N < 8192) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); + } else if (M <= 96) { + if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 1, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); + } else if (M <= 192) { + if (N < 2048) LAUNCH_WMMA(2, 1, 1, 4, 1, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); + } else { + LAUNCH_WMMA(2, 2, 1, 4, 1, 1); + } + } else if (M <= 16) { + // fp16/bf16 refitted at pinned clocks (perf level high) on R9700: total time within + // 0.1-3.6% of the best swept tile per shape (the auto-clock rules were 9% off at + // M <= 16 and 12.5% at M = 256). + if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); + else LAUNCH_WMMA(1, 2, 1, 2, 4, 2); + } else if (M <= 32) { + if (N < 2048) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); + else if (N < 8192) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 2, 2); + } else if (M <= 96) { + if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 2, 2); + } else if (M <= 128) { + if (N < 3072) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); + else if (N < 8192) LAUNCH_WMMA(2, 2, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 2, 1, 4, 1, 1); + } else if (M <= 160) { + if (N < 3072) LAUNCH_WMMA(2, 1, 1, 4, 2, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } else { + if (N < 2816) LAUNCH_WMMA(2, 2, 1, 4, 2, 2); + else if (N < 3840) LAUNCH_WMMA(4, 1, 1, 4, 1, 1); + else LAUNCH_WMMA(4, 2, 1, 4, 1, 1); + } + return; + } else + if constexpr (TARGET == WMMA_TARGET_GFX115X) { + // gfx115x (gfx11 kernels): calibrated on gfx1151 (Radeon 8060S, LPDDR5X) at default + // clocks over the 40 shapes with row-tiles-first; total time within 1-6% (fp16) and + // 0.4-2% (fp32) of the best swept tile per shape (the gfx1100 rules were 15-17% off at + // M <= 16 and 33% at M = 128). The 8-row half-wave tiles and 40 CUs favour fewer warps + // along N at small M than on gfx1100. + if constexpr (std::is_same_v) { + if (M <= 8) { + if (N < 2048) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); + else if (N < 3072) LAUNCH_WMMA(1, 1, 1, 4, 4, 1); + else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); + } else if (M <= 16) { + // M > 8 refitted from a pinned-clock sweep at M = 12, 24, 48 and 96: the previous + // buckets (auto-clock sweep, no data at M = 24/48) were 1.13-1.49x off the best tile. + if (K < 4608) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); + else if (K < 8192) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + else LAUNCH_WMMA(2, 1, 1, 4, 1, 2); + } else if (M <= 32) { + if (K < 3840) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); + else if (K < 17408) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); + } else if (M <= 64) { + if (N < 3840) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + else if (N < 10240) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } else { + if (N < 2048) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + else if (N < 3072) LAUNCH_WMMA(2, 2, 1, 2, 1, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } + } else if (M <= 8) { + if (N < 3072) LAUNCH_WMMA(1, 1, 1, 1, 4, 1); + else if (N < 28672) LAUNCH_WMMA(1, 1, 1, 1, 8, 2); + else LAUNCH_WMMA(1, 1, 1, 1, 2, 2); + } else if (M <= 16) { + if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 4, 1); + else if (N < 25600) LAUNCH_WMMA(2, 2, 1, 1, 4, 2); + else LAUNCH_WMMA(2, 1, 1, 2, 2, 2); + } else if (M <= 24) { + // M > 16 refitted from a pinned-clock sweep at M = 24, 48, 96, 192 and 384 (the + // auto-clock buckets were 1.10-1.12x off the best tile at M = 24-96). The bucket tops + // M = 25-32 and 49-64 keep the gfx1100 tiles, which measured 2-6% faster there. + if (K < 8192) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + else if (K < 10240) LAUNCH_WMMA(4, 1, 1, 2, 1, 2); + else LAUNCH_WMMA(1, 2, 1, 1, 8, 2); + } else if (M <= 32) { + if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); + else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } else if (M <= 48) { + if (N < 2816) LAUNCH_WMMA(2, 1, 1, 4, 2, 2); + else if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 1, 2); + else LAUNCH_WMMA(2, 1, 1, 4, 4, 2); + } else if (M <= 64) { + if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); + else if (N < 5120) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 2, 1, 4, 2, 2); + } else if (M <= 128) { + if (K < 8192) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } else if (M <= 256) { + if (5 * (int64_t)K < 6 * (int64_t)N) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } else { + if (K < 21504) LAUNCH_WMMA(4, 2, 1, 4, 1, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } + return; + } else + if constexpr (std::is_same_v) { + // fp32 (three LDS A tiles per stage), fitted separately: total time over the 40 shapes + // within 0.1-2.8% of the best swept tile per shape. + if (M <= 8) { + if (N < 3840) LAUNCH_WMMA(1, 1, 1, 1, 4, 1); + else if (N < 5120) LAUNCH_WMMA(1, 1, 1, 2, 2, 2); + else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); + } else if (M <= 16) { + if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); + else if (N < 5120) LAUNCH_WMMA(2, 1, 1, 2, 2, 1); + else if (N < 15360) LAUNCH_WMMA(2, 1, 1, 4, 1, 2); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } else if (M <= 24) { + if (N < 3072) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); + else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); + } else if (M <= 48) { + if (N < 2560) LAUNCH_WMMA(1, 2, 1, 2, 2, 2); + else if (N < 5376) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } else { + LAUNCH_WMMA(4, 1, 1, 4, 1, 1); + } + return; + } else + if (M <= 8) { + // Leaves on the aspect ratio K/N: very wide layers (K/N < 2/7) use two warps along N, + // very tall ones (K >= 5N) a shorter split-K with 128-K iterations. + if (7 * (int64_t)K < 2 * (int64_t)N) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); + else if (K >= 5 * N) LAUNCH_WMMA(1, 1, 1, 2, 4, 2); + else LAUNCH_WMMA(1, 1, 1, 1, 8, 1); + } else if (M <= 16) { + if (N < 5120) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); + else LAUNCH_WMMA(2, 2, 1, 2, 4, 2); + } else if (M <= 24) { + if (N < 3072) LAUNCH_WMMA(1, 2, 1, 1, 8, 1); + else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } else if (M <= 32) { + if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); + else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); + else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + } else if (M <= 48) { + if (N < 3840) LAUNCH_WMMA(2, 1, 1, 2, 4, 1); + else if (N < 8192) LAUNCH_WMMA(2, 2, 1, 2, 2, 2); + else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); + } else if (M <= 64) { + if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); + else if (N < 10240) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); + } else if (M <= 96) { + if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); + else if (N < 8192) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); + else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); + } else { + if (N < 2816) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); + else if (N < 3072) LAUNCH_WMMA(4, 2, 1, 4, 2, 1); + else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); + } +#undef LAUNCH_WMMA + // clang-format on +} + +} // namespace + +int gemm_4bit_wmma_arch() { return wmma_device_arch(); } + +/// @brief Host launcher for the RDNA3/RDNA4 WMMA 4-bit GEMM kernel. +/// @return false (nothing launched) if `arch` is not a WMMA generation this build has kernels for. +/// @tparam T Input/output dtype (`bnb_bfloat16`, `half` or `float`) +template +bool launch_gemm_4bit_wmma( + // clang-format off + int arch, // gemm_4bit_wmma_arch() of the current device + const T* A, // inputs [M, K] + const uint8_t* B, // packed 4-bit weights [N, K/2] + const float* absmax, // fp32 absmax [N*K/blocksize] or [ceil(N*K/(blocksize*256))] when nested + const uint8_t* absmax_8bit, // [N*K/blocksize] uint8 compressed absmax; nullptr = non-nested + const float* absmax_code, // [256] codebook for 8bit absmax + const float* absmax_offset, // scalar; nullptr = non-nested + T* C, // output [M, N] + const T* bias, // [N] optional, nullptr = no bias + int M, int N, int K, // problem shape + int blocksize, // elements per quantization block + int quant_type, // 1 = FP4, 2 = NF4 + bnb_stream_t stream // HIP stream + // clang-format on +) { +#if BNB_WMMA_EMIT_12 + if (arch == 12) { + launch_gemm_4bit_wmma_arch<12, T>( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); + return true; + } +#endif +#if BNB_WMMA_EMIT_11 + if (arch == 11) { + launch_gemm_4bit_wmma_arch<11, T>( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); + return true; + } + if (arch == WMMA_TARGET_GFX1103) { + launch_gemm_4bit_wmma_arch( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); + return true; + } + if (arch == WMMA_TARGET_GFX115X) { + launch_gemm_4bit_wmma_arch( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); + return true; + } +#endif + return false; +} + +template bool launch_gemm_4bit_wmma( + int, const bnb_bfloat16*, const uint8_t*, const float*, const uint8_t*, const float*, const float*, bnb_bfloat16*, + const bnb_bfloat16*, int, int, int, int, int, bnb_stream_t +); +template bool launch_gemm_4bit_wmma( + int, const half*, const uint8_t*, const float*, const uint8_t*, const float*, const float*, half*, const half*, int, + int, int, int, int, bnb_stream_t +); +template bool launch_gemm_4bit_wmma( + int, const float*, const uint8_t*, const float*, const uint8_t*, const float*, const float*, float*, const float*, + int, int, int, int, int, bnb_stream_t +); diff --git a/csrc/gemm_4bit_wmma.cuh b/csrc/gemm_4bit_wmma.cuh new file mode 100644 index 000000000..64eba430a --- /dev/null +++ b/csrc/gemm_4bit_wmma.cuh @@ -0,0 +1,21 @@ +#pragma once +// Launcher declarations for the AMD WMMA 4-bit GEMM kernel. +// T must be bnb_bfloat16, half or float (fp32 is emulated with split bf16 operands). Compiled on ROCm only; the kernel +// body is only emitted for RDNA3 (gfx110x) and RDNA4 (gfx120x) targets. Callers pass gemm_4bit_wmma_arch() and must +// check K % 64 == 0 and blocksize >= 32. absmax_8bit == nullptr selects the non-nested (standard) path. + +#include + +#include "compat.cuh" // CUDA/HIP runtime headers + bnb_stream_t + +// WMMA generation of the current device: 11 (RDNA3: gfx1100-gfx1103), 12 (RDNA4: gfx1201), or 0 if the kernel is not +// enabled for it. +int gemm_4bit_wmma_arch(); + +// Returns false (nothing launched) if `arch` is not a generation this build has WMMA kernels for. +template +bool launch_gemm_4bit_wmma( + int arch, const T* A, const uint8_t* B, const float* absmax, const uint8_t* absmax_8bit, const float* absmax_code, + const float* absmax_offset, T* C, const T* bias, int M, int N, int K, int blocksize, int quant_type, + bnb_stream_t stream +); diff --git a/tests/test_functional.py b/tests/test_functional.py index e4cd6a128..3b2e9e489 100644 --- a/tests/test_functional.py +++ b/tests/test_functional.py @@ -33,6 +33,12 @@ (40, 36864, 128), # 64x128-64 wide-N (48, 8192, 512), # 64x64-64 on GDDR+A100, K=512 (48, 8192, 8192), # 64x64-128, large K + (2, 1000, 256), # RDNA3/RDNA4 WMMA: smallest M, N tail + (24, 6000, 704), # RDNA3/RDNA4 WMMA: 64-K iterations (K % 128 != 0), wide N + (200, 2000, 512), # RDNA3/RDNA4 WMMA: M > 128 tile with split-K + (5, 8192, 256), # RDNA4 WMMA: fp32 starts at M=5 on wide N + (16, 6144, 512), # RDNA4 WMMA: M <= 16 tile for N >= 6144 (128-K iterations) + (17, 4096, 704), # RDNA4 WMMA: one row past a 16-row tile, K % 128 != 0 ] @@ -1012,6 +1018,32 @@ def test_matmul_4bit(self, MNK, dtype, blocksize, quant_type, compress_statistic threshold = 0.16 assert mean_err < threshold + @pytest.mark.parametrize("device", get_available_devices()) + @pytest.mark.parametrize("compress_statistics", TRUE_FALSE, ids=id_formatter("compress_statistics")) + @pytest.mark.parametrize("quant_type", ["nf4", "fp4"]) + @pytest.mark.parametrize("blocksize", [32, 64], ids=id_formatter("blocksize")) + @pytest.mark.parametrize("N", [1000, 8192], ids=id_formatter("N")) + @pytest.mark.parametrize("M", [1, 4, 5, 8, 16, 17, 40, 100], ids=id_formatter("M")) + def test_matmul_4bit_fp32_precision(self, M, N, blocksize, quant_type, compress_statistics, device): + # fp32 must keep fp32-level accuracy on every kernel path (the RDNA3/RDNA4 WMMA paths + # emulate it with split bf16 operands). Compare against a float64 product of the + # same dequantized weights. N=8192 reaches RDNA4's fp32 WMMA tiles at small M, which + # narrow weights (N=1000) leave to SIMT up to M=31. + if device not in ("cuda",): + pytest.skip("fp32 precision bound is calibrated for the CUDA/ROCm kernels") + K = 1024 + A = torch.randn(1, M, K, dtype=torch.float32, device=device) + B = torch.randn(N, K, dtype=torch.float32, device=device) / (K**0.5) + qB, qs = F.quantize_4bit( + B, blocksize=blocksize, quant_type=quant_type, compress_statistics=compress_statistics + ) + ref = A.double() @ F.dequantize_4bit(qB, qs).double().t() + out = bnb.matmul_4bit(A, qB, qs) + # fp32 kernels and the fp32 dequant+F.linear fallback stay below ~6e-7; a + # reduced-precision (e.g. bf16 or two-part bf16) path would be at >=8e-6. + rel = ((out.double() - ref).abs().mean() / ref.abs().mean()).item() + assert rel < 2e-6 + @pytest.mark.parametrize("device", get_available_devices()) def test_matmul_4bit_weight_orientation(self, device): N, K = 256, 128 From f926c1fd74284db8e254d24141bb3996e420ef2c Mon Sep 17 00:00:00 2001 From: sstamenk Date: Mon, 16 Nov 2026 18:02:40 +0100 Subject: [PATCH 02/10] [ROCm] WMMA 4-bit GEMM: move the tuning rules into gemm_4bit_wmma_rules.cuh The tile selection was ~180 lines of nested if/else per target and dtype in launch_gemm_4bit_wmma_arch, with conditions written several ways, and the SIMT vs WMMA cutoffs were inline in gemm_4bit(). Both are now data in csrc/gemm_4bit_wmma_rules.cuh, next to the tuning-target constants: - wmma_preferred(target, fp32, M, N): SIMT or WMMA (bf16/fp16 rule plus the per-target fp32 cutoff tables). - Tile rule tables per target and dtype: a list of M buckets, each with up to three leaves (N < x, K < x or K/N < a/b) and a default tile, in the shape the tile sweeps are fitted in. wmma_pick() does the lookup; the launcher collects each table's distinct tiles at compile time and dispatches to their instantiations, so exactly the same kernels are built as before. No behaviour change. Host programs comparing the previous code with the new lookups agree on all 14.0e9 (target, dtype, M, N, K) tile choices (M = 1-1024, N and K in multiples of 64 up to 65536 plus every threshold +-1) and all 21.2e6 (target, dtype, M, N) SIMT/WMMA choices (N in multiples of 32 plus every cutoff +-1); the build contains the same 470 WMMA kernel symbols. Co-Authored-By: Claude Opus 5.5 --- csrc/gemm_4bit.cu | 53 +----- csrc/gemm_4bit_wmma.cu | 307 ++++++++++------------------------ csrc/gemm_4bit_wmma.cuh | 11 +- csrc/gemm_4bit_wmma_rules.cuh | 191 +++++++++++++++++++++ 4 files changed, 290 insertions(+), 272 deletions(-) create mode 100644 csrc/gemm_4bit_wmma_rules.cuh diff --git a/csrc/gemm_4bit.cu b/csrc/gemm_4bit.cu index edb1fdc17..49c928c3f 100644 --- a/csrc/gemm_4bit.cu +++ b/csrc/gemm_4bit.cu @@ -2,7 +2,6 @@ // Dispatches to SIMT, MMA (CUDA) or WMMA (ROCm RDNA3/RDNA4) kernels based on GPU architecture and shape. // Computes out[M, N] = A[M, K] @ B[N, K]^T. All pointers are device memory. -#include #include #include @@ -10,6 +9,7 @@ #include "gemm_4bit_simt.cuh" #if BNB_HIP #include "gemm_4bit_wmma.cuh" +#include "gemm_4bit_wmma_rules.cuh" #endif #if defined(BNB_HAS_GEMM4BIT_SM75) || defined(BNB_HAS_GEMM4BIT_SM80) // Included only when an MMA-capable arch (sm75/sm80+) is in the build. @@ -67,55 +67,10 @@ static void gemm_4bit( constexpr bool is_fp32 = std::is_same_v; #if BNB_HIP - // WMMA needs K % 64 == 0 and at least 32-element quantization blocks. - // RDNA3 (gfx110x) and RDNA3.5 (gfx115x, gfx11 kernels): on the 40 calibrated LLM shapes - // WMMA beats SIMT for bf16/fp16 at every M (gfx1100: at M=1 by ~8% in total time, mostly - // on the larger weights). - // RDNA4 (gfx1201): each WMMA covers 16 rows (gfx11: 8), so SIMT keeps the smallest M. - // On gfx1201 WMMA is 7-10% faster than SIMT in total time over the 40 shapes from M=2 - // for bf16/fp16 (2-3% slower at M=1). - // fp32 (six split-bf16 WMMAs per tile) picks by M and N, see below. - constexpr int GFX12_MIN_M_16BIT = 2; + // WMMA needs K % 64 == 0 and at least 32-element quantization blocks; wmma_preferred() + // (gemm_4bit_wmma_rules.cuh) picks WMMA or SIMT by target, dtype, M and N. const int wmma_arch = K % 64 == 0 && blocksize >= 32 ? gemm_4bit_wmma_arch() : 0; - bool use_wmma = - (wmma_arch == 11 || wmma_arch == 113 || wmma_arch == 115) || (wmma_arch == 12 && M >= GFX12_MIN_M_16BIT); - if (wmma_arch != 0 && is_fp32) { - // fp32: with few output columns the split-bf16 WMMA tiles leave too few blocks to - // stream the weights, so SIMT stays faster up to a few rows (gfx12's 16-row tiles: a - // few dozen). The first row with M <= max_m decides: WMMA iff N >= min_n; past the - // last row WMMA always. Fitted per target from SIMT and WMMA timings at every M up - // to 32: - // - gfx1100 (W7900, pinned clocks): within 2.6% of the per-shape faster kernel in total - // time at M = 4-5 and within 1.7% from M = 6 (SIMT through M = 5 was 1.10x slower at - // M = 5); WMMA at M = 4 lost to SIMT on tall-K shapes by up to 1.34x. - // - gfx1201 (R9700, pinned clocks): within 0.8% in total at M = 5-32; single shapes up - // to 1.14x slower near the N cutoffs (WMMA alone was up to 1.6x slower at M = 6). - struct Cutoff { - int max_m, min_n; - }; - - // Narrow weights stay on SIMT longer (dense M scan, pinned clocks): with N <= 1024 the - // split-bf16 WMMA tiles leave too few blocks, up to 2.4x slower than SIMT at M = 52. - static constexpr Cutoff gfx11_fp32_wmma[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, - {8, 2048}, {12, 2816}, {64, 1024}}; - static constexpr Cutoff gfx115_fp32_wmma[] = {{3, INT_MAX}, {5, 2560}, {7, 1024}}; - // gfx1103 (Radeon 760M, 8 CUs, pinned clocks): SIMT through M = 2, WMMA from M = 3 (by N - // through M = 4): 1.12x faster in total at M = 3 and 1.29x at M = 4 than the gfx1100 table, - // which kept SIMT through M = 4. WMMA for wide N at M = 2 measured 2% slower. - static constexpr Cutoff gfx1103_fp32_wmma[] = {{2, INT_MAX}, {4, 3840}}; - static constexpr Cutoff gfx12_fp32_wmma[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, - {9, 2048}, {15, 1408}, {31, 1024}}; - auto pick = [&](const auto& table) { - for (const auto& row : table) - if (M <= row.max_m) - return N >= row.min_n; - return true; - }; - use_wmma = wmma_arch == 12 ? pick(gfx12_fp32_wmma) - : wmma_arch == 115 ? pick(gfx115_fp32_wmma) - : wmma_arch == 113 ? pick(gfx1103_fp32_wmma) - : pick(gfx11_fp32_wmma); - } + const bool use_wmma = wmma_arch != 0 && wmma_preferred(wmma_arch, is_fp32, M, N); if (use_wmma && launch_gemm_4bit_wmma( wmma_arch, A, B, absmax, absmax_8bit, absmax_code, absmax_offset, out, bias, M, N, K, blocksize, quant_type, stream diff --git a/csrc/gemm_4bit_wmma.cu b/csrc/gemm_4bit_wmma.cu index 4a94106bd..cc29a13ea 100644 --- a/csrc/gemm_4bit_wmma.cu +++ b/csrc/gemm_4bit_wmma.cu @@ -1,14 +1,17 @@ -// AMD WMMA 4-bit GEMM kernel for RDNA3 (gfx110x) and RDNA4 (gfx120x), wave32. +// AMD WMMA 4-bit GEMM kernel for RDNA3 (gfx110x), RDNA3.5 (gfx115x) and RDNA4 (gfx120x), wave32. // Computes C[M,N] = A[M,K] @ B[N,K]^T + bias with fused 4-bit dequantization. +#include #include #include #include #include +#include #include "common.cuh" #include "gemm_4bit_common.cuh" #include "gemm_4bit_wmma.cuh" +#include "gemm_4bit_wmma_rules.cuh" // RDNA3.5 (gfx115x) shares the gfx11 WMMA encoding and half-wave behaviour //, so it runs the gfx11 kernels. @@ -58,13 +61,8 @@ using wmma_v16s = short __attribute__((ext_vector_type(16))); // products (see wmma_16x16x16), gfx12 one full 16x16x16 product. constexpr int wmma_rows(int arch) { return arch == 12 ? 16 : 8; } -// Tuning targets returned by gemm_4bit_wmma_arch(): 11 (gfx110x), 115 (gfx115x, RDNA3.5) -// and 12 (gfx120x). gfx115x runs the gfx11 kernels with its own tile rules. -constexpr int WMMA_TARGET_GFX115X = 115; -// gfx1103 (Radeon 760M/780M iGPU): gfx110x kernels and tile rules, own fp32 dispatch (see -// csrc/gemm_4bit.cu and the Python cutover). -constexpr int WMMA_TARGET_GFX1103 = 113; - +// WMMA generation (kernel family) of a tuning target (gemm_4bit_wmma_rules.cuh): gfx115x and gfx1103 run the +// gfx11 kernels. constexpr int wmma_gen(int target) { return target == WMMA_TARGET_GFX115X || target == WMMA_TARGET_GFX1103 ? 11 : target; } @@ -750,220 +748,93 @@ void launch_wmma_tile( ); } -/// @brief Tile selection for one WMMA generation (parameters as launch_gemm_4bit_wmma). -/// -/// gfx11: calibrated on gfx1100 (W7900) at pinned clocks (perf level high) over 40 LLM -/// linear-layer shapes with row-tiles-first block order and fp16 prescaling: up to three -/// leaves on N or K/N per M bucket, fp16 total -/// time within 0.3-4.4% of the best swept tile per shape (fp32 within 1.5%). Sweeps at default (auto) clocks -/// are bimodal by ~10% and picked wrong small-M tiles. Narrow N keeps 16-column warp tiles and deeper -/// split-K so enough warps stream B; wide N uses 32-column warp tiles and 128-K -/// iterations. +/// The tile rule table (gemm_4bit_wmma_rules.cuh) of a tuning target and dtype. gfx1103 uses the gfx110x tables +/// (it differs in the SIMT/WMMA fp32 cutoffs and Python M limits only); bf16 and fp16 share a table. +template constexpr const auto& wmma_rules() { + constexpr bool fp32 = std::is_same_v; + if constexpr (wmma_gen(TARGET) == 12) { + if constexpr (fp32) + return wmma_rules_gfx12_f32; + else + return wmma_rules_gfx12_f16; + } else if constexpr (TARGET == WMMA_TARGET_GFX115X) { + if constexpr (fp32) + return wmma_rules_gfx115_f32; + else + return wmma_rules_gfx115_f16; + } else { + if constexpr (fp32) + return wmma_rules_gfx11_f32; + else + return wmma_rules_gfx11_f16; + } +} + +/// The distinct tiles of a rule table in first-use order (at most four per bucket). +template struct WmmaTileList { + WmmaTile tiles[R * 4] = {}; + int n = 0; +}; + +template constexpr WmmaTileList wmma_distinct_tiles(const WmmaRule (&rules)[R]) { + WmmaTileList list; + auto add = [&](const WmmaTile& t) { + for (int i = 0; i < list.n; i++) + if (list.tiles[i] == t) + return; + list.tiles[list.n++] = t; + }; + for (const WmmaRule& rule : rules) { + for (const WmmaLeaf& leaf : rule.leaves) + if (leaf.on != WmmaOn::NONE) + add(leaf.tile); + add(rule.otherwise); + } + return list; +} + +/// The distinct tiles of RULES as a compile-time array: the launcher instantiates exactly these. +template +inline constexpr auto wmma_tiles_of = [] { + constexpr auto list = wmma_distinct_tiles(RULES); + std::array tiles{}; + for (int i = 0; i < list.n; i++) + tiles[i] = list.tiles[i]; + return tiles; +}(); + +/// Launch `tile`, which must be one of TILES, through its compile-time instantiation. +template +void launch_wmma_tile_of( + const WmmaTile& tile, std::index_sequence, const T* A, const uint8_t* B, const float* absmax, + const uint8_t* absmax_8bit, const float* absmax_code, const float* absmax_offset, T* C, const T* bias, int M, int N, + int K, int blocksize, int quant_type, bool row_tiles_first, bnb_stream_t stream +) { + (void)((tile == TILES[I] && + (launch_wmma_tile< + ARCH, T, TILES[I].wm, TILES[I].wn, TILES[I].warps_m, TILES[I].warps_n, TILES[I].ksplit, TILES[I].kch>( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, + row_tiles_first, stream + ), + true)) || + ...); +} + +/// @brief Pick the tile for (M, N, K) from the target's rule table and launch it (parameters as +/// launch_gemm_4bit_wmma). template void launch_gemm_4bit_wmma_arch( - // clang-format off - const T* A, // inputs [M, K] - const uint8_t* B, // packed 4-bit weights [N, K/2] - const float* absmax, // fp32 absmax [N*K/blocksize] or [ceil(N*K/(blocksize*256))] when nested - const uint8_t* absmax_8bit, // [N*K/blocksize] uint8 compressed absmax; nullptr = non-nested - const float* absmax_code, // [256] codebook for 8bit absmax - const float* absmax_offset, // scalar; nullptr = non-nested - T* C, // output [M, N] - const T* bias, // [N] optional, nullptr = no bias - int M, int N, int K, // problem shape - int blocksize, // elements per quantization block - int quant_type, // 1 = FP4, 2 = NF4 - bnb_stream_t stream // HIP stream - // clang-format on + const T* A, const uint8_t* B, const float* absmax, const uint8_t* absmax_8bit, const float* absmax_code, + const float* absmax_offset, T* C, const T* bias, int M, int N, int K, int blocksize, int quant_type, + bnb_stream_t stream ) { - constexpr int ARCH = wmma_gen(TARGET); + constexpr const auto& RULES = wmma_rules(); + constexpr const auto& TILES = wmma_tiles_of; const bool row_tiles_first = wmma_row_tiles_first(TARGET, std::is_same_v); - // clang-format off -#define LAUNCH_WMMA(WM, WN, WARPS_M, WARPS_N, KSPLIT, KCH_MAX) \ - launch_wmma_tile( \ - A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, \ - row_tiles_first, stream) - - if constexpr (ARCH == 12) { - // gfx12 (16-row WMMA): calibrated on gfx1201 (R9700) at pinned clocks over the same - // 40 shapes, within ~2-6% (bf16/fp16) and ~0-2% (fp32) geomean of the best swept tile. - // One 16-row tile covers M <= 16, where the kernel is bandwidth-bound; larger M adds - // warps along N and rows per warp rather than warps along M. - if constexpr (std::is_same_v) { - // Refitted at pinned clocks on the one-fragment fp32 kernel: total time within - // 0.0-1.4% of the best swept tile per shape. - if (M <= 16) { - if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 2, 1); - else if (N < 4608) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); - else LAUNCH_WMMA(1, 2, 1, 2, 2, 1); - } else if (M <= 48) { - if (N < 8192) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); - } else if (M <= 96) { - if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 1, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); - } else if (M <= 192) { - if (N < 2048) LAUNCH_WMMA(2, 1, 1, 4, 1, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 1); - } else { - LAUNCH_WMMA(2, 2, 1, 4, 1, 1); - } - } else if (M <= 16) { - // fp16/bf16 refitted at pinned clocks (perf level high) on R9700: total time within - // 0.1-3.6% of the best swept tile per shape (the auto-clock rules were 9% off at - // M <= 16 and 12.5% at M = 256). - if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); - else LAUNCH_WMMA(1, 2, 1, 2, 4, 2); - } else if (M <= 32) { - if (N < 2048) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); - else if (N < 8192) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 2, 2); - } else if (M <= 96) { - if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 2, 2); - } else if (M <= 128) { - if (N < 3072) LAUNCH_WMMA(2, 1, 1, 4, 4, 1); - else if (N < 8192) LAUNCH_WMMA(2, 2, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 2, 1, 4, 1, 1); - } else if (M <= 160) { - if (N < 3072) LAUNCH_WMMA(2, 1, 1, 4, 2, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } else { - if (N < 2816) LAUNCH_WMMA(2, 2, 1, 4, 2, 2); - else if (N < 3840) LAUNCH_WMMA(4, 1, 1, 4, 1, 1); - else LAUNCH_WMMA(4, 2, 1, 4, 1, 1); - } - return; - } else - if constexpr (TARGET == WMMA_TARGET_GFX115X) { - // gfx115x (gfx11 kernels): calibrated on gfx1151 (Radeon 8060S, LPDDR5X) at default - // clocks over the 40 shapes with row-tiles-first; total time within 1-6% (fp16) and - // 0.4-2% (fp32) of the best swept tile per shape (the gfx1100 rules were 15-17% off at - // M <= 16 and 33% at M = 128). The 8-row half-wave tiles and 40 CUs favour fewer warps - // along N at small M than on gfx1100. - if constexpr (std::is_same_v) { - if (M <= 8) { - if (N < 2048) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); - else if (N < 3072) LAUNCH_WMMA(1, 1, 1, 4, 4, 1); - else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); - } else if (M <= 16) { - // M > 8 refitted from a pinned-clock sweep at M = 12, 24, 48 and 96: the previous - // buckets (auto-clock sweep, no data at M = 24/48) were 1.13-1.49x off the best tile. - if (K < 4608) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); - else if (K < 8192) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - else LAUNCH_WMMA(2, 1, 1, 4, 1, 2); - } else if (M <= 32) { - if (K < 3840) LAUNCH_WMMA(1, 1, 1, 4, 2, 1); - else if (K < 17408) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); - } else if (M <= 64) { - if (N < 3840) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - else if (N < 10240) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } else { - if (N < 2048) LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - else if (N < 3072) LAUNCH_WMMA(2, 2, 1, 2, 1, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } - } else if (M <= 8) { - if (N < 3072) LAUNCH_WMMA(1, 1, 1, 1, 4, 1); - else if (N < 28672) LAUNCH_WMMA(1, 1, 1, 1, 8, 2); - else LAUNCH_WMMA(1, 1, 1, 1, 2, 2); - } else if (M <= 16) { - if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 4, 1); - else if (N < 25600) LAUNCH_WMMA(2, 2, 1, 1, 4, 2); - else LAUNCH_WMMA(2, 1, 1, 2, 2, 2); - } else if (M <= 24) { - // M > 16 refitted from a pinned-clock sweep at M = 24, 48, 96, 192 and 384 (the - // auto-clock buckets were 1.10-1.12x off the best tile at M = 24-96). The bucket tops - // M = 25-32 and 49-64 keep the gfx1100 tiles, which measured 2-6% faster there. - if (K < 8192) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - else if (K < 10240) LAUNCH_WMMA(4, 1, 1, 2, 1, 2); - else LAUNCH_WMMA(1, 2, 1, 1, 8, 2); - } else if (M <= 32) { - if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); - else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } else if (M <= 48) { - if (N < 2816) LAUNCH_WMMA(2, 1, 1, 4, 2, 2); - else if (N < 3840) LAUNCH_WMMA(2, 1, 1, 4, 1, 2); - else LAUNCH_WMMA(2, 1, 1, 4, 4, 2); - } else if (M <= 64) { - if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); - else if (N < 5120) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 2, 1, 4, 2, 2); - } else if (M <= 128) { - if (K < 8192) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } else if (M <= 256) { - if (5 * (int64_t)K < 6 * (int64_t)N) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } else { - if (K < 21504) LAUNCH_WMMA(4, 2, 1, 4, 1, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } - return; - } else - if constexpr (std::is_same_v) { - // fp32 (three LDS A tiles per stage), fitted separately: total time over the 40 shapes - // within 0.1-2.8% of the best swept tile per shape. - if (M <= 8) { - if (N < 3840) LAUNCH_WMMA(1, 1, 1, 1, 4, 1); - else if (N < 5120) LAUNCH_WMMA(1, 1, 1, 2, 2, 2); - else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); - } else if (M <= 16) { - if (N < 3840) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); - else if (N < 5120) LAUNCH_WMMA(2, 1, 1, 2, 2, 1); - else if (N < 15360) LAUNCH_WMMA(2, 1, 1, 4, 1, 2); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } else if (M <= 24) { - if (N < 3072) LAUNCH_WMMA(1, 1, 1, 2, 4, 1); - else LAUNCH_WMMA(1, 2, 1, 2, 2, 2); - } else if (M <= 48) { - if (N < 2560) LAUNCH_WMMA(1, 2, 1, 2, 2, 2); - else if (N < 5376) LAUNCH_WMMA(2, 2, 1, 2, 2, 1); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } else { - LAUNCH_WMMA(4, 1, 1, 4, 1, 1); - } - return; - } else - if (M <= 8) { - // Leaves on the aspect ratio K/N: very wide layers (K/N < 2/7) use two warps along N, - // very tall ones (K >= 5N) a shorter split-K with 128-K iterations. - if (7 * (int64_t)K < 2 * (int64_t)N) LAUNCH_WMMA(1, 1, 1, 2, 8, 1); - else if (K >= 5 * N) LAUNCH_WMMA(1, 1, 1, 2, 4, 2); - else LAUNCH_WMMA(1, 1, 1, 1, 8, 1); - } else if (M <= 16) { - if (N < 5120) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); - else LAUNCH_WMMA(2, 2, 1, 2, 4, 2); - } else if (M <= 24) { - if (N < 3072) LAUNCH_WMMA(1, 2, 1, 1, 8, 1); - else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } else if (M <= 32) { - if (N < 3072) LAUNCH_WMMA(2, 1, 1, 2, 8, 1); - else if (N < 5120) LAUNCH_WMMA(2, 2, 1, 2, 4, 2); - else LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - } else if (M <= 48) { - if (N < 3840) LAUNCH_WMMA(2, 1, 1, 2, 4, 1); - else if (N < 8192) LAUNCH_WMMA(2, 2, 1, 2, 2, 2); - else LAUNCH_WMMA(2, 2, 1, 4, 1, 2); - } else if (M <= 64) { - if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); - else if (N < 10240) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); - } else if (M <= 96) { - if (N < 3072) LAUNCH_WMMA(4, 1, 1, 2, 4, 1); - else if (N < 8192) LAUNCH_WMMA(4, 2, 1, 4, 2, 2); - else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); - } else { - if (N < 2816) LAUNCH_WMMA(4, 1, 1, 4, 2, 2); - else if (N < 3072) LAUNCH_WMMA(4, 2, 1, 4, 2, 1); - else LAUNCH_WMMA(4, 2, 1, 4, 1, 2); - } -#undef LAUNCH_WMMA - // clang-format on + launch_wmma_tile_of( + wmma_pick(RULES, M, N, K), std::make_index_sequence{}, A, B, absmax, absmax_8bit, absmax_code, + absmax_offset, C, bias, M, N, K, blocksize, quant_type, row_tiles_first, stream + ); } } // namespace diff --git a/csrc/gemm_4bit_wmma.cuh b/csrc/gemm_4bit_wmma.cuh index 64eba430a..5ad08cfcc 100644 --- a/csrc/gemm_4bit_wmma.cuh +++ b/csrc/gemm_4bit_wmma.cuh @@ -1,18 +1,19 @@ #pragma once // Launcher declarations for the AMD WMMA 4-bit GEMM kernel. // T must be bnb_bfloat16, half or float (fp32 is emulated with split bf16 operands). Compiled on ROCm only; the kernel -// body is only emitted for RDNA3 (gfx110x) and RDNA4 (gfx120x) targets. Callers pass gemm_4bit_wmma_arch() and must -// check K % 64 == 0 and blocksize >= 32. absmax_8bit == nullptr selects the non-nested (standard) path. +// body is only emitted for RDNA3 (gfx110x), RDNA3.5 (gfx115x) and RDNA4 (gfx120x) targets. Callers pass +// gemm_4bit_wmma_arch() and must check K % 64 == 0 and blocksize >= 32. absmax_8bit == nullptr selects the non-nested +// (standard) path. #include #include "compat.cuh" // CUDA/HIP runtime headers + bnb_stream_t -// WMMA generation of the current device: 11 (RDNA3: gfx1100-gfx1103), 12 (RDNA4: gfx1201), or 0 if the kernel is not -// enabled for it. +// WMMA tuning target of the current device: 11 (gfx1100-gfx1102), 113 (gfx1103), 115 (gfx115x), 12 (gfx120x), or 0 +// if the kernel is not enabled for it. Tile rules per target: gemm_4bit_wmma_rules.cuh. int gemm_4bit_wmma_arch(); -// Returns false (nothing launched) if `arch` is not a generation this build has WMMA kernels for. +// Returns false (nothing launched) if `arch` is not a target this build has WMMA kernels for. template bool launch_gemm_4bit_wmma( int arch, const T* A, const uint8_t* B, const float* absmax, const uint8_t* absmax_8bit, const float* absmax_code, diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh new file mode 100644 index 000000000..0dea991fc --- /dev/null +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -0,0 +1,191 @@ +#pragma once +// AMD WMMA 4-bit GEMM tuning rules per target: SIMT or WMMA, and the WMMA tile. + +#include +#include + +// Tuning targets returned by gemm_4bit_wmma_arch(). gfx1103 and gfx115x run the gfx11 kernels; gfx1103 uses the +// gfx110x tile rules with its own fp32 SIMT/WMMA cutoffs, gfx115x has its own rules. +inline constexpr int WMMA_TARGET_GFX11 = 11; // gfx1100-gfx1102 +inline constexpr int WMMA_TARGET_GFX1103 = 113; // gfx1103 (Radeon 760M/780M iGPU) +inline constexpr int WMMA_TARGET_GFX115X = 115; // gfx1150-gfx1153 +inline constexpr int WMMA_TARGET_GFX12 = 12; // gfx1200-gfx1201 + +// --------------------------------------------------------------------------------------------------------------- +// SIMT or WMMA (csrc/gemm_4bit.cu), once Python has chosen the fused kernel over dequant+F.linear. + +/// fp32 cutoffs: the first row with M <= max_m decides, WMMA iff N >= min_n; past the last row WMMA always. +/// SIMT keeps narrow N at small M, where the split-bf16 WMMA tiles leave too few blocks. +struct WmmaFp32Cutoff { + int max_m, min_n; +}; + +// clang-format off +/// gfx11: SIMT through M = 4, then WMMA by N; N < 1024 stays on SIMT through M = 64. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx11[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, {8, 2048}, {12, 2816}, {64, 1024}}; +/// gfx1103: SIMT through M = 2, WMMA from M = 3 (N >= 3840 through M = 4). +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1103[] = {{2, INT_MAX}, {4, 3840}}; +/// gfx115x: SIMT through M = 3, then WMMA by N through M = 7. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx115[] = {{3, INT_MAX}, {5, 2560}, {7, 1024}}; +/// gfx12: SIMT through M = 4, then WMMA by N through M = 31. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx12[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, {9, 2048}, {15, 1408}, {31, 1024}}; +// clang-format on + +template constexpr bool wmma_fp32_pick(const WmmaFp32Cutoff (&cutoffs)[R], int M, int N) { + for (const WmmaFp32Cutoff& c : cutoffs) + if (M <= c.max_m) + return N >= c.min_n; + return true; +} + +/// Whether the WMMA kernel (rather than SIMT) runs on a WMMA target (target != 0). bf16/fp16: WMMA at every M +/// on the gfx11 kernels, from M = 2 on gfx12 (a gfx12 WMMA always computes 16 rows); fp32: the target's cutoffs. +constexpr bool wmma_preferred(int target, bool fp32, int M, int N) { + if (!fp32) + return target != WMMA_TARGET_GFX12 || M >= 2; + switch (target) { + case WMMA_TARGET_GFX12: + return wmma_fp32_pick(wmma_fp32_cutoffs_gfx12, M, N); + case WMMA_TARGET_GFX115X: + return wmma_fp32_pick(wmma_fp32_cutoffs_gfx115, M, N); + case WMMA_TARGET_GFX1103: + return wmma_fp32_pick(wmma_fp32_cutoffs_gfx1103, M, N); + default: + return wmma_fp32_pick(wmma_fp32_cutoffs_gfx11, M, N); + } +} + +// --------------------------------------------------------------------------------------------------------------- +// WMMA tile per problem (csrc/gemm_4bit_wmma.cu). + +/// One tile configuration: the template parameters of the gemm_4bit_wmma kernel. +struct WmmaTile { + int wm, wn; // WMMA tiles per warp along M and N (8x16 on gfx11, 16x16 on gfx12) + int warps_m, warps_n; // warps per block along M and N + int ksplit; // warp groups splitting K, reduced through LDS + int kch; // 64-K units per main-loop iteration (lowered to 1 when K % 128 != 0) +}; + +constexpr bool operator==(const WmmaTile& a, const WmmaTile& b) { + return a.wm == b.wm && a.wn == b.wn && a.warps_m == b.warps_m && a.warps_n == b.warps_n && a.ksplit == b.ksplit && + a.kch == b.kch; +} + +/// Leaf condition: N < lt, K < lt, or K / N < lt / den. +enum class WmmaOn : uint8_t { NONE, N, K, K_OVER_N }; + +struct WmmaLeaf { + WmmaOn on; + int lt; + int den; + WmmaTile tile; +}; + +constexpr WmmaLeaf n_lt(int n, WmmaTile tile) { return {WmmaOn::N, n, 1, tile}; } + +constexpr WmmaLeaf k_lt(int k, WmmaTile tile) { return {WmmaOn::K, k, 1, tile}; } + +constexpr WmmaLeaf k_over_n_lt(int num, int den, WmmaTile tile) { return {WmmaOn::K_OVER_N, num, den, tile}; } + +/// One M bucket, used when M <= max_m: the first matching leaf picks the tile, else `otherwise`. A table's +/// last bucket has max_m = INT_MAX. +struct WmmaRule { + int max_m; + WmmaLeaf leaves[3]; + WmmaTile otherwise; +}; + +constexpr bool wmma_leaf_matches(const WmmaLeaf& leaf, int N, int K) { + switch (leaf.on) { + case WmmaOn::N: + return N < leaf.lt; + case WmmaOn::K: + return K < leaf.lt; + case WmmaOn::K_OVER_N: + return (int64_t)K * leaf.den < (int64_t)leaf.lt * N; + default: + return false; + } +} + +/// The tile a rule table picks for (M, N, K). +template constexpr WmmaTile wmma_pick(const WmmaRule (&rules)[R], int M, int N, int K) { + for (const WmmaRule& rule : rules) { + if (M > rule.max_m) + continue; + for (const WmmaLeaf& leaf : rule.leaves) + if (wmma_leaf_matches(leaf, N, K)) + return leaf.tile; + return rule.otherwise; + } + return rules[R - 1].otherwise; +} + +// clang-format off + +/// gfx11 bf16/fp16. Narrow N keeps 16-column warp tiles and deeper split-K so enough warps stream B; wide N +/// uses 32-column warp tiles and 128-K iterations. At M <= 8, very wide layers (K/N < 2/7) use two warps along +/// N and very tall ones (K >= 5N) a shorter split-K with 128-K iterations. +inline constexpr WmmaRule wmma_rules_gfx11_f16[] = { + {8, {k_over_n_lt(2, 7, {1, 1, 1, 2, 8, 1}), k_over_n_lt(5, 1, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 2, 4, 2}}, + {16, {n_lt(5120, {2, 1, 1, 2, 8, 1})}, {2, 2, 1, 2, 4, 2}}, + {24, {n_lt(3072, {1, 2, 1, 1, 8, 1}), n_lt(5120, {2, 2, 1, 2, 4, 2})}, {4, 1, 1, 4, 2, 2}}, + {32, {n_lt(3072, {2, 1, 1, 2, 8, 1}), n_lt(5120, {2, 2, 1, 2, 4, 2})}, {4, 1, 1, 4, 2, 2}}, + {48, {n_lt(3840, {2, 1, 1, 2, 4, 1}), n_lt(8192, {2, 2, 1, 2, 2, 2})}, {2, 2, 1, 4, 1, 2}}, + {64, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(10240, {4, 1, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 2}}, + {96, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(8192, {4, 2, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {4, 1, 1, 4, 2, 2}), n_lt(3072, {4, 2, 1, 4, 2, 1})}, {4, 2, 1, 4, 1, 2}}, +}; + +/// gfx11 fp32 (three LDS A tiles per stage). +inline constexpr WmmaRule wmma_rules_gfx11_f32[] = { + {8, {n_lt(3840, {1, 1, 1, 1, 4, 1}), n_lt(5120, {1, 1, 1, 2, 2, 2})}, {1, 2, 1, 2, 2, 2}}, + {16, {n_lt(3840, {1, 1, 1, 2, 4, 1}), n_lt(5120, {2, 1, 1, 2, 2, 1}), n_lt(15360, {2, 1, 1, 4, 1, 2})}, {2, 2, 1, 4, 1, 2}}, + {24, {n_lt(3072, {1, 1, 1, 2, 4, 1})}, {1, 2, 1, 2, 2, 2}}, + {48, {n_lt(2560, {1, 2, 1, 2, 2, 2}), n_lt(5376, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, +}; + +/// gfx115x bf16/fp16: fewer warps along N at small M than gfx1100. +inline constexpr WmmaRule wmma_rules_gfx115_f16[] = { + {8, {n_lt(3072, {1, 1, 1, 1, 4, 1}), n_lt(28672, {1, 1, 1, 1, 8, 2})}, {1, 1, 1, 1, 2, 2}}, + {16, {n_lt(3072, {2, 1, 1, 2, 4, 1}), n_lt(25600, {2, 2, 1, 1, 4, 2})}, {2, 1, 1, 2, 2, 2}}, + {24, {k_lt(8192, {4, 1, 1, 4, 2, 2}), k_lt(10240, {4, 1, 1, 2, 1, 2})}, {1, 2, 1, 1, 8, 2}}, + {32, {n_lt(3072, {2, 1, 1, 2, 8, 1}), n_lt(5120, {2, 2, 1, 2, 4, 2})}, {4, 1, 1, 4, 2, 2}}, + {48, {n_lt(2816, {2, 1, 1, 4, 2, 2}), n_lt(3840, {2, 1, 1, 4, 1, 2})}, {2, 1, 1, 4, 4, 2}}, + {64, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(5120, {4, 1, 1, 4, 2, 2})}, {4, 2, 1, 4, 2, 2}}, + {128, {k_lt(8192, {4, 2, 1, 4, 2, 2})}, {4, 1, 1, 4, 2, 2}}, + {256, {k_over_n_lt(6, 5, {4, 2, 1, 4, 2, 2})}, {4, 1, 1, 4, 2, 2}}, + {INT_MAX, {k_lt(21504, {4, 2, 1, 4, 1, 2})}, {4, 1, 1, 4, 2, 2}}, +}; + +/// gfx115x fp32. +inline constexpr WmmaRule wmma_rules_gfx115_f32[] = { + {8, {n_lt(2048, {1, 1, 1, 2, 4, 1}), n_lt(3072, {1, 1, 1, 4, 4, 1})}, {1, 2, 1, 2, 2, 2}}, + {16, {k_lt(4608, {2, 2, 1, 2, 2, 1}), k_lt(8192, {2, 2, 1, 4, 1, 2})}, {2, 1, 1, 4, 1, 2}}, + {32, {k_lt(3840, {1, 1, 1, 4, 2, 1}), k_lt(17408, {2, 2, 1, 4, 1, 2})}, {1, 2, 1, 2, 2, 2}}, + {64, {n_lt(3840, {2, 2, 1, 4, 1, 2}), n_lt(10240, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2048, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, +}; + +/// gfx12 bf16/fp16. One 16-row tile covers M <= 16; larger M adds warps along N and rows per warp rather than +/// warps along M. +inline constexpr WmmaRule wmma_rules_gfx12_f16[] = { + {16, {n_lt(3840, {1, 1, 1, 2, 8, 1})}, {1, 2, 1, 2, 4, 2}}, + {32, {n_lt(2048, {1, 1, 1, 2, 8, 1}), n_lt(8192, {2, 1, 1, 4, 4, 1})}, {2, 2, 1, 4, 2, 2}}, + {96, {n_lt(3840, {2, 1, 1, 4, 4, 1})}, {2, 2, 1, 4, 2, 2}}, + {128, {n_lt(3072, {2, 1, 1, 4, 4, 1}), n_lt(8192, {2, 2, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 1}}, + {160, {n_lt(3072, {2, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {2, 2, 1, 4, 2, 2}), n_lt(3840, {4, 1, 1, 4, 1, 1})}, {4, 2, 1, 4, 1, 1}}, +}; + +/// gfx12 fp32 (one-fragment split-bf16 kernel). +inline constexpr WmmaRule wmma_rules_gfx12_f32[] = { + {16, {n_lt(3840, {1, 1, 1, 2, 2, 1}), n_lt(4608, {1, 1, 1, 4, 2, 1})}, {1, 2, 1, 2, 2, 1}}, + {48, {n_lt(8192, {1, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 1}}, + {96, {n_lt(3840, {2, 1, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 1}}, + {192, {n_lt(2048, {2, 1, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 1}}, + {INT_MAX, {}, {2, 2, 1, 4, 1, 1}}, +}; + +// clang-format on From ae61bdb5f608de119feb7b20884c26a7c339ed5a Mon Sep 17 00:00:00 2001 From: sstamenk Date: Mon, 16 Nov 2026 20:21:46 +0100 Subject: [PATCH 03/10] [ROCm] WMMA 4-bit GEMM: fix Inf in fp32 inputs, build for generic targets, review fixes - fp32: an Inf activation became NaN. split_bf16 kept Inf/NaN in the leading part, which is also multiplied by B's lower parts, and those are zero for every centroid exact in bf16 (Inf * 0). Non-finite values now go to the last part, which only meets B's leading part, so Inf/NaN propagate as in fp32 math. Finite results are unchanged. New test: test_matmul_4bit_fp32_special_values (fails on the WMMA path before this change). - Builds for gfx11-generic / gfx12-generic emitted no WMMA kernel bodies but the dispatch still selected WMMA by device name, so the first launch aborted on the missing symbol. The device pass now treats __gfx11_generic__ / __gfx12_generic__ like their family (one BNB_WMMA_DEVICE_ARCH instead of BNB_WMMA_RDNA3/4, which also drops most new -Wexpansion-to-defined warnings). - Document the input ranges of the WMMA path: absmax is applied to the fp32 sum of A x centroid over a quantization group, so |A| must stay below ~FLT_MAX / blocksize (fp32/bf16 inputs only); the three-part split-bf16 keeps fp32 accuracy for |A| >= ~1e-33. - Python: check K % 64 once; note that the M limits were calibrated with blocksize 64 and weights streamed from DRAM. - Named tuning targets instead of literal 11/12; fix stale test comments (the fp32 precision bound and its metric, the gfx12 wide-N tile). Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 21 ++++----- csrc/gemm_4bit_wmma.cu | 76 +++++++++++++++---------------- tests/test_functional.py | 29 ++++++++++-- 3 files changed, 71 insertions(+), 55 deletions(-) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 122b1cef3..0391d3ff8 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -833,14 +833,15 @@ def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): return True arch = _rocm_gfx_arch(device_index) - if arch == "gfx1103" and K % 64 == 0: # RDNA3 iGPU WMMA - return M <= 384 - if arch.startswith("gfx110") and K % 64 == 0: # RDNA3 WMMA - return M <= (128 if dtype == torch.float32 else 384) - if arch.startswith("gfx115") and K % 64 == 0: # RDNA3.5 WMMA (gfx1151 values) - return M <= 512 - if arch.startswith("gfx120") and K % 64 == 0: # RDNA4 WMMA (gfx1201 values) - return M <= (512 if dtype == torch.float32 else 384) + if K % 64 == 0: # WMMA kernel + if arch == "gfx1103": # RDNA3 iGPU + return M <= 384 + if arch.startswith("gfx110"): # RDNA3 + return M <= (128 if dtype == torch.float32 else 384) + if arch.startswith("gfx115"): # RDNA3.5 (gfx1151 values) + return M <= 512 + if arch.startswith("gfx120"): # RDNA4 (gfx1201 values) + return M <= (512 if dtype == torch.float32 else 384) if arch.startswith("gfx11") or arch.startswith("gfx12"): # RDNA3 / RDNA4 / CDNA5 (gfx125x) return M <= 8 if arch.startswith("gfx9"): # CDNA1-4 / MI-series (Wave64) @@ -938,9 +939,7 @@ def _dequant_linear_fallback( _gemm_4bit_custom_max_m = 1536 else: _gemm_4bit_use_custom_fn = _gemm_4bit_use_custom_rocm - # ROCm: the per-arch heuristic above owns RDNA/CDNA thresholds; gfx110x/gfx1201 bf16/fp16 - # keep the custom kernel through M=384, gfx1103 fp32 through M=384, gfx1151 (all dtypes) - # and gfx1201 fp32 through M=512. + # ROCm: the per-arch heuristic above owns RDNA/CDNA thresholds; this is the largest of them. _gemm_4bit_custom_max_m = 512 diff --git a/csrc/gemm_4bit_wmma.cu b/csrc/gemm_4bit_wmma.cu index cc29a13ea..394dd204f 100644 --- a/csrc/gemm_4bit_wmma.cu +++ b/csrc/gemm_4bit_wmma.cu @@ -13,17 +13,13 @@ #include "gemm_4bit_wmma.cuh" #include "gemm_4bit_wmma_rules.cuh" -// RDNA3.5 (gfx115x) shares the gfx11 WMMA encoding and half-wave behaviour -//, so it runs the gfx11 kernels. -#define BNB_WMMA_RDNA3 (IS_RDNA3 || IS_RDNA3_5) -#define BNB_WMMA_RDNA4 IS_RDNA4 - // WMMA generation the current device pass compiles kernel bodies for (0 = none, // including the host pass). Kernels are templated on the generation so the host -// can size tiles for the device it runs on. -#if BNB_WMMA_RDNA3 +// can size tiles for the device it runs on. RDNA3.5 (gfx115x) shares the gfx11 WMMA +// encoding and runs the gfx11 kernels; the generic targets cover their family's chips. +#if IS_RDNA3 || IS_RDNA3_5 || defined(__gfx11_generic__) #define BNB_WMMA_DEVICE_ARCH 11 -#elif BNB_WMMA_RDNA4 +#elif IS_RDNA4 || defined(__gfx12_generic__) #define BNB_WMMA_DEVICE_ARCH 12 #else #define BNB_WMMA_DEVICE_ARCH 0 @@ -61,11 +57,9 @@ using wmma_v16s = short __attribute__((ext_vector_type(16))); // products (see wmma_16x16x16), gfx12 one full 16x16x16 product. constexpr int wmma_rows(int arch) { return arch == 12 ? 16 : 8; } -// WMMA generation (kernel family) of a tuning target (gemm_4bit_wmma_rules.cuh): gfx115x and gfx1103 run the -// gfx11 kernels. -constexpr int wmma_gen(int target) { - return target == WMMA_TARGET_GFX115X || target == WMMA_TARGET_GFX1103 ? 11 : target; -} +// WMMA generation (kernel family) of a tuning target (gemm_4bit_wmma_rules.cuh): gfx120x runs the gfx12 +// kernels, gfx110x, gfx1103 and gfx115x the gfx11 kernels. +constexpr int wmma_gen(int target) { return target == WMMA_TARGET_GFX12 ? 12 : 11; } // Per-lane operand fragment: 16 (gfx11) or 8 (gfx12) 16-bit values. template using wmma_frag = std::conditional_t; @@ -88,7 +82,7 @@ template using wmma_frag = std::conditional_t __device__ __forceinline__ wmma_v8f wmma_16x16x16(wmma_frag a, wmma_frag b, wmma_v8f c) { if constexpr (ARCH == 11) { -#if BNB_WMMA_RDNA3 +#if BNB_WMMA_DEVICE_ARCH == 11 if constexpr (std::is_same_v) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32( __builtin_bit_cast(wmma_v16h, a), __builtin_bit_cast(wmma_v16h, b), c @@ -100,7 +94,7 @@ __device__ __forceinline__ wmma_v8f wmma_16x16x16(wmma_frag a, wmma_frag) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12( __builtin_bit_cast(wmma_v8h, a), __builtin_bit_cast(wmma_v8h, b), c @@ -120,8 +114,12 @@ constexpr int WMMA_F32_PARTS = 3; // Split an fp32 value into P bf16 parts (bit patterns in the low 16 bits) whose sum // is x to ~2^-(8P) relative: every part but the last truncates, so each remainder -// is exact in fp32; the last rounds to nearest even. Inf/NaN keep the lower parts at -// zero so they propagate through the leading part alone. +// is exact in fp32; the last rounds to nearest even. This holds for |x| >= ~1e-33 +// (2^-110): below that the lower parts and their products are fp32 denormals, which +// the WMMAs flush, so a row whose values are all that small loses accuracy. +// Inf/NaN go to the last part alone, with the others zero: the last part is only +// multiplied by the leading part of B, so no Inf * 0 products arise from B's lower +// parts (zero for every centroid exact in bf16) and Inf/NaN propagate as in fp32. template __device__ __forceinline__ void split_bf16(float x, uint32_t (&parts)[P]) { const bool finite = (__builtin_bit_cast(uint32_t, x) & 0x7f800000u) != 0x7f800000u; float r = x; @@ -135,14 +133,17 @@ template __device__ __forceinline__ void split_bf16(float x, uint32_t (& parts[P - 1] = (bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16; if (!finite) { #pragma unroll - for (int p = 1; p < P; p++) + for (int p = 0; p < P - 1; p++) parts[p] = 0u; + // Keep NaNs whose payload is only in the low 16 bits from truncating to Inf. + const uint32_t xb = __builtin_bit_cast(uint32_t, x); + parts[P - 1] = (xb >> 16) | ((xb & 0x007fffffu) ? 0x40u : 0u); } } // Add the value held by the lane 16 positions away (the other half-wave). __device__ __forceinline__ float half_wave_sum(float v) { -#if BNB_WMMA_RDNA3 +#if BNB_WMMA_DEVICE_ARCH == 11 const uint32_t other = __builtin_amdgcn_permlanex16( __builtin_bit_cast(uint32_t, v), __builtin_bit_cast(uint32_t, v), 0x76543210u, 0xfedcba98u, false, false ); @@ -509,6 +510,9 @@ __device__ __forceinline__ void gemm_4bit_wmma_body( for (int wm = 0; wm < WM; wm++) #pragma unroll for (int wn = 0; wn < WN; wn++) + // absmax scales the group's fp32 sum of A x centroid only here, so that sum + // must stay finite: |A| below ~FLT_MAX / blocksize (~5e36 at blocksize 64), + // reachable only by fp32/bf16 inputs (the SIMT bf16 path: FLT_MAX / 8). if constexpr (!PRESCALE) acc[wm][wn] += tmp[wm][wn] * scale[wn]; } @@ -622,26 +626,18 @@ __global__ void __launch_bounds__(KSPLIT* WARPS_M* WARPS_N * 32) gemm_4bit_wmma( namespace { // WMMA tuning target for a gcnArchName ("gfx1201" or "gfx1201:xnack-"): 11, 113, 115, 12, or 0. -// The chips must be ones whose device pass emits the kernel body (IS_RDNA3 / IS_RDNA4 in -// common.cuh); any other device would launch an empty kernel. Measured: gfx1100, gfx1103, -// gfx1151 and gfx1201. gfx1101/gfx1102, gfx1150/gfx1152/gfx1153 and gfx1200 share the WMMA +// The chips must be ones whose device pass emits the kernel body (BNB_WMMA_DEVICE_ARCH, +// including builds for gfx11-generic / gfx12-generic); any other device would launch an empty kernel. Measured: +// gfx1100, gfx1103, gfx1151 and gfx1201. gfx1101/gfx1102, gfx1150/gfx1152/gfx1153 and gfx1200 share the WMMA // instructions of their family and use its rules (gfx1100, gfx1151, gfx1201) unmeasured. int wmma_arch_of(const char* name) { static constexpr struct { const char* chip; int arch; - } chips[] = { - {"gfx1100", 11}, - {"gfx1101", 11}, - {"gfx1102", 11}, - {"gfx1103", WMMA_TARGET_GFX1103}, - {"gfx1150", WMMA_TARGET_GFX115X}, - {"gfx1151", WMMA_TARGET_GFX115X}, - {"gfx1152", WMMA_TARGET_GFX115X}, - {"gfx1153", WMMA_TARGET_GFX115X}, - {"gfx1200", 12}, - {"gfx1201", 12} - }; + } chips[] = {{"gfx1100", WMMA_TARGET_GFX11}, {"gfx1101", WMMA_TARGET_GFX11}, {"gfx1102", WMMA_TARGET_GFX11}, + {"gfx1103", WMMA_TARGET_GFX1103}, {"gfx1150", WMMA_TARGET_GFX115X}, {"gfx1151", WMMA_TARGET_GFX115X}, + {"gfx1152", WMMA_TARGET_GFX115X}, {"gfx1153", WMMA_TARGET_GFX115X}, {"gfx1200", WMMA_TARGET_GFX12}, + {"gfx1201", WMMA_TARGET_GFX12}}; for (const auto& c : chips) { const size_t n = std::strlen(c.chip); @@ -672,9 +668,9 @@ int wmma_device_arch() { /// (see gemm_4bit_wmma_body). Only matters with two or more row tiles. fp32 on gfx110x /// stays N-first. The tile rules are fitted with this order. bool wmma_row_tiles_first(int target, bool fp32) { - if (target == 11 || target == WMMA_TARGET_GFX1103) + if (target == WMMA_TARGET_GFX11 || target == WMMA_TARGET_GFX1103) return !fp32; - return target == 12 || target == WMMA_TARGET_GFX115X; + return target == WMMA_TARGET_GFX12 || target == WMMA_TARGET_GFX115X; } /// Launch one tile configuration. KCH_MAX is lowered to 1 when K is not a multiple @@ -863,16 +859,16 @@ bool launch_gemm_4bit_wmma( // clang-format on ) { #if BNB_WMMA_EMIT_12 - if (arch == 12) { - launch_gemm_4bit_wmma_arch<12, T>( + if (arch == WMMA_TARGET_GFX12) { + launch_gemm_4bit_wmma_arch( A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream ); return true; } #endif #if BNB_WMMA_EMIT_11 - if (arch == 11) { - launch_gemm_4bit_wmma_arch<11, T>( + if (arch == WMMA_TARGET_GFX11) { + launch_gemm_4bit_wmma_arch( A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream ); return true; diff --git a/tests/test_functional.py b/tests/test_functional.py index 3b2e9e489..0d6eebd35 100644 --- a/tests/test_functional.py +++ b/tests/test_functional.py @@ -37,7 +37,7 @@ (24, 6000, 704), # RDNA3/RDNA4 WMMA: 64-K iterations (K % 128 != 0), wide N (200, 2000, 512), # RDNA3/RDNA4 WMMA: M > 128 tile with split-K (5, 8192, 256), # RDNA4 WMMA: fp32 starts at M=5 on wide N - (16, 6144, 512), # RDNA4 WMMA: M <= 16 tile for N >= 6144 (128-K iterations) + (16, 6144, 512), # RDNA4 WMMA: wide-N M <= 16 tile (128-K iterations for fp16/bf16) (17, 4096, 704), # RDNA4 WMMA: one row past a 16-row tile, K % 128 != 0 ] @@ -1029,7 +1029,7 @@ def test_matmul_4bit_fp32_precision(self, M, N, blocksize, quant_type, compress_ # emulate it with split bf16 operands). Compare against a float64 product of the # same dequantized weights. N=8192 reaches RDNA4's fp32 WMMA tiles at small M, which # narrow weights (N=1000) leave to SIMT up to M=31. - if device not in ("cuda",): + if device != "cuda": pytest.skip("fp32 precision bound is calibrated for the CUDA/ROCm kernels") K = 1024 A = torch.randn(1, M, K, dtype=torch.float32, device=device) @@ -1039,11 +1039,32 @@ def test_matmul_4bit_fp32_precision(self, M, N, blocksize, quant_type, compress_ ) ref = A.double() @ F.dequantize_4bit(qB, qs).double().t() out = bnb.matmul_4bit(A, qB, qs) - # fp32 kernels and the fp32 dequant+F.linear fallback stay below ~6e-7; a - # reduced-precision (e.g. bf16 or two-part bf16) path would be at >=8e-6. + # Mean absolute error over mean absolute reference. The fp32 kernels and the fp32 + # dequant+F.linear fallback stay below ~1.5e-6 (the RDNA4 three-part split-bf16 WMMA path + # with blocksize 64 is the highest); a two-part bf16 split or bf16 math would be at >=8e-6. rel = ((out.double() - ref).abs().mean() / ref.abs().mean()).item() assert rel < 2e-6 + @pytest.mark.parametrize("device", get_available_devices()) + @pytest.mark.parametrize("M", [4, 100], ids=id_formatter("M")) + def test_matmul_4bit_fp32_special_values(self, M, device): + # Inf and NaN activations must propagate as in fp32 math on every kernel path (the + # RDNA3/RDNA4 split-bf16 WMMA path must not turn Inf * (zero lower part) into NaN). + if device != "cuda": + pytest.skip("checks the CUDA/ROCm 4-bit GEMM kernels") + N, K = 4096, 1024 + A = torch.randn(1, M, K, dtype=torch.float32, device=device) + A[..., 0] = float("inf") + A[..., 1::4, 1] = float("-inf") + A[..., 2::4, 2] = float("nan") + B = torch.randn(N, K, dtype=torch.float32, device=device) / (K**0.5) + qB, qs = F.quantize_4bit(B, blocksize=64, quant_type="nf4") + ref = A.double() @ F.dequantize_4bit(qB, qs).double().t() + out = bnb.matmul_4bit(A, qB, qs).double() + assert torch.equal(out.isnan(), ref.isnan()) + assert torch.equal(out.isposinf(), ref.isposinf()) + assert torch.equal(out.isneginf(), ref.isneginf()) + @pytest.mark.parametrize("device", get_available_devices()) def test_matmul_4bit_weight_orientation(self, device): N, K = 256, 128 From 560cf650ffcdba42f34eee94c252d86acb31adf0 Mon Sep 17 00:00:00 2001 From: sstamenk Date: Thu, 19 Nov 2026 23:23:01 +0100 Subject: [PATCH 04/10] [ROCm] WMMA 4-bit GEMM: tuning targets by gfx number with family fallback The tuning targets were ad hoc numbers (11, 113, 115, 12) that grouped chips by the rules they shared. They are now the chips' gfx numbers (1100-1103, 1150-1153, 1200-1201), and each family has a main target its rules were calibrated on: gfx1100 for gfx110x, gfx1151 for gfx115x, gfx1201 for gfx120x. Each kind of tuning is a per-chip specialization that falls back to the family main: - WmmaFp32Cutoffs (SIMT vs WMMA for fp32): own for gfx1100, gfx1103, gfx1151, gfx1201. - WmmaTileRules (tile tables): own for gfx1100, gfx1151, gfx1201; targets sharing tables share one launcher instantiation (`owner`). - _ROCM_WMMA_MAX_M in Python (fused vs dequant+F.linear): own for gfx1100, gfx1103, gfx1151, gfx1201. A newly measured chip then only adds the specializations it needs. The block order and the gfx12 M = 1 SIMT rule follow the family/generation as before. No behaviour change: every chip gets the same tiles and SIMT/WMMA choices as before (compared on a host over M = 1-600 and N, K in multiples of 64 plus the thresholds, fp16 and fp32) and the same Python limits; wmma_arch_of accepts exactly the same chips. Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 36 ++++---- csrc/gemm_4bit_wmma.cu | 125 ++++++++++++---------------- csrc/gemm_4bit_wmma.cuh | 4 +- csrc/gemm_4bit_wmma_rules.cuh | 131 +++++++++++++++++++++--------- 4 files changed, 167 insertions(+), 129 deletions(-) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 0391d3ff8..44c6a3a23 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -811,17 +811,30 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): return M <= (16 if (tall_k_2xn or n_blocks < 48) else 8) +# WMMA kernel targets (csrc/gemm_4bit_wmma_rules.cuh) and the main chip of their family, whose limits a chip uses +# where it has none of its own. +_ROCM_WMMA_FAMILY_MAIN = { + **dict.fromkeys(("gfx1100", "gfx1101", "gfx1102", "gfx1103"), "gfx1100"), + **dict.fromkeys(("gfx1150", "gfx1151", "gfx1152", "gfx1153"), "gfx1151"), + **dict.fromkeys(("gfx1200", "gfx1201"), "gfx1201"), +} +# Largest M on the fused path per WMMA target: (bf16/fp16, fp32). +_ROCM_WMMA_MAX_M = { + "gfx1100": (384, 128), # W7900 + "gfx1103": (384, 384), # Radeon 760M + "gfx1151": (512, 512), # Radeon 8060S + "gfx1201": (384, 512), # R9700 +} + + @functools.cache def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): """ Fused custom kernel vs dequant+F.linear heuristic for ROCm. RDNA3/RDNA3.5/RDNA4 with K % 64 == 0 have a WMMA kernel (the C dispatch picks SIMT or WMMA), - which stays ahead of dequant+F.linear up to these M limits: - - gfx110x: bf16/fp16 through M=384, fp32 through M=128. - - gfx1103: all dtypes through M=384. - - gfx115x: all dtypes through M=512. - - gfx120x: bf16/fp16 through M=384, fp32 through M=512. + which stays ahead of dequant+F.linear up to the limits in _ROCM_WMMA_MAX_M; a chip without its own + entry uses its family main's (_ROCM_WMMA_FAMILY_MAIN). Otherwise (K % 64 != 0) gfx11/gfx12 keep SIMT through M=8. gfx125x (CDNA5) is Wave32 but lacks the v_dot2 SIMT instructions, so its kernel takes the fp32-FMA CDNA math path; it keeps the gfx12 default (M<=8) pending calibration. CDNA/gfx9 is calibrated on MI308X (gfx942): bf16/fp16 win through @@ -833,15 +846,10 @@ def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): return True arch = _rocm_gfx_arch(device_index) - if K % 64 == 0: # WMMA kernel - if arch == "gfx1103": # RDNA3 iGPU - return M <= 384 - if arch.startswith("gfx110"): # RDNA3 - return M <= (128 if dtype == torch.float32 else 384) - if arch.startswith("gfx115"): # RDNA3.5 (gfx1151 values) - return M <= 512 - if arch.startswith("gfx120"): # RDNA4 (gfx1201 values) - return M <= (512 if dtype == torch.float32 else 384) + family_main = _ROCM_WMMA_FAMILY_MAIN.get(arch) + if family_main is not None and K % 64 == 0: # WMMA kernel + max_m = _ROCM_WMMA_MAX_M.get(arch, _ROCM_WMMA_MAX_M[family_main]) + return M <= max_m[dtype == torch.float32] if arch.startswith("gfx11") or arch.startswith("gfx12"): # RDNA3 / RDNA4 / CDNA5 (gfx125x) return M <= 8 if arch.startswith("gfx9"): # CDNA1-4 / MI-series (Wave64) diff --git a/csrc/gemm_4bit_wmma.cu b/csrc/gemm_4bit_wmma.cu index 394dd204f..9db2da152 100644 --- a/csrc/gemm_4bit_wmma.cu +++ b/csrc/gemm_4bit_wmma.cu @@ -57,10 +57,6 @@ using wmma_v16s = short __attribute__((ext_vector_type(16))); // products (see wmma_16x16x16), gfx12 one full 16x16x16 product. constexpr int wmma_rows(int arch) { return arch == 12 ? 16 : 8; } -// WMMA generation (kernel family) of a tuning target (gemm_4bit_wmma_rules.cuh): gfx120x runs the gfx12 -// kernels, gfx110x, gfx1103 and gfx115x the gfx11 kernels. -constexpr int wmma_gen(int target) { return target == WMMA_TARGET_GFX12 ? 12 : 11; } - // Per-lane operand fragment: 16 (gfx11) or 8 (gfx12) 16-bit values. template using wmma_frag = std::conditional_t; @@ -625,25 +621,23 @@ __global__ void __launch_bounds__(KSPLIT* WARPS_M* WARPS_N * 32) gemm_4bit_wmma( namespace { -// WMMA tuning target for a gcnArchName ("gfx1201" or "gfx1201:xnack-"): 11, 113, 115, 12, or 0. -// The chips must be ones whose device pass emits the kernel body (BNB_WMMA_DEVICE_ARCH, -// including builds for gfx11-generic / gfx12-generic); any other device would launch an empty kernel. Measured: -// gfx1100, gfx1103, gfx1151 and gfx1201. gfx1101/gfx1102, gfx1150/gfx1152/gfx1153 and gfx1200 share the WMMA -// instructions of their family and use its rules (gfx1100, gfx1151, gfx1201) unmeasured. +// WMMA tuning target for a gcnArchName ("gfx1201" or "gfx1201:xnack-"): its gfx number if it is in WMMA_TARGETS +// (chips whose device pass emits the kernel body, BNB_WMMA_DEVICE_ARCH, including builds for gfx11-generic / +// gfx12-generic), else 0. Tunings per target and their family fallback: gemm_4bit_wmma_rules.cuh. int wmma_arch_of(const char* name) { - static constexpr struct { - const char* chip; - int arch; - } chips[] = {{"gfx1100", WMMA_TARGET_GFX11}, {"gfx1101", WMMA_TARGET_GFX11}, {"gfx1102", WMMA_TARGET_GFX11}, - {"gfx1103", WMMA_TARGET_GFX1103}, {"gfx1150", WMMA_TARGET_GFX115X}, {"gfx1151", WMMA_TARGET_GFX115X}, - {"gfx1152", WMMA_TARGET_GFX115X}, {"gfx1153", WMMA_TARGET_GFX115X}, {"gfx1200", WMMA_TARGET_GFX12}, - {"gfx1201", WMMA_TARGET_GFX12}}; - - for (const auto& c : chips) { - const size_t n = std::strlen(c.chip); - if (std::strncmp(name, c.chip, n) == 0 && (name[n] == '\0' || name[n] == ':')) - return c.arch; + if (std::strncmp(name, "gfx", 3) != 0) + return 0; + int target = 0, digits = 0; + for (const char* p = name + 3; *p != '\0' && *p != ':'; p++, digits++) { + if (*p < '0' || *p > '9') + return 0; + target = target * 10 + (*p - '0'); } + if (digits != 4) + return 0; + for (const int t : WMMA_TARGETS) + if (t == target) + return t; return 0; } @@ -667,11 +661,7 @@ int wmma_device_arch() { /// Whether blocks walk the row tiles of the same N columns first, so they share B in L2 /// (see gemm_4bit_wmma_body). Only matters with two or more row tiles. fp32 on gfx110x /// stays N-first. The tile rules are fitted with this order. -bool wmma_row_tiles_first(int target, bool fp32) { - if (target == WMMA_TARGET_GFX11 || target == WMMA_TARGET_GFX1103) - return !fp32; - return target == WMMA_TARGET_GFX12 || target == WMMA_TARGET_GFX115X; -} +bool wmma_row_tiles_first(int target, bool fp32) { return wmma_family_main(target) == 1100 ? !fp32 : true; } /// Launch one tile configuration. KCH_MAX is lowered to 1 when K is not a multiple /// of 128; one absmax covers each half-wave's per-iteration K slice when @@ -744,26 +734,12 @@ void launch_wmma_tile( ); } -/// The tile rule table (gemm_4bit_wmma_rules.cuh) of a tuning target and dtype. gfx1103 uses the gfx110x tables -/// (it differs in the SIMT/WMMA fp32 cutoffs and Python M limits only); bf16 and fp16 share a table. +/// The tile rule table (gemm_4bit_wmma_rules.cuh) of a tuning target and dtype; bf16 and fp16 share a table. template constexpr const auto& wmma_rules() { - constexpr bool fp32 = std::is_same_v; - if constexpr (wmma_gen(TARGET) == 12) { - if constexpr (fp32) - return wmma_rules_gfx12_f32; - else - return wmma_rules_gfx12_f16; - } else if constexpr (TARGET == WMMA_TARGET_GFX115X) { - if constexpr (fp32) - return wmma_rules_gfx115_f32; - else - return wmma_rules_gfx115_f16; - } else { - if constexpr (fp32) - return wmma_rules_gfx11_f32; - else - return wmma_rules_gfx11_f16; - } + if constexpr (std::is_same_v) + return WmmaTileRules::f32; + else + return WmmaTileRules::f16; } /// The distinct tiles of a rule table in first-use order (at most four per bucket). @@ -833,12 +809,36 @@ void launch_gemm_4bit_wmma_arch( ); } +/// Launch for `target` if it is WMMA_TARGETS[I], through the launcher of the target owning its tile tables. Only +/// targets of the generation this pass emits kernels for are instantiated (the host pass: all). +template +bool launch_gemm_4bit_wmma_of( + int target, std::index_sequence, const T* A, const uint8_t* B, const float* absmax, + const uint8_t* absmax_8bit, const float* absmax_code, const float* absmax_offset, T* C, const T* bias, int M, int N, + int K, int blocksize, int quant_type, bnb_stream_t stream +) { + bool launched = false; + auto one = [&](auto target_constant) { + constexpr int TARGET = decltype(target_constant)::value; + if constexpr (wmma_gen(TARGET) == 12 ? BNB_WMMA_EMIT_12 : BNB_WMMA_EMIT_11) { + launch_gemm_4bit_wmma_arch::owner, T>( + A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); + return true; + } + return false; + }; + (void)((target == WMMA_TARGETS[I] && (launched = one(std::integral_constant{}), true)) || + ...); + return launched; +} + } // namespace int gemm_4bit_wmma_arch() { return wmma_device_arch(); } /// @brief Host launcher for the RDNA3/RDNA4 WMMA 4-bit GEMM kernel. -/// @return false (nothing launched) if `arch` is not a WMMA generation this build has kernels for. +/// @return false (nothing launched) if `arch` is not a WMMA target this build has kernels for. /// @tparam T Input/output dtype (`bnb_bfloat16`, `half` or `float`) template bool launch_gemm_4bit_wmma( @@ -858,35 +858,10 @@ bool launch_gemm_4bit_wmma( bnb_stream_t stream // HIP stream // clang-format on ) { -#if BNB_WMMA_EMIT_12 - if (arch == WMMA_TARGET_GFX12) { - launch_gemm_4bit_wmma_arch( - A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream - ); - return true; - } -#endif -#if BNB_WMMA_EMIT_11 - if (arch == WMMA_TARGET_GFX11) { - launch_gemm_4bit_wmma_arch( - A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream - ); - return true; - } - if (arch == WMMA_TARGET_GFX1103) { - launch_gemm_4bit_wmma_arch( - A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream - ); - return true; - } - if (arch == WMMA_TARGET_GFX115X) { - launch_gemm_4bit_wmma_arch( - A, B, absmax, absmax_8bit, absmax_code, absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream - ); - return true; - } -#endif - return false; + return launch_gemm_4bit_wmma_of( + arch, std::make_index_sequence{}, A, B, absmax, absmax_8bit, absmax_code, + absmax_offset, C, bias, M, N, K, blocksize, quant_type, stream + ); } template bool launch_gemm_4bit_wmma( diff --git a/csrc/gemm_4bit_wmma.cuh b/csrc/gemm_4bit_wmma.cuh index 5ad08cfcc..6127a9ff8 100644 --- a/csrc/gemm_4bit_wmma.cuh +++ b/csrc/gemm_4bit_wmma.cuh @@ -9,8 +9,8 @@ #include "compat.cuh" // CUDA/HIP runtime headers + bnb_stream_t -// WMMA tuning target of the current device: 11 (gfx1100-gfx1102), 113 (gfx1103), 115 (gfx115x), 12 (gfx120x), or 0 -// if the kernel is not enabled for it. Tile rules per target: gemm_4bit_wmma_rules.cuh. +// WMMA tuning target of the current device: its gfx number (1100-1103, 1150-1153, 1200-1201), or 0 if the kernel is not +// enabled for it. Tunings per target and their family fallback: gemm_4bit_wmma_rules.cuh. int gemm_4bit_wmma_arch(); // Returns false (nothing launched) if `arch` is not a target this build has WMMA kernels for. diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index 0dea991fc..b56420f10 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -1,15 +1,27 @@ #pragma once -// AMD WMMA 4-bit GEMM tuning rules per target: SIMT or WMMA, and the WMMA tile. +// AMD WMMA 4-bit GEMM tuning rules per gfx target: SIMT or WMMA, and the WMMA tile. A target without its own +// specialization below uses its family main's (wmma_family_main). #include +#include #include - -// Tuning targets returned by gemm_4bit_wmma_arch(). gfx1103 and gfx115x run the gfx11 kernels; gfx1103 uses the -// gfx110x tile rules with its own fp32 SIMT/WMMA cutoffs, gfx115x has its own rules. -inline constexpr int WMMA_TARGET_GFX11 = 11; // gfx1100-gfx1102 -inline constexpr int WMMA_TARGET_GFX1103 = 113; // gfx1103 (Radeon 760M/780M iGPU) -inline constexpr int WMMA_TARGET_GFX115X = 115; // gfx1150-gfx1153 -inline constexpr int WMMA_TARGET_GFX12 = 12; // gfx1200-gfx1201 +#include +#include + +/// The supported chips (the device pass of each emits the kernel body, see BNB_WMMA_DEVICE_ARCH). +inline constexpr int WMMA_TARGETS[] = {1100, 1101, 1102, 1103, 1150, 1151, 1152, 1153, 1200, 1201}; + +/// WMMA generation (kernel family): gfx120x runs the gfx12 kernels, gfx110x and gfx115x the gfx11 kernels. +constexpr int wmma_gen(int target) { return target >= 1200 ? 12 : 11; } + +/// The main target of a chip's family, whose tunings it uses where it has none of its own. +constexpr int wmma_family_main(int target) { + if (target >= 1200) + return 1201; + if (target >= 1150) + return 1151; + return 1100; +} // --------------------------------------------------------------------------------------------------------------- // SIMT or WMMA (csrc/gemm_4bit.cu), once Python has chosen the fused kernel over dequant+F.linear. @@ -21,16 +33,35 @@ struct WmmaFp32Cutoff { }; // clang-format off -/// gfx11: SIMT through M = 4, then WMMA by N; N < 1024 stays on SIMT through M = 64. -inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx11[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, {8, 2048}, {12, 2816}, {64, 1024}}; +/// gfx1100: SIMT through M = 4, then WMMA by N; N < 1024 stays on SIMT through M = 64. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1100[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, {8, 2048}, {12, 2816}, {64, 1024}}; /// gfx1103: SIMT through M = 2, WMMA from M = 3 (N >= 3840 through M = 4). inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1103[] = {{2, INT_MAX}, {4, 3840}}; -/// gfx115x: SIMT through M = 3, then WMMA by N through M = 7. -inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx115[] = {{3, INT_MAX}, {5, 2560}, {7, 1024}}; -/// gfx12: SIMT through M = 4, then WMMA by N through M = 31. -inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx12[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, {9, 2048}, {15, 1408}, {31, 1024}}; +/// gfx1151: SIMT through M = 3, then WMMA by N through M = 7. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1151[] = {{3, INT_MAX}, {5, 2560}, {7, 1024}}; +/// gfx1201: SIMT through M = 4, then WMMA by N through M = 31. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1201[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, {9, 2048}, {15, 1408}, {31, 1024}}; // clang-format on +/// The fp32 cutoffs of a target: its own where it has them, else its family main's. +template struct WmmaFp32Cutoffs : WmmaFp32Cutoffs {}; + +template <> struct WmmaFp32Cutoffs<1100> { + static constexpr const auto& table = wmma_fp32_cutoffs_gfx1100; +}; + +template <> struct WmmaFp32Cutoffs<1103> { + static constexpr const auto& table = wmma_fp32_cutoffs_gfx1103; +}; + +template <> struct WmmaFp32Cutoffs<1151> { + static constexpr const auto& table = wmma_fp32_cutoffs_gfx1151; +}; + +template <> struct WmmaFp32Cutoffs<1201> { + static constexpr const auto& table = wmma_fp32_cutoffs_gfx1201; +}; + template constexpr bool wmma_fp32_pick(const WmmaFp32Cutoff (&cutoffs)[R], int M, int N) { for (const WmmaFp32Cutoff& c : cutoffs) if (M <= c.max_m) @@ -40,19 +71,21 @@ template constexpr bool wmma_fp32_pick(const WmmaFp32Cutoff (&cutoffs)[R /// Whether the WMMA kernel (rather than SIMT) runs on a WMMA target (target != 0). bf16/fp16: WMMA at every M /// on the gfx11 kernels, from M = 2 on gfx12 (a gfx12 WMMA always computes 16 rows); fp32: the target's cutoffs. -constexpr bool wmma_preferred(int target, bool fp32, int M, int N) { +template constexpr bool wmma_preferred_for(bool fp32, int M, int N) { if (!fp32) - return target != WMMA_TARGET_GFX12 || M >= 2; - switch (target) { - case WMMA_TARGET_GFX12: - return wmma_fp32_pick(wmma_fp32_cutoffs_gfx12, M, N); - case WMMA_TARGET_GFX115X: - return wmma_fp32_pick(wmma_fp32_cutoffs_gfx115, M, N); - case WMMA_TARGET_GFX1103: - return wmma_fp32_pick(wmma_fp32_cutoffs_gfx1103, M, N); - default: - return wmma_fp32_pick(wmma_fp32_cutoffs_gfx11, M, N); - } + return wmma_gen(TARGET) != 12 || M >= 2; + return wmma_fp32_pick(WmmaFp32Cutoffs::table, M, N); +} + +template +constexpr bool wmma_preferred_of(int target, bool fp32, int M, int N, std::index_sequence) { + bool r = false; + (void)((target == WMMA_TARGETS[I] && (r = wmma_preferred_for(fp32, M, N), true)) || ...); + return r; +} + +constexpr bool wmma_preferred(int target, bool fp32, int M, int N) { + return wmma_preferred_of(target, fp32, M, N, std::make_index_sequence{}); } // --------------------------------------------------------------------------------------------------------------- @@ -123,10 +156,10 @@ template constexpr WmmaTile wmma_pick(const WmmaRule (&rules)[R], int M, // clang-format off -/// gfx11 bf16/fp16. Narrow N keeps 16-column warp tiles and deeper split-K so enough warps stream B; wide N +/// gfx1100 bf16/fp16. Narrow N keeps 16-column warp tiles and deeper split-K so enough warps stream B; wide N /// uses 32-column warp tiles and 128-K iterations. At M <= 8, very wide layers (K/N < 2/7) use two warps along /// N and very tall ones (K >= 5N) a shorter split-K with 128-K iterations. -inline constexpr WmmaRule wmma_rules_gfx11_f16[] = { +inline constexpr WmmaRule wmma_rules_gfx1100_f16[] = { {8, {k_over_n_lt(2, 7, {1, 1, 1, 2, 8, 1}), k_over_n_lt(5, 1, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 2, 4, 2}}, {16, {n_lt(5120, {2, 1, 1, 2, 8, 1})}, {2, 2, 1, 2, 4, 2}}, {24, {n_lt(3072, {1, 2, 1, 1, 8, 1}), n_lt(5120, {2, 2, 1, 2, 4, 2})}, {4, 1, 1, 4, 2, 2}}, @@ -137,8 +170,8 @@ inline constexpr WmmaRule wmma_rules_gfx11_f16[] = { {INT_MAX, {n_lt(2816, {4, 1, 1, 4, 2, 2}), n_lt(3072, {4, 2, 1, 4, 2, 1})}, {4, 2, 1, 4, 1, 2}}, }; -/// gfx11 fp32 (three LDS A tiles per stage). -inline constexpr WmmaRule wmma_rules_gfx11_f32[] = { +/// gfx1100 fp32 (three LDS A tiles per stage). +inline constexpr WmmaRule wmma_rules_gfx1100_f32[] = { {8, {n_lt(3840, {1, 1, 1, 1, 4, 1}), n_lt(5120, {1, 1, 1, 2, 2, 2})}, {1, 2, 1, 2, 2, 2}}, {16, {n_lt(3840, {1, 1, 1, 2, 4, 1}), n_lt(5120, {2, 1, 1, 2, 2, 1}), n_lt(15360, {2, 1, 1, 4, 1, 2})}, {2, 2, 1, 4, 1, 2}}, {24, {n_lt(3072, {1, 1, 1, 2, 4, 1})}, {1, 2, 1, 2, 2, 2}}, @@ -146,8 +179,8 @@ inline constexpr WmmaRule wmma_rules_gfx11_f32[] = { {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, }; -/// gfx115x bf16/fp16: fewer warps along N at small M than gfx1100. -inline constexpr WmmaRule wmma_rules_gfx115_f16[] = { +/// gfx1151 bf16/fp16: fewer warps along N at small M than gfx1100. +inline constexpr WmmaRule wmma_rules_gfx1151_f16[] = { {8, {n_lt(3072, {1, 1, 1, 1, 4, 1}), n_lt(28672, {1, 1, 1, 1, 8, 2})}, {1, 1, 1, 1, 2, 2}}, {16, {n_lt(3072, {2, 1, 1, 2, 4, 1}), n_lt(25600, {2, 2, 1, 1, 4, 2})}, {2, 1, 1, 2, 2, 2}}, {24, {k_lt(8192, {4, 1, 1, 4, 2, 2}), k_lt(10240, {4, 1, 1, 2, 1, 2})}, {1, 2, 1, 1, 8, 2}}, @@ -159,8 +192,8 @@ inline constexpr WmmaRule wmma_rules_gfx115_f16[] = { {INT_MAX, {k_lt(21504, {4, 2, 1, 4, 1, 2})}, {4, 1, 1, 4, 2, 2}}, }; -/// gfx115x fp32. -inline constexpr WmmaRule wmma_rules_gfx115_f32[] = { +/// gfx1151 fp32. +inline constexpr WmmaRule wmma_rules_gfx1151_f32[] = { {8, {n_lt(2048, {1, 1, 1, 2, 4, 1}), n_lt(3072, {1, 1, 1, 4, 4, 1})}, {1, 2, 1, 2, 2, 2}}, {16, {k_lt(4608, {2, 2, 1, 2, 2, 1}), k_lt(8192, {2, 2, 1, 4, 1, 2})}, {2, 1, 1, 4, 1, 2}}, {32, {k_lt(3840, {1, 1, 1, 4, 2, 1}), k_lt(17408, {2, 2, 1, 4, 1, 2})}, {1, 2, 1, 2, 2, 2}}, @@ -168,9 +201,9 @@ inline constexpr WmmaRule wmma_rules_gfx115_f32[] = { {INT_MAX, {n_lt(2048, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, }; -/// gfx12 bf16/fp16. One 16-row tile covers M <= 16; larger M adds warps along N and rows per warp rather than +/// gfx1201 bf16/fp16. One 16-row tile covers M <= 16; larger M adds warps along N and rows per warp rather than /// warps along M. -inline constexpr WmmaRule wmma_rules_gfx12_f16[] = { +inline constexpr WmmaRule wmma_rules_gfx1201_f16[] = { {16, {n_lt(3840, {1, 1, 1, 2, 8, 1})}, {1, 2, 1, 2, 4, 2}}, {32, {n_lt(2048, {1, 1, 1, 2, 8, 1}), n_lt(8192, {2, 1, 1, 4, 4, 1})}, {2, 2, 1, 4, 2, 2}}, {96, {n_lt(3840, {2, 1, 1, 4, 4, 1})}, {2, 2, 1, 4, 2, 2}}, @@ -179,8 +212,8 @@ inline constexpr WmmaRule wmma_rules_gfx12_f16[] = { {INT_MAX, {n_lt(2816, {2, 2, 1, 4, 2, 2}), n_lt(3840, {4, 1, 1, 4, 1, 1})}, {4, 2, 1, 4, 1, 1}}, }; -/// gfx12 fp32 (one-fragment split-bf16 kernel). -inline constexpr WmmaRule wmma_rules_gfx12_f32[] = { +/// gfx1201 fp32 (one-fragment split-bf16 kernel). +inline constexpr WmmaRule wmma_rules_gfx1201_f32[] = { {16, {n_lt(3840, {1, 1, 1, 2, 2, 1}), n_lt(4608, {1, 1, 1, 4, 2, 1})}, {1, 2, 1, 2, 2, 1}}, {48, {n_lt(8192, {1, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 1}}, {96, {n_lt(3840, {2, 1, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 1}}, @@ -189,3 +222,25 @@ inline constexpr WmmaRule wmma_rules_gfx12_f32[] = { }; // clang-format on + +/// The tile rule tables of a target: its own where it has them, else its family main's (gfx1103 uses gfx1100's). +/// `owner` is the target whose tables they are, so targets sharing tables share one launcher instantiation. +template struct WmmaTileRules : WmmaTileRules {}; + +template <> struct WmmaTileRules<1100> { + static constexpr int owner = 1100; + static constexpr const auto& f16 = wmma_rules_gfx1100_f16; + static constexpr const auto& f32 = wmma_rules_gfx1100_f32; +}; + +template <> struct WmmaTileRules<1151> { + static constexpr int owner = 1151; + static constexpr const auto& f16 = wmma_rules_gfx1151_f16; + static constexpr const auto& f32 = wmma_rules_gfx1151_f32; +}; + +template <> struct WmmaTileRules<1201> { + static constexpr int owner = 1201; + static constexpr const auto& f16 = wmma_rules_gfx1201_f16; + static constexpr const auto& f32 = wmma_rules_gfx1201_f32; +}; From 0e5cfb99b38fdb270a335c989b1107de579929be Mon Sep 17 00:00:00 2001 From: sstamenk Date: Thu, 19 Nov 2026 23:24:04 +0100 Subject: [PATCH 05/10] [ROCm] WMMA 4-bit GEMM: own tunings for gfx1200 gfx1200 (RX 9060 XT: 32 CUs, 320 GB/s, 32 MB Infinity Cache) used the gfx1201 (R9700, 64 CUs) rules unmeasured. Measured at pinned clocks over the 40 shapes: - Tile rules: own tile tables (WmmaTileRules<1200>; it keeps the gfx12 kernels, row-tiles-first order and gfx1201 SIMT/WMMA choice through the family fallback) fitted from tile sweeps. The gfx1201 tables were 5-6% off the best swept tile at M <= 16, 7-8% at M = 20-32 and 13-16% at M = 104-128 (fp16), 4% at M = 20-32 (fp32); those buckets are refitted (fp16 within 1.6-4.0%, fp32 0.5-0.6%), the others keep the gfx1201 tiles. A/B/A of the default dispatch (A1/A2 within 0.72%): bf16/fp16 1.04x faster at M = 2-32 and 1.09-1.12x at M = 97-128, fp32 1.035x at M = 17-32; other M within 0.33%. - fp32 SIMT/WMMA cutoffs and the bf16/fp16 SIMT choice at M = 1 are shared with gfx1201: a refit on gfx1200 timings gains at most 0.3%. - Python M limit: bf16/fp16 now through M = 512 on gfx1200 (gfx1201: 384). At M = 385-512 the fused kernel is 1.29-1.42x faster in total than dequant + F.linear and ahead on 24-31 of the 40 shapes (repeated, also with blocksize 32). fp32 stays at 512. Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 1 + csrc/gemm_4bit_wmma_rules.cuh | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 44c6a3a23..19036b0e6 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -823,6 +823,7 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): "gfx1100": (384, 128), # W7900 "gfx1103": (384, 384), # Radeon 760M "gfx1151": (512, 512), # Radeon 8060S + "gfx1200": (512, 512), # RX 9060 XT "gfx1201": (384, 512), # R9700 } diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index b56420f10..7258eefd8 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -201,6 +201,27 @@ inline constexpr WmmaRule wmma_rules_gfx1151_f32[] = { {INT_MAX, {n_lt(2048, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, }; +/// gfx1200 bf16/fp16: own tiles at M <= 32 and M = 97-128, the gfx1201 tiles elsewhere. At M <= 16 the +/// split-K-8 tile covers N < 10240 (gfx1201: N < 3840). +inline constexpr WmmaRule wmma_rules_gfx1200_f16[] = { + {16, {n_lt(10240, {1, 1, 1, 2, 8, 1})}, {1, 1, 1, 4, 4, 2}}, + {32, {n_lt(3840, {2, 1, 1, 4, 4, 1}), n_lt(8192, {2, 2, 1, 4, 2, 2})}, {2, 1, 1, 4, 2, 2}}, + {96, {n_lt(3840, {2, 1, 1, 4, 4, 1})}, {2, 2, 1, 4, 2, 2}}, + {128, {n_lt(2816, {2, 2, 1, 4, 2, 2}), n_lt(8192, {4, 2, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 2}}, + {160, {n_lt(3072, {2, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {2, 2, 1, 4, 2, 2}), n_lt(3840, {4, 1, 1, 4, 1, 1})}, {4, 2, 1, 4, 1, 1}}, +}; + +/// gfx1200 fp32: the gfx1201 table plus its own M = 17-32 bucket. +inline constexpr WmmaRule wmma_rules_gfx1200_f32[] = { + {16, {n_lt(3840, {1, 1, 1, 2, 2, 1}), n_lt(4608, {1, 1, 1, 4, 2, 1})}, {1, 2, 1, 2, 2, 1}}, + {32, {n_lt(3840, {1, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 1}}, + {48, {n_lt(8192, {1, 1, 1, 4, 2, 1})}, {2, 2, 1, 4, 1, 1}}, + {96, {n_lt(3840, {2, 1, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 1}}, + {192, {n_lt(2048, {2, 1, 1, 4, 1, 1})}, {2, 2, 1, 4, 1, 1}}, + {INT_MAX, {}, {2, 2, 1, 4, 1, 1}}, +}; + /// gfx1201 bf16/fp16. One 16-row tile covers M <= 16; larger M adds warps along N and rows per warp rather than /// warps along M. inline constexpr WmmaRule wmma_rules_gfx1201_f16[] = { @@ -239,6 +260,12 @@ template <> struct WmmaTileRules<1151> { static constexpr const auto& f32 = wmma_rules_gfx1151_f32; }; +template <> struct WmmaTileRules<1200> { + static constexpr int owner = 1200; + static constexpr const auto& f16 = wmma_rules_gfx1200_f16; + static constexpr const auto& f32 = wmma_rules_gfx1200_f32; +}; + template <> struct WmmaTileRules<1201> { static constexpr int owner = 1201; static constexpr const auto& f16 = wmma_rules_gfx1201_f16; From 6a8f5d9a92a7abc54718e28408e37e0be333ca61 Mon Sep 17 00:00:00 2001 From: sstamenk Date: Thu, 19 Nov 2026 23:24:05 +0100 Subject: [PATCH 06/10] [ROCm] WMMA 4-bit GEMM: own tile rules for gfx1150 (Radeon 890M) gfx1150 used the gfx1151 (Radeon 8060S) rules unmeasured. On the Radeon 890M (16 CUs, 2 MB L2, no Infinity Cache) those tables were approximately 1.04-1.07x off the per-shape best swept tile at M <= 16 and up to 1.44x at M = 192-256 (fp16), and approximately 1.03-1.15x at M = 12-64 (fp32); the gfx110x/gfx1103 tiles were 4-16% off at fp16 M < 128. gfx1150 gets its own bf16/fp16 and fp32 tile tables (WmmaTileRules<1150>) fitted from tile sweeps over the 40 shapes (derive_cfg3.py), with M = 65-96 fitted on fp16 and bf16 together (fp16 prescaling made an fp16-only fit up to 1.5x slower on some bf16 layers) and a narrow-N leaf at M = 17-64 (fp32: 9-16) for the MoE expert and GQA k/v layers. fp32 keeps the gfx115x tiles at M <= 8 and above M = 64 and the gfx1151 SIMT/WMMA cutoffs (family fallback), where a refit gained less than approximately 3%. Validated against the inherited rules in one process per dtype, 5 alternating cycles, at performance level high (not a fixed clock on this APU), total over the 40 shapes: fp16/bf16 1.03x at M = 1-16, 1.04-1.26x at M = 20-128, 1.19-1.44x at M = 160-512; fp32 1.11x at M = 9-16 and 1.02-1.15x at M = 20-64. Single MoE down projections still lose up to approximately 1.28x at M = 72-160; the benchmark notes list them. Kept after measuring: row-tiles-first block order (fp16 N-first approximately 1.12x slower at M = 128-256) and the Python limit of M = 512 (the fused path beats dequant + F.linear at M = 384-512 in total time and on 37-40 of the 40 shapes in every dtype). Co-Authored-By: Claude Opus 5.5 --- csrc/gemm_4bit_wmma_rules.cuh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index 7258eefd8..ca1653daa 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -179,6 +179,25 @@ inline constexpr WmmaRule wmma_rules_gfx1100_f32[] = { {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, }; +/// gfx1150 bf16/fp16. At M = 17-64 the first leaf gives narrow N (MoE experts, GQA k/v) its own tile. +inline constexpr WmmaRule wmma_rules_gfx1150_f16[] = { + {8, {k_lt(3072, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 1, 8, 2}}, + {16, {k_lt(1536, {2, 1, 1, 2, 4, 1}), k_lt(4096, {2, 1, 1, 1, 8, 1})}, {2, 1, 1, 4, 4, 2}}, + {32, {n_lt(2048, {4, 1, 1, 4, 2, 2}), k_lt(2560, {4, 1, 1, 2, 4, 1}), k_lt(12288, {4, 1, 1, 4, 1, 2})}, {4, 1, 1, 4, 2, 2}}, + {48, {n_lt(1024, {2, 1, 1, 2, 2, 1}), k_lt(3840, {2, 2, 1, 2, 1, 1}), k_lt(12288, {2, 2, 1, 2, 1, 2})}, {4, 2, 1, 4, 2, 2}}, + {64, {n_lt(2048, {4, 1, 1, 4, 1, 2}), k_lt(2560, {4, 1, 1, 4, 2, 2}), k_lt(17408, {4, 2, 1, 4, 1, 2})}, {4, 2, 1, 4, 2, 2}}, + {96, {n_lt(2560, {4, 1, 1, 4, 1, 2}), n_lt(3072, {4, 1, 1, 4, 1, 1})}, {4, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {4, 2, 1, 4, 1, 2}), n_lt(3072, {4, 1, 1, 4, 1, 1})}, {4, 2, 1, 4, 1, 2}}, +}; + +/// gfx1150 fp32: own tiles at M = 9-64, the gfx1151 tiles elsewhere. +inline constexpr WmmaRule wmma_rules_gfx1150_f32[] = { + {8, {n_lt(2048, {1, 1, 1, 2, 4, 1}), n_lt(3072, {1, 1, 1, 4, 4, 1})}, {1, 2, 1, 2, 2, 2}}, + {16, {n_lt(2048, {2, 2, 1, 2, 2, 1}), n_lt(2816, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, + {64, {n_lt(2816, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2048, {2, 2, 1, 4, 1, 2}), n_lt(3072, {2, 2, 1, 2, 1, 1})}, {2, 2, 1, 4, 1, 2}}, +}; + /// gfx1151 bf16/fp16: fewer warps along N at small M than gfx1100. inline constexpr WmmaRule wmma_rules_gfx1151_f16[] = { {8, {n_lt(3072, {1, 1, 1, 1, 4, 1}), n_lt(28672, {1, 1, 1, 1, 8, 2})}, {1, 1, 1, 1, 2, 2}}, @@ -254,6 +273,12 @@ template <> struct WmmaTileRules<1100> { static constexpr const auto& f32 = wmma_rules_gfx1100_f32; }; +template <> struct WmmaTileRules<1150> { + static constexpr int owner = 1150; + static constexpr const auto& f16 = wmma_rules_gfx1150_f16; + static constexpr const auto& f32 = wmma_rules_gfx1150_f32; +}; + template <> struct WmmaTileRules<1151> { static constexpr int owner = 1151; static constexpr const auto& f16 = wmma_rules_gfx1151_f16; From 2a1bc514d761dc7f266be41ca3a71af67da1364f Mon Sep 17 00:00:00 2001 From: sstamenk Date: Thu, 19 Nov 2026 23:24:05 +0100 Subject: [PATCH 07/10] [ROCm] WMMA 4-bit GEMM: own tunings for gfx1101 gfx1101 (RX 7700 XT: 54 CUs, 432 GB/s, 48 MB Infinity Cache) used the gfx1100 (W7900, 96 CUs) rules unmeasured. Measured at pinned clocks over the 40 shapes: - Tile rules: own tile tables (WmmaTileRules<1101>; gfx11 kernels, gfx1100 block order and SIMT/WMMA choice through the family fallback) at M <= 64 (bf16/fp16) and M <= 16 (fp32), fitted from tile sweeps; larger M keeps the gfx1100 tiles. The gfx1100 tables were 5% off the best swept tile at M <= 16 and 9-11% at M = 20-64 (fp16), 8-10% at M <= 16 (fp32). A/B/A of the default dispatch (A1/A2 within 0.53%): bf16/fp16 1.03-1.04x faster at M <= 16 and 1.06-1.07x at M = 17-64, fp32 1.07x at M = 5-8 and 1.09-1.10x at M = 9-16; other M within 0.6%. bf16/fp16 at M = 1 now beats SIMT in total (was 1.7-2.2% slower). - fp32 SIMT/WMMA cutoffs stay the gfx110x ones: with the new tiles they are within 1% of the per-shape faster kernel except M = 4 (3.1%; a refit gains 2.1%). - Python M limits: bf16/fp16 through M = 448 (gfx110x: 384), a conservative shared cap for blocksize 64: fused 1.09-1.18x faster in total at M = 401-448, ahead on 25-37 of the 40 shapes (at 449-480 only 1.03-1.05x on 20-26 shapes); with blocksize 32 fused is even (fp16) / 1.07x slower (bf16) at M = 448. fp32 through M = 512 (gfx110x: 128) for the stock hipBLASLt, whose fp32 GEMM is slow here: dequant+F.linear is 3-5x slower in total; against rocBLAS fused is ahead in total through M = 512, a near-tie there. Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 1 + csrc/gemm_4bit_wmma_rules.cuh | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 19036b0e6..39e50c2d2 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -821,6 +821,7 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): # Largest M on the fused path per WMMA target: (bf16/fp16, fp32). _ROCM_WMMA_MAX_M = { "gfx1100": (384, 128), # W7900 + "gfx1101": (448, 512), # RX 7700 XT "gfx1103": (384, 384), # Radeon 760M "gfx1151": (512, 512), # Radeon 8060S "gfx1200": (512, 512), # RX 9060 XT diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index ca1653daa..6962e5872 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -179,6 +179,26 @@ inline constexpr WmmaRule wmma_rules_gfx1100_f32[] = { {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, }; +/// gfx1101 bf16/fp16: own tiles through M = 64, the gfx1100 tiles above. +inline constexpr WmmaRule wmma_rules_gfx1101_f16[] = { + {8, {n_lt(4608, {1, 1, 1, 1, 4, 1}), n_lt(10240, {1, 1, 1, 1, 8, 2})}, {1, 1, 1, 1, 4, 2}}, + {16, {n_lt(1280, {2, 1, 1, 1, 8, 1}), n_lt(4608, {2, 2, 1, 1, 4, 1}), n_lt(10240, {2, 1, 1, 4, 2, 2})}, {2, 2, 1, 2, 4, 2}}, + {32, {n_lt(3072, {2, 2, 1, 1, 4, 1}), n_lt(5376, {4, 1, 1, 4, 2, 2}), k_over_n_lt(2, 5, {4, 1, 1, 4, 2, 2})}, {4, 2, 1, 2, 2, 1}}, + {48, {n_lt(4096, {2, 2, 1, 1, 4, 1})}, {2, 2, 1, 4, 1, 2}}, + {64, {n_lt(1280, {4, 1, 1, 2, 4, 1}), n_lt(5120, {4, 2, 1, 2, 2, 1})}, {4, 2, 1, 4, 1, 2}}, + {96, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(8192, {4, 2, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {4, 1, 1, 4, 2, 2}), n_lt(3072, {4, 2, 1, 4, 2, 1})}, {4, 2, 1, 4, 1, 2}}, +}; + +/// gfx1101 fp32: own tiles through M = 16, the gfx1100 tiles above. +inline constexpr WmmaRule wmma_rules_gfx1101_f32[] = { + {8, {n_lt(4608, {1, 1, 1, 2, 2, 1}), n_lt(8192, {1, 2, 1, 2, 2, 2})}, {1, 2, 1, 2, 2, 1}}, + {16, {n_lt(2816, {1, 2, 1, 2, 2, 2}), n_lt(8192, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {24, {n_lt(3072, {1, 1, 1, 2, 4, 1})}, {1, 2, 1, 2, 2, 2}}, + {48, {n_lt(2560, {1, 2, 1, 2, 2, 2}), n_lt(5376, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, +}; + /// gfx1150 bf16/fp16. At M = 17-64 the first leaf gives narrow N (MoE experts, GQA k/v) its own tile. inline constexpr WmmaRule wmma_rules_gfx1150_f16[] = { {8, {k_lt(3072, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 1, 8, 2}}, @@ -273,6 +293,12 @@ template <> struct WmmaTileRules<1100> { static constexpr const auto& f32 = wmma_rules_gfx1100_f32; }; +template <> struct WmmaTileRules<1101> { + static constexpr int owner = 1101; + static constexpr const auto& f16 = wmma_rules_gfx1101_f16; + static constexpr const auto& f32 = wmma_rules_gfx1101_f32; +}; + template <> struct WmmaTileRules<1150> { static constexpr int owner = 1150; static constexpr const auto& f16 = wmma_rules_gfx1150_f16; From 86329ae370bb1e003d03ff349a8bf1754c8f99b6 Mon Sep 17 00:00:00 2001 From: sstamenk Date: Thu, 19 Nov 2026 23:24:06 +0100 Subject: [PATCH 08/10] [ROCm] WMMA 4-bit GEMM: own tunings for gfx1102 gfx1102 (RX 7600 XT: 32 CUs, 288 GB/s, 32 MB Infinity Cache) used the gfx1100 (W7900, 96 CUs) rules unmeasured. Measured at pinned clocks over the 40 shapes: - Tile rules: own tile tables (WmmaTileRules<1102>; gfx11 kernels and gfx1100 block order through the family fallback). bf16/fp16: the gfx1100 table was 8-19% off the best swept tile at M <= 64; M <= 64 is refitted (1.9-5.3%), with an N < 1024 leaf at M = 17-48 for small GQA k/v. M > 64 keeps the gfx1100 tiles. Default dispatch vs the gfx1100 table (A1/B1/A2/B2, repeats within 0.7%): 1.07-1.08x faster at M = 1-8, 1.11-1.12x at 9-16, 1.14-1.15x at 17-32, 1.04-1.05x at 33-48, 1.06x at 49-64, bf16 and fp16 alike; single shapes up to 1.17x slower (qwen3-14b o/q at M = 8, small GQA k/v 1.14x at M = 9-16 and 49-64). fp32: M = 9-24 is refitted (gfx1100 tiles 12% and 4.6% off the best swept tile; dispatch 1.10-1.11x faster at M = 9-16, 1.03x at 17-24); the other buckets keep the gfx1100 tiles. - fp32 SIMT/WMMA cutoffs (WmmaFp32Cutoffs<1102>): the gfx1100 table plus WMMA for N >= 8192 at M = 4, 1.06x faster in total there (in-process interleaved: 0.942x the time); other M within 0.9% of the per-shape oracle. bf16/fp16 keep WMMA at M = 1 (with the new tiles ~5% faster than SIMT). - Python M limit: gfx1102 now through M = 512 for all dtypes (gfx1100: 384, fp32 128). bf16/fp16 at M = 385-512 are 1.19-1.42x faster in total than dequant + F.linear and ahead on 24-36 of the 40 shapes (blocksize 32 at M ~512: still ~8% less total time, but ahead on only 19-21 shapes); fp32 is 2.4-2.7x faster at M = 129-512 and ahead on every shape (fp32 GEMM on this ROCm 10.2 nightly goes through hipBLAS/rocBLAS at ~1.9 TFLOPS; torch does not use hipBLASLt on gfx1102). Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 1 + csrc/gemm_4bit_wmma_rules.cuh | 34 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 39e50c2d2..2c3fb9455 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -822,6 +822,7 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): _ROCM_WMMA_MAX_M = { "gfx1100": (384, 128), # W7900 "gfx1101": (448, 512), # RX 7700 XT + "gfx1102": (512, 512), # RX 7600 XT "gfx1103": (384, 384), # Radeon 760M "gfx1151": (512, 512), # Radeon 8060S "gfx1200": (512, 512), # RX 9060 XT diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index 6962e5872..8dea15a74 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -35,6 +35,9 @@ struct WmmaFp32Cutoff { // clang-format off /// gfx1100: SIMT through M = 4, then WMMA by N; N < 1024 stays on SIMT through M = 64. inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1100[] = {{4, INT_MAX}, {5, 3072}, {7, 2816}, {8, 2048}, {12, 2816}, {64, 1024}}; +/// gfx1102: the gfx1100 cutoffs, but WMMA for N >= 8192 already at M = 4. +inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1102[] = { + {3, INT_MAX}, {4, 8192}, {5, 3072}, {7, 2816}, {8, 2048}, {12, 2816}, {64, 1024}}; /// gfx1103: SIMT through M = 2, WMMA from M = 3 (N >= 3840 through M = 4). inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1103[] = {{2, INT_MAX}, {4, 3840}}; /// gfx1151: SIMT through M = 3, then WMMA by N through M = 7. @@ -50,6 +53,10 @@ template <> struct WmmaFp32Cutoffs<1100> { static constexpr const auto& table = wmma_fp32_cutoffs_gfx1100; }; +template <> struct WmmaFp32Cutoffs<1102> { + static constexpr const auto& table = wmma_fp32_cutoffs_gfx1102; +}; + template <> struct WmmaFp32Cutoffs<1103> { static constexpr const auto& table = wmma_fp32_cutoffs_gfx1103; }; @@ -199,6 +206,27 @@ inline constexpr WmmaRule wmma_rules_gfx1101_f32[] = { {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, }; +/// gfx1102 bf16/fp16: own tiles through M = 64 (fewer warps along N, more rows per warp than gfx1100), the +/// gfx1100 tiles above. N < 1024 at M = 17-48 uses split-K 4. +inline constexpr WmmaRule wmma_rules_gfx1102_f16[] = { + {8, {k_lt(3840, {1, 2, 1, 1, 8, 1}), k_lt(14336, {1, 1, 1, 1, 4, 2})}, {1, 1, 1, 1, 8, 2}}, + {16, {n_lt(3072, {2, 2, 1, 1, 4, 1}), n_lt(5376, {2, 1, 1, 4, 1, 2})}, {2, 1, 1, 2, 2, 2}}, + {32, {n_lt(1024, {2, 1, 1, 2, 4, 2}), n_lt(3840, {4, 1, 1, 2, 2, 1}), n_lt(5376, {4, 1, 1, 4, 1, 2})}, {4, 2, 1, 4, 1, 2}}, + {48, {n_lt(1024, {2, 1, 1, 2, 4, 2}), k_lt(2560, {2, 2, 1, 2, 2, 1}), k_lt(8192, {2, 2, 1, 4, 1, 2})}, {2, 2, 1, 2, 2, 2}}, + {64, {k_lt(2560, {4, 1, 1, 4, 2, 1}), k_lt(6144, {4, 2, 1, 4, 1, 2})}, {4, 2, 1, 4, 2, 2}}, + {96, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(8192, {4, 2, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {4, 1, 1, 4, 2, 2}), n_lt(3072, {4, 2, 1, 4, 2, 1})}, {4, 2, 1, 4, 1, 2}}, +}; + +/// gfx1102 fp32: the gfx1100 table with its own M = 9-24 buckets. +inline constexpr WmmaRule wmma_rules_gfx1102_f32[] = { + {8, {n_lt(3840, {1, 1, 1, 1, 4, 1}), n_lt(5120, {1, 1, 1, 2, 2, 2})}, {1, 2, 1, 2, 2, 2}}, + {16, {n_lt(3840, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {24, {n_lt(3072, {1, 1, 1, 2, 2, 1}), n_lt(8192, {1, 2, 1, 2, 2, 2})}, {2, 2, 1, 4, 1, 2}}, + {48, {n_lt(2560, {1, 2, 1, 2, 2, 2}), n_lt(5376, {2, 2, 1, 2, 2, 1})}, {2, 2, 1, 4, 1, 2}}, + {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, +}; + /// gfx1150 bf16/fp16. At M = 17-64 the first leaf gives narrow N (MoE experts, GQA k/v) its own tile. inline constexpr WmmaRule wmma_rules_gfx1150_f16[] = { {8, {k_lt(3072, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 1, 8, 2}}, @@ -299,6 +327,12 @@ template <> struct WmmaTileRules<1101> { static constexpr const auto& f32 = wmma_rules_gfx1101_f32; }; +template <> struct WmmaTileRules<1102> { + static constexpr int owner = 1102; + static constexpr const auto& f16 = wmma_rules_gfx1102_f16; + static constexpr const auto& f32 = wmma_rules_gfx1102_f32; +}; + template <> struct WmmaTileRules<1150> { static constexpr int owner = 1150; static constexpr const auto& f16 = wmma_rules_gfx1150_f16; From d134bba310e1abe3cc5c7359b4883ed38a04b075 Mon Sep 17 00:00:00 2001 From: sstamenk Date: Tue, 24 Nov 2026 04:17:45 +0100 Subject: [PATCH 09/10] [ROCm] WMMA 4-bit GEMM: own tunings for gfx1103 gfx1103 (Radeon 760M: 8 CUs, no Infinity Cache) used the gfx1100 (W7900) tile tables with its own fp32 cutoffs and M limits; those came from a 760M with one DDR5-5600 SO-DIMM (44.8 GB/s). Measured at pinned clocks over the 40 shapes on a second 760M with 128-bit LPDDR5X-7500 (120 GB/s): - Tile rules: own tile tables (WmmaTileRules<1103>; gfx11 kernels and the gfx1100 block order through the family fallback). bf16/fp16: the gfx1100 table was 22-26% off the best swept tile at M <= 32 and 9% at M = 33-64. M <= 64 is refitted; above, the gfx1100 tiles stay (M = 65-96: one tile would gain 3.0% in fp16 but 2.6% in bf16, under the bar; M > 96: 1.4% off). Default dispatch vs the gfx1100 table (in-process interleaved, 5 cycles, fp16 and bf16 alike): 1.24x faster at M = 1-8, 1.16x at 9-16, 1.10x at 17-32, 1.08x at 33-48, 1.09x at 49-64. Every (shape, M) cell whose tile changes is faster; the cells that keep their tile read 0.94-1.07x (same kernel; two of 1180 above 1.02x, 1.00x and 0.99x when measured again). The table is not the blocksize-64 fit on the new machine alone (the fit takes 0.5%, 2.6% and 9.0% less time there at M = 1-8, 9-16 and 17-32). At blocksize 32 the fit's M = 17-32 tiles are 1.06x slower than the gfx1100 table (1.6x on one shape) where this table is 1.06x faster. At M <= 16 the choice is the more conservative one because the first machine's one 5-shape sweep (a risk signal, not repeatable) loses 4.0% and 5.8% against the gfx1100 table with the fit and -0.5% and +2.6% with this table. At blocksize 32 and M = 9-16 this table gains 5% instead of 14%, with five shapes 2-10% slower than with the gfx1100 table. fp32: one tile through M = 8 and one 16-row tile above (the gfx1100 tiles were 5-17% off the best swept tile at M <= 48 and 8% at M >= 64). Default dispatch: 1.03x faster at M = 3-4, 1.06x at 5-8, 1.17x at 9-16, 1.08x at 17-24, 1.05x at 25-48, 1.08x at multiples of 32 above (up to 1.29x in between), every shape faster from M = 49. - fp32 SIMT/WMMA cutoffs: unchanged (within 1.1% of the per-shape oracle at M = 3-4 with the new tiles, 5.5% at M = 2; the best single cutoff per M would gain 0.3-2.5%). - Python M limit: 512 for all dtypes (was 384). At M = 416-512 the fused kernel is 1.71-1.81x (fp16) and 1.69-1.81x (bf16) faster in total than dequant + F.linear and ahead on 33-37 of the 40 shapes (blocksize 32 at M = 512: 1.57x / 1.63x, 29 / 27 shapes); fp32 is 2.9x faster and ahead on every shape. Single small MoE / dense projections are more than 1.2x slower than dequant there (up to about 1.5x; at blocksize 32 and M = 512 four shapes per dtype, gate_up layers included); a per-shape fallback would recover at most 0.35% of the total. Co-Authored-By: Claude Fable 5.2 --- bitsandbytes/backends/cuda/ops.py | 2 +- csrc/gemm_4bit_wmma_rules.cuh | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 2c3fb9455..7be1e7b98 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -823,7 +823,7 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): "gfx1100": (384, 128), # W7900 "gfx1101": (448, 512), # RX 7700 XT "gfx1102": (512, 512), # RX 7600 XT - "gfx1103": (384, 384), # Radeon 760M + "gfx1103": (512, 512), # Radeon 760M "gfx1151": (512, 512), # Radeon 8060S "gfx1200": (512, 512), # RX 9060 XT "gfx1201": (384, 512), # R9700 diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index 8dea15a74..3daa9d630 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -227,6 +227,23 @@ inline constexpr WmmaRule wmma_rules_gfx1102_f32[] = { {INT_MAX, {}, {4, 1, 1, 4, 1, 1}}, }; +/// gfx1103 bf16/fp16: own tiles through M = 64, the gfx1100 tiles above. +inline constexpr WmmaRule wmma_rules_gfx1103_f16[] = { + {8, {k_lt(8192, {1, 2, 1, 1, 4, 2})}, {1, 2, 1, 1, 8, 2}}, + {16, {}, {2, 1, 1, 4, 2, 2}}, + {32, {}, {4, 1, 1, 4, 2, 2}}, + {48, {k_lt(12288, {2, 2, 1, 4, 1, 2})}, {4, 2, 1, 4, 1, 2}}, + {64, {}, {4, 2, 1, 4, 1, 2}}, + {96, {n_lt(3072, {4, 1, 1, 2, 4, 1}), n_lt(8192, {4, 2, 1, 4, 2, 2})}, {4, 2, 1, 4, 1, 2}}, + {INT_MAX, {n_lt(2816, {4, 1, 1, 4, 2, 2}), n_lt(3072, {4, 2, 1, 4, 2, 1})}, {4, 2, 1, 4, 1, 2}}, +}; + +/// gfx1103 fp32: one tile through M = 8 and one above. +inline constexpr WmmaRule wmma_rules_gfx1103_f32[] = { + {8, {}, {1, 2, 1, 2, 2, 2}}, + {INT_MAX, {}, {2, 2, 1, 4, 1, 2}}, +}; + /// gfx1150 bf16/fp16. At M = 17-64 the first leaf gives narrow N (MoE experts, GQA k/v) its own tile. inline constexpr WmmaRule wmma_rules_gfx1150_f16[] = { {8, {k_lt(3072, {1, 1, 1, 1, 8, 1})}, {1, 1, 1, 1, 8, 2}}, @@ -311,7 +328,7 @@ inline constexpr WmmaRule wmma_rules_gfx1201_f32[] = { // clang-format on -/// The tile rule tables of a target: its own where it has them, else its family main's (gfx1103 uses gfx1100's). +/// The tile rule tables of a target: its own where it has them, else its family main's (gfx1152 uses gfx1151's). /// `owner` is the target whose tables they are, so targets sharing tables share one launcher instantiation. template struct WmmaTileRules : WmmaTileRules {}; @@ -333,6 +350,12 @@ template <> struct WmmaTileRules<1102> { static constexpr const auto& f32 = wmma_rules_gfx1102_f32; }; +template <> struct WmmaTileRules<1103> { + static constexpr int owner = 1103; + static constexpr const auto& f16 = wmma_rules_gfx1103_f16; + static constexpr const auto& f32 = wmma_rules_gfx1103_f32; +}; + template <> struct WmmaTileRules<1150> { static constexpr int owner = 1150; static constexpr const auto& f16 = wmma_rules_gfx1150_f16; From 8c13ff0da66e7fee223549648097759d2edd640b Mon Sep 17 00:00:00 2001 From: sstamenk Date: Tue, 24 Nov 2026 17:15:23 +0100 Subject: [PATCH 10/10] [ROCm] WMMA 4-bit GEMM: declare a fallback target per chip, gfx1152/gfx1153 use gfx1103 A chip without tunings of its own used the main chip of its family (gfx1100, gfx1151, gfx1201). Replace that with an explicit fallback per target (wmma_fallback in gemm_4bit_wmma_rules.cuh, _ROCM_WMMA_FALLBACK in ops.py): gfx1101 -> gfx1100, gfx1150 -> gfx1151 and gfx1200 -> gfx1201 as before, and gfx1152 / gfx1153 -> gfx1103 instead of gfx1151. A target that has no fallback and lacks a specialization does not compile. gfx1152 (Radeon 860M/840M) is a small RDNA3.5 iGPU: 4-8 CUs, 128-bit LPDDR5X, 2 MB L2, no Infinity Cache, 1024 VGPRs per SIMD, like the Radeon 760M the gfx1103 tables were fitted on (gfx1151, the 8060S: 40 CUs, 256-bit, 32 MB MALL, 1536 VGPRs). gfx1153 has the same 1024-VGPR register file in LLVM and follows gfx1152. On the 760M's tile sweeps the gfx1151 fp16 table is 24-31% off the best tile at M <= 16 and 12-25% above M = 64. Neither chip was measured: their tiles, fp32 cutoffs and M limits (512/512, as before) now come from gfx1103. The block order follows the target whose tile tables run (fp32 N-first with gfx110x tables), so gfx1152/gfx1153 get the order gfx1103's tables were fitted with. Every other target's tile picks, SIMT/WMMA choices, block order and M limits are unchanged. Co-Authored-By: Claude Opus 5.5 --- bitsandbytes/backends/cuda/ops.py | 24 +++++++++++++--------- csrc/gemm_4bit_wmma.cu | 6 +++--- csrc/gemm_4bit_wmma_rules.cuh | 34 +++++++++++++++++++++---------- 3 files changed, 40 insertions(+), 24 deletions(-) diff --git a/bitsandbytes/backends/cuda/ops.py b/bitsandbytes/backends/cuda/ops.py index 7be1e7b98..ee3550a89 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -811,12 +811,17 @@ def _gemm_4bit_use_custom_cuda(device_index, dtype, M, N, K): return M <= (16 if (tall_k_2xn or n_blocks < 48) else 8) -# WMMA kernel targets (csrc/gemm_4bit_wmma_rules.cuh) and the main chip of their family, whose limits a chip uses -# where it has none of its own. -_ROCM_WMMA_FAMILY_MAIN = { - **dict.fromkeys(("gfx1100", "gfx1101", "gfx1102", "gfx1103"), "gfx1100"), - **dict.fromkeys(("gfx1150", "gfx1151", "gfx1152", "gfx1153"), "gfx1151"), - **dict.fromkeys(("gfx1200", "gfx1201"), "gfx1201"), +# WMMA kernel targets (csrc/gemm_4bit_wmma_rules.cuh). +_ROCM_WMMA_TARGETS = frozenset( + ("gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1153", "gfx1200", "gfx1201") +) +# The target whose limits a target uses where it has none of its own (as wmma_fallback in the rules header). +_ROCM_WMMA_FALLBACK = { + "gfx1101": "gfx1100", + "gfx1150": "gfx1151", + "gfx1152": "gfx1103", + "gfx1153": "gfx1103", + "gfx1200": "gfx1201", } # Largest M on the fused path per WMMA target: (bf16/fp16, fp32). _ROCM_WMMA_MAX_M = { @@ -837,7 +842,7 @@ def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): RDNA3/RDNA3.5/RDNA4 with K % 64 == 0 have a WMMA kernel (the C dispatch picks SIMT or WMMA), which stays ahead of dequant+F.linear up to the limits in _ROCM_WMMA_MAX_M; a chip without its own - entry uses its family main's (_ROCM_WMMA_FAMILY_MAIN). + entry uses its fallback's (_ROCM_WMMA_FALLBACK). Otherwise (K % 64 != 0) gfx11/gfx12 keep SIMT through M=8. gfx125x (CDNA5) is Wave32 but lacks the v_dot2 SIMT instructions, so its kernel takes the fp32-FMA CDNA math path; it keeps the gfx12 default (M<=8) pending calibration. CDNA/gfx9 is calibrated on MI308X (gfx942): bf16/fp16 win through @@ -849,9 +854,8 @@ def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): return True arch = _rocm_gfx_arch(device_index) - family_main = _ROCM_WMMA_FAMILY_MAIN.get(arch) - if family_main is not None and K % 64 == 0: # WMMA kernel - max_m = _ROCM_WMMA_MAX_M.get(arch, _ROCM_WMMA_MAX_M[family_main]) + if arch in _ROCM_WMMA_TARGETS and K % 64 == 0: # WMMA kernel + max_m = _ROCM_WMMA_MAX_M.get(arch) or _ROCM_WMMA_MAX_M[_ROCM_WMMA_FALLBACK[arch]] return M <= max_m[dtype == torch.float32] if arch.startswith("gfx11") or arch.startswith("gfx12"): # RDNA3 / RDNA4 / CDNA5 (gfx125x) return M <= 8 diff --git a/csrc/gemm_4bit_wmma.cu b/csrc/gemm_4bit_wmma.cu index 9db2da152..4efdbc7bb 100644 --- a/csrc/gemm_4bit_wmma.cu +++ b/csrc/gemm_4bit_wmma.cu @@ -659,9 +659,9 @@ int wmma_device_arch() { } /// Whether blocks walk the row tiles of the same N columns first, so they share B in L2 -/// (see gemm_4bit_wmma_body). Only matters with two or more row tiles. fp32 on gfx110x -/// stays N-first. The tile rules are fitted with this order. -bool wmma_row_tiles_first(int target, bool fp32) { return wmma_family_main(target) == 1100 ? !fp32 : true; } +/// (see gemm_4bit_wmma_body), for the tile tables of `owner`. Only matters with two or more row +/// tiles. fp32 with gfx110x tables stays N-first. The tile rules are fitted with this order. +bool wmma_row_tiles_first(int owner, bool fp32) { return owner >= 1150 || !fp32; } /// Launch one tile configuration. KCH_MAX is lowered to 1 when K is not a multiple /// of 128; one absmax covers each half-wave's per-iteration K slice when diff --git a/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh index 3daa9d630..4839e6bb9 100644 --- a/csrc/gemm_4bit_wmma_rules.cuh +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -1,6 +1,6 @@ #pragma once // AMD WMMA 4-bit GEMM tuning rules per gfx target: SIMT or WMMA, and the WMMA tile. A target without its own -// specialization below uses its family main's (wmma_family_main). +// specialization below uses its fallback target's (wmma_fallback). #include #include @@ -14,13 +14,21 @@ inline constexpr int WMMA_TARGETS[] = {1100, 1101, 1102, 1103, 1150, 1151, 1152, /// WMMA generation (kernel family): gfx120x runs the gfx12 kernels, gfx110x and gfx115x the gfx11 kernels. constexpr int wmma_gen(int target) { return target >= 1200 ? 12 : 11; } -/// The main target of a chip's family, whose tunings it uses where it has none of its own. -constexpr int wmma_family_main(int target) { - if (target >= 1200) - return 1201; - if (target >= 1150) +/// The target whose tunings a target uses where it has none of its own (0: it has all of its own). +constexpr int wmma_fallback(int target) { + switch (target) { + case 1101: + return 1100; + case 1150: return 1151; - return 1100; + case 1152: + case 1153: + return 1103; + case 1200: + return 1201; + default: + return 0; + } } // --------------------------------------------------------------------------------------------------------------- @@ -46,8 +54,10 @@ inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1151[] = {{3, INT_MAX}, {5, inline constexpr WmmaFp32Cutoff wmma_fp32_cutoffs_gfx1201[] = {{4, INT_MAX}, {5, 8192}, {6, 4096}, {9, 2048}, {15, 1408}, {31, 1024}}; // clang-format on -/// The fp32 cutoffs of a target: its own where it has them, else its family main's. -template struct WmmaFp32Cutoffs : WmmaFp32Cutoffs {}; +/// The fp32 cutoffs of a target: its own where it has them, else its fallback's. +template struct WmmaFp32Cutoffs : WmmaFp32Cutoffs {}; + +template <> struct WmmaFp32Cutoffs<0>; // a target without cutoffs of its own needs a fallback template <> struct WmmaFp32Cutoffs<1100> { static constexpr const auto& table = wmma_fp32_cutoffs_gfx1100; @@ -328,9 +338,11 @@ inline constexpr WmmaRule wmma_rules_gfx1201_f32[] = { // clang-format on -/// The tile rule tables of a target: its own where it has them, else its family main's (gfx1152 uses gfx1151's). +/// The tile rule tables of a target: its own where it has them, else its fallback's. /// `owner` is the target whose tables they are, so targets sharing tables share one launcher instantiation. -template struct WmmaTileRules : WmmaTileRules {}; +template struct WmmaTileRules : WmmaTileRules {}; + +template <> struct WmmaTileRules<0>; // a target without tile tables of its own needs a fallback template <> struct WmmaTileRules<1100> { static constexpr int owner = 1100;