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..ee3550a89 100644 --- a/bitsandbytes/backends/cuda/ops.py +++ b/bitsandbytes/backends/cuda/ops.py @@ -811,24 +811,52 @@ 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). +_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 = { + "gfx1100": (384, 128), # W7900 + "gfx1101": (448, 512), # RX 7700 XT + "gfx1102": (512, 512), # RX 7600 XT + "gfx1103": (512, 512), # Radeon 760M + "gfx1151": (512, 512), # Radeon 8060S + "gfx1200": (512, 512), # RX 9060 XT + "gfx1201": (384, 512), # R9700 +} + + @functools.cache def _gemm_4bit_use_custom_rocm(device_index, dtype, M, N, K): """ - Fused SIMT kernel vs dequant+F.linear heuristic for ROCm. + Fused custom 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. + 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 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 + M<=4 after the SIMT math-path tuning, fp32 only through M<=2. - TODO: revisit once WMMA/MFMA kernels land; calibrate the gfx125x crossover. + 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 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 if arch.startswith("gfx9"): # CDNA1-4 / MI-series (Wave64) @@ -917,7 +945,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 +954,8 @@ 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; this is the largest of them. + _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..49c928c3f 100644 --- a/csrc/gemm_4bit.cu +++ b/csrc/gemm_4bit.cu @@ -1,5 +1,5 @@ // 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 @@ -7,6 +7,10 @@ #include "compat.cuh" #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. #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,19 @@ 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; 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; + 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 + )) + 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..4efdbc7bb --- /dev/null +++ b/csrc/gemm_4bit_wmma.cu @@ -0,0 +1,878 @@ +// 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" + +// 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. 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 IS_RDNA4 || defined(__gfx12_generic__) +#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; } + +// 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_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 + ); + } 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_DEVICE_ARCH == 12 + 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. 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; +#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 = 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_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 + ); + 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++) + // 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]; + } + }; + + 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-"): 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) { + 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; +} + +// 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), 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 +/// 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 + ); +} + +/// 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() { + 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). +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( + 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 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); + 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 + ); +} + +/// 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 target 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 +) { + 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( + 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..6127a9ff8 --- /dev/null +++ b/csrc/gemm_4bit_wmma.cuh @@ -0,0 +1,22 @@ +#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), 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 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. +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/csrc/gemm_4bit_wmma_rules.cuh b/csrc/gemm_4bit_wmma_rules.cuh new file mode 100644 index 000000000..4839e6bb9 --- /dev/null +++ b/csrc/gemm_4bit_wmma_rules.cuh @@ -0,0 +1,393 @@ +#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 fallback target's (wmma_fallback). + +#include +#include +#include +#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 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; + case 1152: + case 1153: + return 1103; + case 1200: + return 1201; + default: + return 0; + } +} + +// --------------------------------------------------------------------------------------------------------------- +// 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 +/// 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. +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 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; +}; + +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; +}; + +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) + 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. +template constexpr bool wmma_preferred_for(bool fp32, int M, int N) { + if (!fp32) + 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{}); +} + +// --------------------------------------------------------------------------------------------------------------- +// 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 + +/// 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_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}}, + {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}}, +}; + +/// 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}}, + {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}}, +}; + +/// 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}}, +}; + +/// 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}}, +}; + +/// 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}}, + {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}}, + {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}}, +}; + +/// 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}}, + {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}}, +}; + +/// 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[] = { + {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}}, +}; + +/// 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}}, + {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 + +/// 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<0>; // a target without tile tables of its own needs a fallback + +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<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<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<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; + 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; + 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; + static constexpr const auto& f32 = wmma_rules_gfx1201_f32; +}; diff --git a/tests/test_functional.py b/tests/test_functional.py index e4cd6a128..0d6eebd35 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: 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 ] @@ -1012,6 +1018,53 @@ 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 != "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) + # 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