#include "mmq-few.cuh" #include "cp-async.cuh" #include "mma.cuh" #include "mmvq.cuh" #include "quantize.cuh" #include "vecdotq.cuh" #include // mul_mat_q_few for NVIDIA uses the int8 MMA fragment layout and cp.async, mul_mat_q_few_wmma for RDNA the WMMA layout. Not on MUSA. #if !defined(GGML_USE_MUSA) using namespace ggml_cuda_mma; // Few-row MMQ: int8 MMA mat-mul for 2-24 src1 columns (block scaled FP4 MMA for NVFP4 with 4-bit src1, FP16 MMA with FP16 src1 for F8_E4M3). // A CUDA block has 16 src0 rows (32 for 2 column groups on large matrices, not with 4-bit src1). // Its warps split K in units of 256 values and copy raw src0 rows into their own cp.async ring, src1 is quantized to the MMA fragment layout. // MUL_MAT_ID: one column group per expert and CUDA block, for short rows the warps split the rows instead of K (64 rows per block). static constexpr int MMQ_FEW_MAX_NCG = 3; // max. number of column groups static constexpr int MMQ_FEW_NROWS = 16; // src0 rows of one MMA tile static constexpr int MMQ_FEW_NWARPS = 4; template static constexpr __host__ __device__ int mmq_few_unit_size_of() { return QK_K/ggml_cuda_type_traits::qk*ggml_cuda_type_traits::bs; } // src0 bytes per 256 values, 0 for the types without a few-row decoder. static constexpr __host__ __device__ int mmq_few_unit_size(const ggml_type type) { switch (type) { case GGML_TYPE_Q8_0: return mmq_few_unit_size_of(); case GGML_TYPE_Q3_K: return mmq_few_unit_size_of(); case GGML_TYPE_Q4_K: return mmq_few_unit_size_of(); case GGML_TYPE_Q5_K: return mmq_few_unit_size_of(); case GGML_TYPE_Q6_K: return mmq_few_unit_size_of(); case GGML_TYPE_IQ3_S: return mmq_few_unit_size_of(); case GGML_TYPE_IQ4_NL: return mmq_few_unit_size_of(); case GGML_TYPE_IQ4_XS: return mmq_few_unit_size_of(); case GGML_TYPE_NVFP4: return mmq_few_unit_size_of(); case GGML_TYPE_F8_E4M3: return QK_K; default: return 0; } } // Q4_K and Q5_K also need the src1 sums for their mins. static constexpr __host__ __device__ mmq_q8_1_ds_layout mmq_few_ds_layout(const ggml_type type) { return type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K ? MMQ_Q8_1_DS_LAYOUT_DS4 : MMQ_Q8_1_DS_LAYOUT_D4; } // Units of 256 values per ring stage: 1 for Q6_K, 3 column groups (fewer free registers) and 32-row tiles (2 blocks per SM), else 2. // fp4: NVFP4 with 4-bit src1, which has enough free registers for 2 units with 3 column groups. // F8_E4M3: 1 unit, else a block needs 72 KB of shared memory and only one fits into an SM. static constexpr __host__ __device__ int mmq_few_nunits_stage(const ggml_type type, const int ncg, const int nmt, const bool fp4) { return type == GGML_TYPE_Q6_K || type == GGML_TYPE_F8_E4M3 || (ncg > 2 && !fp4) || nmt > 1 ? 1 : 2; } // A third ring stage only makes Q6_K faster, the other types get slower on large matrices. static constexpr __host__ __device__ int mmq_few_nstages(const ggml_type type) { return type == GGML_TYPE_Q6_K ? 3 : 2; } // The src0 data of a ring stage does not fill whole 16 byte chunks, it is copied from the preceding 16 byte boundary. static constexpr __host__ __device__ bool mmq_few_unaligned(const ggml_type type, const int nunits_stage) { return (nunits_stage*mmq_few_unit_size(type)) % 16 != 0; } // for unaligned data the max. over the 8 possible start offsets static constexpr __host__ __device__ int mmq_few_nchunks(const ggml_type type, const int nunits_stage) { const int nbytes = nunits_stage*mmq_few_unit_size(type); return mmq_few_unaligned(type, nunits_stage) ? (14 + nbytes + 15)/16 : nbytes/16; } // Unaligned rows are padded to an odd number of 16 byte chunks against bank conflicts, for aligned rows the padding costs more than it saves. // F8_E4M3: the 8 lanes of each phase of a 16-byte load read 64 bytes from each of 2 adjacent rows, a padding of 64 bytes puts the 2 rows into different banks. static constexpr __host__ __device__ int mmq_few_sram_stride(const ggml_type type, const int nunits_stage) { const int nchunks = mmq_few_nchunks(type, nunits_stage); if (type == GGML_TYPE_F8_E4M3) { return 16*nchunks + 64; } return mmq_few_unaligned(type, nunits_stage) && nchunks % 2 == 0 ? 16*(nchunks + 1) : 16*nchunks; } static constexpr __host__ __device__ int mmq_few_nbytes_shared(const ggml_type type, const int ncg, const int nmt, const bool fp4) { return MMQ_FEW_NWARPS*mmq_few_nstages(type)*nmt*MMQ_FEW_NROWS*mmq_few_sram_stride(type, mmq_few_nunits_stage(type, ncg, nmt, fp4)); } // With Q6_K and Q8_0 two CUDA blocks with 32-row tiles would not fit into an SM. static constexpr __host__ __device__ bool mmq_few_tall_supported(const ggml_type type) { return type == GGML_TYPE_Q3_K || type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_NVFP4; } // The MUL_MAT_ID src1 quantizer keeps the natural value order, the NVFP4 decoder needs the nvfp4 order (see quantize_mmq_few_q8_1). // F8_E4M3 needs FP16 src1, which has no MUL_MAT_ID quantizer. static constexpr __host__ __device__ bool mmq_few_id_supported(const ggml_type type) { return type != GGML_TYPE_NVFP4 && type != GGML_TYPE_F8_E4M3; } // MUL_MAT_ID with fewer than 2 units of 256 values per warp: the warps split the rows, each warp has its own 16 rows. static constexpr __host__ __device__ bool mmq_few_ksplit(const bool has_ids, const int nunits) { return !has_ids || nunits >= 2*MMQ_FEW_NWARPS; } #if defined(CP_ASYNC_AVAILABLE) // The src1 fragments of a lane for one unit of 256 values, see quantize.cuh. struct mmq_few_y_frag { int4 qs[4]; int4 ds[4]; }; static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_frag & yf, const int4 * y) { #pragma unroll for (int j = 0; j < 4; ++j) { yf.qs[j] = y[j*WARP_SIZE + threadIdx.x]; } #pragma unroll for (int j = 0; j < 4; ++j) { yf.ds[j] = y[4*WARP_SIZE + 4*(threadIdx.x % 4) + j]; } } // The src1 fragments of a lane for NVFP4 with 4-bit src1, see MMQ_FEW_FP4_INT4: the B fragments of the 4 blocks of 64 values and the scales of column g. struct mmq_few_y_fp4 { int4 qs[2]; int4 sc; }; static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_fp4 & yf, const int4 * y) { yf.qs[0] = y[threadIdx.x]; yf.qs[1] = y[WARP_SIZE + threadIdx.x]; yf.sc = y[2*WARP_SIZE + threadIdx.x/4]; } // The src1 fragments of a lane for F8_E4M3, see MMQ_FEW_F16_INT4: the B fragments of the 4 blocks of 64 values and the scales of the columns 2t and 2t + 1. struct mmq_few_y_f16 { int4 h[8]; float2 d; }; static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_f16 & yf, const int4 * y) { #pragma unroll for (int j = 0; j < 8; ++j) { yf.h[j] = y[j*WARP_SIZE + threadIdx.x]; } yf.d = ((const float2 *) (y + 8*WARP_SIZE))[threadIdx.x % 4]; } static __device__ __forceinline__ int2 mmq_few_get_b(const mmq_few_y_frag & yf, const int s) { const int4 q = yf.qs[s/2]; return s % 2 == 0 ? make_int2(q.x, q.y) : make_int2(q.z, q.w); } template static __device__ __forceinline__ float2 mmq_few_get_d(const mmq_few_y_frag & yf, const int s) { if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) { const float * d = (const float *) &yf.ds[s/2]; return make_float2(d[2*(s % 2) + 0], d[2*(s % 2) + 1]); } else { const half2 * ds = (const half2 *) &yf.ds[s/2]; return make_float2(__low2float(ds[2*(s % 2) + 0]), __low2float(ds[2*(s % 2) + 1])); } } static __device__ __forceinline__ float2 mmq_few_get_sum(const mmq_few_y_frag & yf, const int s) { const half2 * ds = (const half2 *) &yf.ds[s/2]; return make_float2(__high2float(ds[2*(s % 2) + 0]), __high2float(ds[2*(s % 2) + 1])); } // C.x[0], C.x[1]: row g, columns 2t and 2t+1. C.x[2], C.x[3]: row g+8. static __device__ __forceinline__ tile<16, 8, int> mmq_few_mma(const int (&lo)[2], const int (&hi)[2], const int2 b) { tile<16, 8, int> A; A.x[0] = lo[0]; A.x[1] = lo[1]; A.x[2] = hi[0]; A.x[3] = hi[1]; tile<8, 8, int> B; B.x[0] = b.x; B.x[1] = b.y; tile<16, 8, int> C; mma(C, A, B); return C; } static __device__ __forceinline__ tile<16, 8, int> mmq_few_mma_k16(const int (&a)[2], const int b) { tile<16, 4, int> A; A.x[0] = a[0]; A.x[1] = a[1]; tile<8, 4, int> B; B.x[0] = b; tile<16, 8, int> C; mma(C, A, B); return C; } // sum_d += d * (C * ls) of sub-block s for all column groups, ls are the src0 row scales template static __device__ __forceinline__ void mmq_few_mma_add( const int (&lo)[2], const int (&hi)[2], const scale_t (&ls)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) { #pragma unroll for (int c = 0; c < ncg; ++c) { const tile<16, 8, int> C = mmq_few_mma(lo, hi, mmq_few_get_b(yf[c], s)); const float2 d = mmq_few_get_d(yf[c], s); sum_d[c][0] += d.x * float(C.x[0]*ls[0]); sum_d[c][1] += d.y * float(C.x[1]*ls[0]); sum_d[c][2] += d.x * float(C.x[2]*ls[1]); sum_d[c][3] += d.y * float(C.x[3]*ls[1]); } } // Same with one k=16 MMA per half of sub-block s, sc_lo and sc_hi are the scales of the halves (int, or float for NVFP4). template static __device__ __forceinline__ void mmq_few_mma_k16_add( const int (&lo)[2], const int (&hi)[2], const scale_t (&sc_lo)[2], const scale_t (&sc_hi)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) { #pragma unroll for (int c = 0; c < ncg; ++c) { const int2 b = mmq_few_get_b(yf[c], s); const tile<16, 8, int> C_lo = mmq_few_mma_k16(lo, b.x); const tile<16, 8, int> C_hi = mmq_few_mma_k16(hi, b.y); const float2 d = mmq_few_get_d(yf[c], s); sum_d[c][0] += d.x * float(C_lo.x[0]*sc_lo[0] + C_hi.x[0]*sc_hi[0]); sum_d[c][1] += d.y * float(C_lo.x[1]*sc_lo[0] + C_hi.x[1]*sc_hi[0]); sum_d[c][2] += d.x * float(C_lo.x[2]*sc_lo[1] + C_hi.x[2]*sc_hi[1]); sum_d[c][3] += d.y * float(C_lo.x[3]*sc_lo[1] + C_hi.x[3]*sc_hi[1]); } } // The int8 scales of the halves are bytes 0 and 1 of sc[r]. template static __device__ __forceinline__ void mmq_few_mma_k16_add( const int (&lo)[2], const int (&hi)[2], const int (&sc)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) { const int sc_lo[2] = {(int8_t) sc[0], (int8_t) sc[1]}; const int sc_hi[2] = {(int8_t) (sc[0] >> 8), (int8_t) (sc[1] >> 8)}; mmq_few_mma_k16_add(lo, hi, sc_lo, sc_hi, yf, s, sum_d); } template static __device__ __forceinline__ void mmq_few_add_scaled(float (&sum)[ncg][4], const float (&d)[2], const float (&sum_d)[ncg][4]) { #pragma unroll for (int c = 0; c < ncg; ++c) { #pragma unroll for (int l = 0; l < 4; ++l) { sum[c][l] += d[l/2]*sum_d[c][l]; } } } // vec_dot: one unit of 256 values of the 16 rows of a warp, x[0] and x[1] are the rows g and g+8 of lane (g, t). // The lane decodes the values [4t, 4t + 4) and [16 + 4t, 16 + 4t + 4) of each sub-block, its A fragments. template static __device__ __forceinline__ void mmq_few_vec_dot_q45_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { using block_t = std::conditional_t; const int t = threadIdx.x % 4; int qs[2][4][2]; [[maybe_unused]] int qh[2][2]; // Q5_K: bit s holds the high bit of sub-block s int sc[2][2]; int mn[2][2]; float d[2]; float dmin[2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_t * bx = (const block_t *) x[r]; #pragma unroll for (int j = 0; j < 4; ++j) { qs[r][j][0] = get_int_b4(bx->qs + 32*j, t); qs[r][j][1] = get_int_b4(bx->qs + 32*j + 16, t); } if constexpr (type == GGML_TYPE_Q5_K) { qh[r][0] = get_int_b4(bx->qh, t); qh[r][1] = get_int_b4(bx->qh + 16, t); } const int4 hdr = *(const int4 *) bx; // dm and the 12 scale bytes const int scales[3] = {hdr.y, hdr.z, hdr.w}; sc[r][0] = unpack_scales_q45_K(scales, 0); sc[r][1] = unpack_scales_q45_K(scales, 1); mn[r][0] = unpack_scales_q45_K(scales, 2); mn[r][1] = unpack_scales_q45_K(scales, 3); const float2 dm = __half22float2(bx->dm); d[r] = dm.x; dmin[r] = dm.y; } float sum_d[ncg][4] = {{0.0f}}; float sum_m[ncg][4] = {{0.0f}}; #pragma unroll for (int s = 0; s < 8; ++s) { const int j = s/2; const int shift = 4*(s % 2); int lo[2]; int hi[2]; #pragma unroll for (int r = 0; r < 2; ++r) { lo[r] = (qs[r][j][0] >> shift) & 0x0F0F0F0F; hi[r] = (qs[r][j][1] >> shift) & 0x0F0F0F0F; if constexpr (type == GGML_TYPE_Q5_K) { lo[r] |= ((qh[r][0] >> s) & 0x01010101) << 4; hi[r] |= ((qh[r][1] >> s) & 0x01010101) << 4; } } const int ls[2] = {(sc[0][s/4] >> (8*(s % 4))) & 0xFF, (sc[1][s/4] >> (8*(s % 4))) & 0xFF}; const float m0 = (mn[0][s/4] >> (8*(s % 4))) & 0xFF; const float m1 = (mn[1][s/4] >> (8*(s % 4))) & 0xFF; mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); #pragma unroll for (int c = 0; c < ncg; ++c) { const float2 sm = mmq_few_get_sum(yf[c], s); sum_m[c][0] += m0 * sm.x; sum_m[c][1] += m0 * sm.y; sum_m[c][2] += m1 * sm.x; sum_m[c][3] += m1 * sm.y; } } #pragma unroll for (int c = 0; c < ncg; ++c) { #pragma unroll for (int l = 0; l < 4; ++l) { sum[c][l] += d[l/2]*sum_d[c][l] - dmin[l/2]*sum_m[c][l]; } } } // Q6_K and Q3_K have a scale per 16 values: one k=16 MMA per half of a sub-block. template static __device__ __forceinline__ void mmq_few_vec_dot_q6_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; float d[2]; #pragma unroll for (int r = 0; r < 2; ++r) { d[r] = __half2float(((const block_q6_K *) x[r])->d); } float sum_d[ncg][4] = {{0.0f}}; #pragma unroll for (int n = 0; n < 2; ++n) { int ql[2][2][2]; // [row][ql offset 0 or 32][lo or hi] int qh[2][2]; int sc[2][2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_q6_K * bx = (const block_q6_K *) x[r]; #pragma unroll for (int k = 0; k < 2; ++k) { ql[r][k][0] = get_int_b2(bx->ql + 64*n + 32*k, t); ql[r][k][1] = get_int_b2(bx->ql + 64*n + 32*k + 16, t); } qh[r][0] = get_int_b2(bx->qh + 32*n, t); qh[r][1] = get_int_b2(bx->qh + 32*n + 16, t); sc[r][0] = get_int_b2(bx->scales + 8*n, 0); sc[r][1] = get_int_b2(bx->scales + 8*n, 1); } #pragma unroll for (int j = 0; j < 4; ++j) { const int s = 4*n + j; int lo[2]; int hi[2]; #pragma unroll for (int r = 0; r < 2; ++r) { lo[r] = __vsub4(((ql[r][j % 2][0] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[r][0] >> (2*j)) & 0x03030303) << 4), 0x20202020); hi[r] = __vsub4(((ql[r][j % 2][1] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[r][1] >> (2*j)) & 0x03030303) << 4), 0x20202020); } const int sc_s[2] = {sc[0][j/2] >> (16*(j % 2)), sc[1][j/2] >> (16*(j % 2))}; // scales 2s and 2s+1 mmq_few_mma_k16_add(lo, hi, sc_s, yf, s, sum_d); } } mmq_few_add_scaled(sum, d, sum_d); } template static __device__ __forceinline__ void mmq_few_vec_dot_q3_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; int hm[2][2]; int sc[2][4]; // the 16 scales of a row as int8, minus 32 float d[2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_q3_K * bx = (const block_q3_K *) x[r]; hm[r][0] = ~get_int_b2(bx->hmask, t); // a set bit means that 4 is subtracted hm[r][1] = ~get_int_b2(bx->hmask + 16, t); #pragma unroll for (int ksc = 0; ksc < 4; ++ksc) { sc[r][ksc] = unpack_scales_q3_K(bx->scales, ksc); } d[r] = __half2float(bx->d); } float sum_d[ncg][4] = {{0.0f}}; #pragma unroll for (int n = 0; n < 2; ++n) { int qs[2][2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_q3_K * bx = (const block_q3_K *) x[r]; qs[r][0] = get_int_b2(bx->qs + 32*n, t); qs[r][1] = get_int_b2(bx->qs + 32*n + 16, t); } #pragma unroll for (int j = 0; j < 4; ++j) { const int s = 4*n + j; int lo[2]; int hi[2]; #pragma unroll for (int r = 0; r < 2; ++r) { lo[r] = __vsub4((qs[r][0] >> (2*j)) & 0x03030303, ((hm[r][0] >> s) & 0x01010101) << 2); hi[r] = __vsub4((qs[r][1] >> (2*j)) & 0x03030303, ((hm[r][1] >> s) & 0x01010101) << 2); } const int sc_s[2] = {sc[0][s/2] >> (16*(s % 2)), sc[1][s/2] >> (16*(s % 2))}; // scales 2s and 2s+1 mmq_few_mma_k16_add(lo, hi, sc_s, yf, s, sum_d); } } mmq_few_add_scaled(sum, d, sum_d); } template static __device__ __forceinline__ void mmq_few_vec_dot_iq4_xs(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; float d[2]; int scales_h[2]; int scales_l[2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_iq4_xs * bx = (const block_iq4_xs *) x[r]; d[r] = __half2float(bx->d); scales_h[r] = bx->scales_h; scales_l[r] = get_int_b4(bx->scales_l, 0); } float sum_d[ncg][4] = {{0.0f}}; #pragma unroll for (int s = 0; s < 8; ++s) { int lo[2]; int hi[2]; int ls[2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_iq4_xs * bx = (const block_iq4_xs *) x[r]; const int2 v = get_int_from_table_16(get_int_b4(bx->qs + 16*s, t), kvalues_iq4nl); lo[r] = v.x; hi[r] = v.y; ls[r] = (((scales_l[r] >> (4*s)) & 0x0F) | (((scales_h[r] >> (2*s)) & 0x03) << 4)) - 32; } mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); } mmq_few_add_scaled(sum, d, sum_d); } // Q8_0 and IQ4_NL have a block with its own scale per 32 values. template static __device__ __forceinline__ void mmq_few_vec_dot_q8_0_iq4_nl(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; #pragma unroll for (int s = 0; s < 8; ++s) { int lo[2]; int hi[2]; float d[2]; #pragma unroll for (int r = 0; r < 2; ++r) { if constexpr (type == GGML_TYPE_Q8_0) { const block_q8_0 * bx = (const block_q8_0 *) x[r] + s; lo[r] = get_int_b2(bx->qs, t); hi[r] = get_int_b2(bx->qs + 16, t); d[r] = __half2float(bx->d); } else { const block_iq4_nl * bx = (const block_iq4_nl *) x[r] + s; const int2 v = get_int_from_table_16(get_int_b2(bx->qs, t), kvalues_iq4nl); lo[r] = v.x; hi[r] = v.y; d[r] = __half2float(bx->d); } } mmq_few_mma_add(lo, hi, d, yf, s, sum); } } template static __device__ __forceinline__ void mmq_few_vec_dot_iq3_s(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; float d[2]; #pragma unroll for (int r = 0; r < 2; ++r) { d[r] = __half2float(((const block_iq3_s *) x[r])->d); } float sum_d[ncg][4] = {{0.0f}}; #pragma unroll for (int s = 0; s < 8; ++s) { int lo[2]; int hi[2]; int ls[2]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_iq3_s * bx = (const block_iq3_s *) x[r]; const int qh = bx->qh[s]; // the values [4k, 4k + 4) of a sub-block come from grid entry k, with the signs in bits 4*(k%2) of byte k/2 const int k_lo = t; const int k_hi = 4 + t; const int grid_lo = iq3s_grid[bx->qs[8*s + k_lo] | (((qh >> k_lo) & 1) << 8)]; const int grid_hi = iq3s_grid[bx->qs[8*s + k_hi] | (((qh >> k_hi) & 1) << 8)]; const int sign_lo = (bx->signs[4*s + k_lo/2] >> (4*(k_lo % 2))) & 0x0F; const int sign_hi = (bx->signs[4*s + k_hi/2] >> (4*(k_hi % 2))) & 0x0F; const int mask_lo = __vcmpne4(((sign_lo & 0x03) << 7) | ((sign_lo & 0x0C) << 21), 0x00000000); const int mask_hi = __vcmpne4(((sign_hi & 0x03) << 7) | ((sign_hi & 0x0C) << 21), 0x00000000); lo[r] = __vsub4(grid_lo ^ mask_lo, mask_lo); hi[r] = __vsub4(grid_hi ^ mask_hi, mask_hi); ls[r] = 1 + 2*((bx->scales[s/2] >> (4*(s % 2))) & 0x0F); } mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); } mmq_few_add_scaled(sum, d, sum_d); } // The doubled E2M1 values of the 4 nibbles in the low 16 bits of q as int8, like get_int_from_table_16. static __device__ __forceinline__ int mmq_few_e2m1_x4(const int q) { const uint32_t * table32 = (const uint32_t *) kvalues_fp4; const uint32_t low = __byte_perm(table32[0], table32[1], q); const uint32_t high = __byte_perm(table32[2], table32[3], q); return __byte_perm(low, high, 0x3210 | ((q & 0x8888) >> 1)); } // NVFP4 has a UE4M3 scale per 16 values: one k=16 MMA per half of a sub-block, the E2M1 values are converted to int8 with a table. // Byte i of 16 values holds the values i and i + 8. Lane t takes the bytes 2t and 2t + 1, so src1 has the values 2t, 2t + 8, 2t + 1, 2t + 9 in this order (nvfp4_order in quantize.cu). template static __device__ __forceinline__ void mmq_few_vec_dot_nvfp4(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; #pragma unroll for (int ib = 0; ib < QK_K/QK_NVFP4; ++ib) { int q[2][4]; float sc[2][4]; #pragma unroll for (int r = 0; r < 2; ++r) { const block_nvfp4 * bx = (const block_nvfp4 *) x[r] + ib; #pragma unroll for (int j = 0; j < QK_NVFP4/QK_NVFP4_SUB; ++j) { q[r][j] = mmq_few_e2m1_x4(*(const uint16_t *) (bx->qs + 8*j + 2*t)); } // The 4 UE4M3 scales, not halved like in ggml_cuda_ue4m3_to_fp32 (the write-back halves). As there, the NaN codes 0x7F and 0xFF give 0. #ifdef FP8_AVAILABLE // 2 scales per conversion uint32_t d4 = get_int_b4(bx->d, 0); const uint32_t nan = ((d4 & 0x7F7F7F7F) + 0x01010101) & 0x80808080; // 0x80 in the bytes 0x7F and 0xFF d4 &= ~(nan | (nan - (nan >> 7))); // these bytes to 0 const float2 s01 = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t) (d4 & 0xFFFF), __NV_E4M3))); const float2 s23 = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t) (d4 >> 16), __NV_E4M3))); sc[r][0] = s01.x; sc[r][1] = s01.y; sc[r][2] = s23.x; sc[r][3] = s23.y; #else #pragma unroll for (int j = 0; j < QK_NVFP4/QK_NVFP4_SUB; ++j) { sc[r][j] = 2.0f*ggml_cuda_ue4m3_to_fp32(bx->d[j]); } #endif // FP8_AVAILABLE } #pragma unroll for (int h = 0; h < 2; ++h) { const int lo[2] = {q[0][2*h + 0], q[1][2*h + 0]}; const int hi[2] = {q[0][2*h + 1], q[1][2*h + 1]}; const float sc_lo[2] = {sc[0][2*h + 0], sc[1][2*h + 0]}; const float sc_hi[2] = {sc[0][2*h + 1], sc[1][2*h + 1]}; mmq_few_mma_k16_add(lo, hi, sc_lo, sc_hi, yf, 2*ib + h, sum); } } } // NVFP4 with 4-bit src1: one block scaled FP4 m16n8k64 MMA per block of 64 values, the 32 bit words of src0 and src1 are the MMA fragments. // Lanes with t % 2 == 0 give the scales of row g, lanes with t % 2 == 1 those of row g + 8, see mma_block_scaled_fp4. template static __device__ __forceinline__ void mmq_few_vec_dot_nvfp4_fp4(const char * const (&x)[2], const mmq_few_y_fp4 (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; const char * x_sc = t % 2 == 0 ? x[0] : x[1]; // x[t % 2] would put x into local memory #pragma unroll for (int ib = 0; ib < QK_K/QK_NVFP4; ++ib) { const block_nvfp4 * bx0 = (const block_nvfp4 *) x[0] + ib; const block_nvfp4 * bx1 = (const block_nvfp4 *) x[1] + ib; tile<16, 8, int> A; A.x[0] = get_int_b4(bx0->qs, t); A.x[1] = get_int_b4(bx1->qs, t); A.x[2] = get_int_b4(bx0->qs, t + 4); A.x[3] = get_int_b4(bx1->qs, t + 4); const uint32_t scale_A = get_int_b4(((const block_nvfp4 *) x_sc + ib)->d, 0); #pragma unroll for (int c = 0; c < ncg; ++c) { const int * qs = (const int *) &yf[c].qs[ib/2]; tile<8, 8, int> B; B.x[0] = qs[2*(ib % 2) + 0]; B.x[1] = qs[2*(ib % 2) + 1]; const uint32_t scale_B = ((const int *) &yf[c].sc)[ib]; mma_block_scaled_fp4(*(tile<16, 8, float> *) sum[c], A, B, scale_A, scale_B); } } } // The 2 E4M3 values in the low 16 bits of q as half2, exact. static __device__ __forceinline__ int mmq_few_e4m3x2_to_half2(const int q) { #ifdef FP8_AVAILABLE // sm_89 and newer: one instruction, older GPUs: software conversion in the CUDA headers const __half2_raw h = __nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t) (q & 0xFFFF), __NV_E4M3); return int(h.x) | (int(h.y) << 16); #else // CUDA < 11.8 has no cuda_fp8.h const half2 h = __floats2half2_rn(ggml_cuda_f8_e4m3_to_fp32(q & 0xFF), ggml_cuda_f8_e4m3_to_fp32((q >> 8) & 0xFF)); return *(const int *) &h; #endif // FP8_AVAILABLE } // F8_E4M3: FP16 m16n8k16 MMAs with FP32 accumulation, the E4M3 values are converted to FP16. The scale of src1 is per unit and column. // In each block of 64 values the lane takes the 16 bytes [16t, 16t + 16) of its rows, int j of them is MMA j. src1 has the same k order (MMQ_FEW_F16_INT4). template static __device__ __forceinline__ void mmq_few_vec_dot_f8(const char * const (&x)[2], const mmq_few_y_f16 (&yf)[ncg], float (&sum)[ncg][4]) { const int t = threadIdx.x % 4; tile<16, 8, float> C[ncg]; #pragma unroll for (int b = 0; b < QK_K/64; ++b) { const int4 q0 = *(const int4 *) (x[0] + 64*b + 16*t); const int4 q1 = *(const int4 *) (x[1] + 64*b + 16*t); const int q[2][4] = {{q0.x, q0.y, q0.z, q0.w}, {q1.x, q1.y, q1.z, q1.w}}; #pragma unroll for (int j = 0; j < 4; ++j) { // A: k = 2t, 2t + 1 of the rows g and g + 8 (low 16 bits), then k = 2t + 8, 2t + 9 (high 16 bits) tile<16, 8, half2> A; int * Ai = (int *) A.x; Ai[0] = mmq_few_e4m3x2_to_half2(q[0][j]); Ai[1] = mmq_few_e4m3x2_to_half2(q[1][j]); Ai[2] = mmq_few_e4m3x2_to_half2(q[0][j] >> 16); Ai[3] = mmq_few_e4m3x2_to_half2(q[1][j] >> 16); #pragma unroll for (int c = 0; c < ncg; ++c) { const int * h = (const int *) &yf[c].h[2*b + j/2]; tile<8, 8, half2> B; int * Bi = (int *) B.x; Bi[0] = h[2*(j % 2) + 0]; Bi[1] = h[2*(j % 2) + 1]; mma(C[c], A, B); } } } #pragma unroll for (int c = 0; c < ncg; ++c) { sum[c][0] += yf[c].d.x*C[c].x[0]; sum[c][1] += yf[c].d.y*C[c].x[1]; sum[c][2] += yf[c].d.x*C[c].x[2]; sum[c][3] += yf[c].d.y*C[c].x[3]; } } template static __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { if constexpr (type == GGML_TYPE_Q8_0 || type == GGML_TYPE_IQ4_NL) { mmq_few_vec_dot_q8_0_iq4_nl(x, yf, sum); } else if constexpr (type == GGML_TYPE_Q3_K) { mmq_few_vec_dot_q3_K(x, yf, sum); } else if constexpr (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { mmq_few_vec_dot_q45_K(x, yf, sum); } else if constexpr (type == GGML_TYPE_Q6_K) { mmq_few_vec_dot_q6_K(x, yf, sum); } else if constexpr (type == GGML_TYPE_IQ3_S) { mmq_few_vec_dot_iq3_s(x, yf, sum); } else if constexpr (type == GGML_TYPE_IQ4_XS) { mmq_few_vec_dot_iq4_xs(x, yf, sum); } else if constexpr (type == GGML_TYPE_NVFP4) { mmq_few_vec_dot_nvfp4(x, yf, sum); } else { static_assert(type == GGML_TYPE_COUNT, "unsupported type"); } } #endif // defined(CP_ASYNC_AVAILABLE) // has_ids: MUL_MAT_ID, blockIdx.y is a pair of quantize_mmq_few_id_q8_1, its expert is the src0 channel and dst dims 1 and 2 are slot and token. // fp4: NVFP4 src0 with 4-bit src1, which has a scale per column in y_scale. x_scale is an optional scale of all of src0 (NVFP4, F8_E4M3). template __launch_bounds__(MMQ_FEW_NWARPS*ggml_cuda_get_physical_warp_size(), 1) static __global__ void mul_mat_q_few( const char * x, const int4 * y_ptr, const float * y_scale, const float * x_scale, float * dst, const int nunits, const int nrows_x, const int ncols_dst, const int64_t stride_row_x, const int stride_col_dst, const int channel_ratio, const int64_t stride_channel_x, const int stride_channel_dst, const int sample_ratio, const int64_t stride_sample_x, const int stride_sample_dst, const bool x_is_constant, const int * pairs) { #if defined(CP_ASYNC_AVAILABLE) constexpr int nwarps = MMQ_FEW_NWARPS; constexpr int warp_size = ggml_cuda_get_physical_warp_size(); static_assert(warp_size == WARP_SIZE, "unsupported warp size"); static_assert(!has_ids || (ncg == 1 && nmt == 1), "unsupported MUL_MAT_ID config"); static_assert(!fp4 || (type == GGML_TYPE_NVFP4 && !has_ids), "4-bit src1 is only supported for NVFP4 MUL_MAT"); static_assert(type != GGML_TYPE_F8_E4M3 || !has_ids, "F8_E4M3 is only supported for MUL_MAT"); constexpr bool f16_y = type == GGML_TYPE_F8_E4M3; // FP16 src1 using y_frag_t = std::conditional_t>; constexpr int y_int4 = fp4 ? MMQ_FEW_FP4_INT4 : (f16_y ? MMQ_FEW_F16_INT4 : MMQ_FEW_Q8_1_INT4); constexpr int unit_size = mmq_few_unit_size(type); constexpr int nrows = nmt*MMQ_FEW_NROWS; constexpr int nunits_stage = mmq_few_nunits_stage(type, ncg, nmt, fp4); constexpr int nstages = mmq_few_nstages(type); constexpr bool unaligned = mmq_few_unaligned(type, nunits_stage); constexpr int nchunks = mmq_few_nchunks(type, nunits_stage); constexpr int sram_stride = mmq_few_sram_stride(type, nunits_stage); constexpr int nbytes_stage = nrows*sram_stride; constexpr int ncopies = nrows*nchunks; static_assert(unit_size > 0, "unsupported type"); extern __shared__ char data_mmq_few[]; char * ring = data_mmq_few + threadIdx.y*nstages*nbytes_stage; const bool ksplit = mmq_few_ksplit(has_ids, nunits); const int row0_blk = blockIdx.x*(ksplit ? nrows : nwarps*nrows); const int row0 = ksplit ? row0_blk : row0_blk + threadIdx.y*nrows; const int iu_begin = ksplit ? nunits_stage*threadIdx.y : 0; const int iu_step = ksplit ? nunits_stage*nwarps : nunits_stage; const int channel_dst = blockIdx.y; const int sample_dst = blockIdx.z; const int nchannels = gridDim.y; int ncols = ncols_dst; [[maybe_unused]] const int * pair = nullptr; if constexpr (has_ids) { ggml_cuda_pdl_sync(); // the pairs come from the preceding kernel pair = pairs + channel_dst*MMQ_FEW_PAIR_INTS; ncols = pair[1]; if (ncols == 0) { return; } x += int64_t(pair[0])*stride_channel_x; } else { x += int64_t(sample_dst/sample_ratio)*stride_sample_x + int64_t(channel_dst/channel_ratio)*stride_channel_x; dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst; } const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*ncg*y_int4; // No bounds check for the units, the gate makes nunits a multiple of nunits_stage. // The extra bytes of unaligned data are inside the allocation, which ggml aligns and pads to 128 bytes. auto load_stage = [&](const int stage, const int iu0) { const unsigned int dst_stage = ggml_cuda_cvta_generic_to_shared(ring + stage*nbytes_stage); #pragma unroll for (int c0 = 0; c0 < ncopies; c0 += warp_size) { const int c = c0 + threadIdx.x; const int i = c / nchunks; const int ic = c % nchunks; if (ncopies % warp_size == 0 || c < ncopies) { const int row = min(row0 + i, nrows_x - 1); const char * src = x + int64_t(row)*stride_row_x + int64_t(iu0)*unit_size; if constexpr (unaligned) { const int off = (uintptr_t) src % 16; if (16*ic < off + nunits_stage*unit_size) { cp_async_cg_16<0>(dst_stage + i*sram_stride + 16*ic, src - off + 16*ic); } } else { cp_async_cg_16<0>(dst_stage + i*sram_stride + 16*ic, src + 16*ic); } } } }; // offsets of the rows of this lane from their 16 byte boundary int off_row[2*nmt] = {0}; if constexpr (unaligned) { #pragma unroll for (int r = 0; r < 2*nmt; ++r) { const int row = min(row0 + int(threadIdx.x)/4 + 8*r, nrows_x - 1); off_row[r] = (uintptr_t) (x + int64_t(row)*stride_row_x) % 16; } } // Only weights, which no preceding kernel writes, are read before the PDL wait. if (!x_is_constant) { ggml_cuda_pdl_sync(); } #if __CUDA_ARCH__ == GGML_CUDA_CC_GB10 // DGX Spark DRAM serves the short row pieces of the stage copies slowly, so the rows of the block are first prefetched into L2 in address order. { const int tid = threadIdx.y*warp_size + threadIdx.x; const int nrows_blk = min(ksplit ? nrows : nwarps*nrows, nrows_x - row0_blk); const int64_t row_bytes = int64_t(nunits)*unit_size; const bool contig = stride_row_x == row_bytes; for (int ir = 0; ir < (contig ? 1 : nrows_blk); ++ir) { const uintptr_t p0 = (uintptr_t) (x + int64_t(row0_blk + ir)*stride_row_x); const uintptr_t p1 = p0 + (contig ? nrows_blk*row_bytes : row_bytes); for (uintptr_t p = (p0 & ~uintptr_t(127)) + 128*tid; p < p1; p += 128*nwarps*warp_size) { ggml_cuda_prefetch_l2((const void *) p); } } } #endif // __CUDA_ARCH__ == GGML_CUDA_CC_GB10 #pragma unroll for (int stage = 0; stage < nstages - 1; ++stage) { const int iu0 = iu_begin + stage*iu_step; if (iu0 < nunits) { load_stage(stage, iu0); } cp_async_commit_group(); } if (x_is_constant) { ggml_cuda_pdl_sync(); } auto load_y = [&](y_frag_t (&yf)[ncg], const int iu) { #pragma unroll for (int c = 0; c < ncg; ++c) { mmq_few_load_y(yf[c], y + (int64_t(iu)*ncg + c)*y_int4); } }; // The next src1 fragments are loaded right after the MMAs that use the current ones, an earlier load is slower. y_frag_t yf[nunits_stage][ncg]; if (iu_begin < nunits) { #pragma unroll for (int k = 0; k < nunits_stage; ++k) { load_y(yf[k], iu_begin + k); } } float sum[nmt][ncg][4] = {{{0.0f}}}; for (int iter = 0, iu0 = iu_begin; iu0 < nunits; ++iter, iu0 += iu_step) { const int iu_load = iu0 + (nstages - 1)*iu_step; if (iu_load < nunits) { load_stage((iter + nstages - 1) % nstages, iu_load); } cp_async_commit_group(); const bool has_next = iu0 + iu_step < nunits; cp_async_wait_group(); ggml_cuda_syncwarp(); const char * xs = ring + (iter % nstages)*nbytes_stage; const int off_stage = unaligned ? (iu0*unit_size) % 16 : 0; #pragma unroll for (int k = 0; k < nunits_stage; ++k) { #pragma unroll for (int m = 0; m < nmt; ++m) { const char * const xr[2] = { xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 0)*sram_stride + (off_row[2*m + 0] + off_stage) % 16 + k*unit_size, xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 8)*sram_stride + (off_row[2*m + 1] + off_stage) % 16 + k*unit_size, }; if constexpr (fp4) { mmq_few_vec_dot_nvfp4_fp4(xr, yf[k], sum[m]); } else if constexpr (f16_y) { mmq_few_vec_dot_f8(xr, yf[k], sum[m]); } else { mmq_few_vec_dot(xr, yf[k], sum[m]); } } if (has_next) { load_y(yf[k], iu0 + iu_step + k); } } ggml_cuda_syncwarp(); // the stage is overwritten in the next iteration } cp_async_wait_all(); ggml_cuda_pdl_lc(); // reduce the sums over the warps as one flat array if (ksplit) { constexpr int nsum = nmt*ncg*4; float * sum_flat = &sum[0][0][0]; float * buf_sum = (float *) data_mmq_few; __syncthreads(); if (threadIdx.y > 0) { #pragma unroll for (int i = 0; i < nsum; ++i) { buf_sum[((threadIdx.y - 1)*nsum + i)*warp_size + threadIdx.x] = sum_flat[i]; } } __syncthreads(); if (threadIdx.y > 0) { return; } #pragma unroll for (int w = 0; w < nwarps - 1; ++w) { #pragma unroll for (int i = 0; i < nsum; ++i) { sum_flat[i] += buf_sum[(w*nsum + i)*warp_size + threadIdx.x]; } } } [[maybe_unused]] float scale_x = 1.0f; if constexpr (type == GGML_TYPE_NVFP4) { scale_x = (fp4 ? 1.0f : 0.5f)*(x_scale ? *x_scale : 1.0f); // 8-bit src1: halved here, as the decoder halves neither the UE4M3 scales nor the doubled E2M1 values if constexpr (fp4) { y_scale += (int64_t(sample_dst)*nchannels + channel_dst)*ncg*MMQ_FEW_NCOLS; } } else if constexpr (type == GGML_TYPE_F8_E4M3) { scale_x = x_scale ? *x_scale : 1.0f; } #pragma unroll for (int m = 0; m < nmt; ++m) { #pragma unroll for (int c = 0; c < ncg; ++c) { #pragma unroll for (int l = 0; l < 4; ++l) { const int i = row0 + MMQ_FEW_NROWS*m + tile<16, 8, int>::get_i(l); const int j = c*MMQ_FEW_NCOLS + tile<16, 8, int>::get_j(l); if (i < nrows_x && j < ncols) { if constexpr (has_ids) { const int e = pair[2 + j]; // token*n_expert_used + slot dst[int64_t(e / ncols_dst)*stride_channel_dst + int64_t(e % ncols_dst)*stride_col_dst + i] = sum[m][c][l]; } else if constexpr (type == GGML_TYPE_NVFP4) { dst[int64_t(j)*stride_col_dst + i] = (fp4 ? y_scale[j]*scale_x : scale_x)*sum[m][c][l]; } else if constexpr (type == GGML_TYPE_F8_E4M3) { dst[int64_t(j)*stride_col_dst + i] = scale_x*sum[m][c][l]; } else { dst[int64_t(j)*stride_col_dst + i] = sum[m][c][l]; } } } } } #else GGML_UNUSED_VARS(x, y_ptr, y_scale, x_scale, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_dst, x_is_constant, pairs); NO_DEVICE_CODE; #endif // defined(CP_ASYNC_AVAILABLE) } // RDNA version with WMMA for up to 16 src1 columns. A WMMA multiplies 16x16 int8 matrices, see mma.cuh: // A = src1, B = src0, C = A @ B. // A and B: lane l holds the column resp. row l%16, the values [16k, 16k + 16) on RDNA3 and [8*(l/16), 8*(l/16) + 8) on RDNA4. // C: lane l holds the src1 columns 2v + l/16 (RDNA3) resp. 8*(l/16) + v (RDNA4) of the src0 row l%16. // So the src0 scales of a row stay in the lane that decodes it, the src1 scales of the C columns come with the layout in quantize.cuh. // The lanes decode their rows straight from global memory. A ring as in mul_mat_q_few, filled through registers without cp.async, was slower. // A second group of 16 columns spills registers with ROCm 7.2. static constexpr __host__ __device__ bool mmq_few_wmma_supported(const ggml_type type) { return type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || type == GGML_TYPE_Q6_K; } // the reduction over the warps static constexpr int MMQ_FEW_WMMA_NBYTES_SHARED = (MMQ_FEW_NWARPS - 1)*8*WARP_SIZE*sizeof(float); #if defined(AMD_WMMA_AVAILABLE) // The A and B tiles of a lane for one WMMA, MIRRORED on RDNA3 where both half-warps hold the same data. #if defined(AMD_WMMA_256B_AVAILABLE) using mmq_few_tile_ab = tile<16, 4, int, DATA_LAYOUT_I_MAJOR_MIRRORED>; #else using mmq_few_tile_ab = tile<16, 4, int, DATA_LAYOUT_I_MAJOR>; #endif using mmq_few_tile_c = tile<16, 16, int, DATA_LAYOUT_J_MAJOR>; // int32 per lane and WMMA, 4 on RDNA3 and 2 on RDNA4 static constexpr int MMQ_FEW_WMMA_NE = mmq_few_tile_ab::ne; // The src1 fragments of a lane for one sub-block, see quantize.cuh. struct mmq_few_wmma_y { int qs[2][MMQ_FEW_WMMA_NE]; // [hh] holds the values [16*hh, 16*hh + 16) of the WMMA int ds[8]; // d (D4) resp. (d, sum) (DS4) of the C columns, ds[v] of C.x[v] }; // The C registers of a lane, on RDNA3 the ones with v >= 4 hold only the columns >= 8. template static constexpr int mmq_few_wmma_nv() { return half && MMQ_FEW_WMMA_NE == 4 ? 4 : 8; } // half: only the first 8 columns are used, the others are zero. template static __device__ __forceinline__ mmq_few_wmma_y mmq_few_wmma_load_y(const int4 * y, const int s) { const int m = threadIdx.x % 16; const int h = threadIdx.x / 16; mmq_few_wmma_y yf; if constexpr (MMQ_FEW_WMMA_NE == 2) { // RDNA4: the lane holds the values [16*hh + 8*h, 16*hh + 8*h + 8) of column m. // The src1 quantize kernel zeroes the columns beyond ne1, a branch to skip the unused ones is more expensive than the loads. const int2 * y2 = (const int2 *) y; const int2 q0 = y2[(s*MMQ_FEW_WMMA_NCOLS + m)*4 + 0 + h]; const int2 q1 = y2[(s*MMQ_FEW_WMMA_NCOLS + m)*4 + 2 + h]; yf.qs[0][0] = q0.x; yf.qs[0][1] = q0.y; yf.qs[1][0] = q1.x; yf.qs[1][1] = q1.y; } else if (half && m >= MMQ_FEW_WMMA_NCOLS/2) { yf.qs[0][0] = 0; yf.qs[0][1] = 0; yf.qs[0][2] = 0; yf.qs[0][3] = 0; yf.qs[1][0] = 0; yf.qs[1][1] = 0; yf.qs[1][2] = 0; yf.qs[1][3] = 0; } else { const int4 q0 = y[(s*MMQ_FEW_WMMA_NCOLS + m)*2 + 0]; const int4 q1 = y[(s*MMQ_FEW_WMMA_NCOLS + m)*2 + 1]; yf.qs[0][0] = q0.x; yf.qs[0][1] = q0.y; yf.qs[0][2] = q0.z; yf.qs[0][3] = q0.w; yf.qs[1][0] = q1.x; yf.qs[1][1] = q1.y; yf.qs[1][2] = q1.z; yf.qs[1][3] = q1.w; } if constexpr (MMQ_FEW_WMMA_NE == 2) { // RDNA4: C.x[v] is the column 8*h + v const int4 d0 = y[8*MMQ_FEW_WMMA_NCOLS*2 + 4*s + 0 + h]; const int4 d1 = y[8*MMQ_FEW_WMMA_NCOLS*2 + 4*s + 2 + h]; yf.ds[0] = d0.x; yf.ds[1] = d1.x; yf.ds[2] = d0.y; yf.ds[3] = d1.y; yf.ds[4] = d0.z; yf.ds[5] = d1.z; yf.ds[6] = d0.w; yf.ds[7] = d1.w; } else { const int4 ds0 = y[8*MMQ_FEW_WMMA_NCOLS*2 + (s*2 + h)*2 + 0]; const int4 ds1 = half ? make_int4(0, 0, 0, 0) : y[8*MMQ_FEW_WMMA_NCOLS*2 + (s*2 + h)*2 + 1]; yf.ds[0] = ds0.x; yf.ds[1] = ds0.y; yf.ds[2] = ds0.z; yf.ds[3] = ds0.w; yf.ds[4] = ds1.x; yf.ds[5] = ds1.y; yf.ds[6] = ds1.z; yf.ds[7] = ds1.w; } return yf; } template static __device__ __forceinline__ float mmq_few_wmma_get_d(const mmq_few_wmma_y & yf, const int v) { if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) { return __int_as_float(yf.ds[v]); } else { return __low2float(*(const half2 *) &yf.ds[v]); } } static __device__ __forceinline__ float mmq_few_wmma_get_sum(const mmq_few_wmma_y & yf, const int v) { return __high2float(*(const half2 *) &yf.ds[v]); } // n ints at the even byte offset o of the 4 byte aligned p, with whole 4 byte loads. In the unrolled decoders o is a constant. template static __device__ __forceinline__ void mmq_few_wmma_get_ints_b2(const char * p, const int o, int * dst) { const int * w = (const int *) (p + (o & ~3)); if (o % 4 == 0) { #pragma unroll for (int i = 0; i < n; ++i) { dst[i] = w[i]; } } else { int lo = w[0]; #pragma unroll for (int i = 0; i < n; ++i) { const int hi = w[i + 1]; dst[i] = __builtin_amdgcn_alignbyte(hi, lo, 2); lo = hi; } } } static __device__ __forceinline__ void mmq_few_wmma(mmq_few_tile_c & C, const int * a, const int * b) { mmq_few_tile_ab A; mmq_few_tile_ab B; #pragma unroll for (int l = 0; l < MMQ_FEW_WMMA_NE; ++l) { A.x[l] = a[l]; B.x[l] = b[l]; } mma(C, A, B); } // vec_dot: one unit of 256 values of row l%16, x points to its data, y to the src1 fragments of the unit. // The decoders write sub-block s of the row to b[8], the int32 at index i holds the values [4i, 4i + 4). // One WMMA uses b + 4*hh + i0, with i0 = (4 - MMQ_FEW_WMMA_NE)*(l/16) the offset of the values of the lane. template static __device__ __forceinline__ void mmq_few_wmma_vec_dot_q45_K(const char * x, const int4 * y, float (&sum)[8]) { using block_t = std::conditional_t; const block_t * bx = (const block_t *) __builtin_assume_aligned(x, 16); const int4 hdr = *(const int4 *) bx; // dm and the 12 scale bytes const int scales[3] = {hdr.y, hdr.z, hdr.w}; const int sc[2] = {unpack_scales_q45_K(scales, 0), unpack_scales_q45_K(scales, 1)}; const int mn[2] = {unpack_scales_q45_K(scales, 2), unpack_scales_q45_K(scales, 3)}; const float2 dm = __half22float2(bx->dm); [[maybe_unused]] int qh[8]; // Q5_K: bit s holds the high bit of sub-block s if constexpr (type == GGML_TYPE_Q5_K) { #pragma unroll for (int i = 0; i < 8; ++i) { qh[i] = get_int_b4(bx->qh, i); } } float sum_d[8] = {0.0f}; float sum_m[8] = {0.0f}; const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16); #pragma unroll for (int j = 0; j < 4; ++j) { int qs[8]; #pragma unroll for (int i = 0; i < 8; ++i) { qs[i] = get_int_b4(bx->qs + 32*j, i); } #pragma unroll for (int s = 2*j; s < 2*j + 2; ++s) { int b[8]; #pragma unroll for (int i = 0; i < 8; ++i) { b[i] = (qs[i] >> (4*(s % 2))) & 0x0F0F0F0F; if constexpr (type == GGML_TYPE_Q5_K) { b[i] |= ((qh[i] >> s) & 0x01010101) << 4; } } const int ls = (sc[s/4] >> (8*(s % 4))) & 0xFF; const float m = (mn[s/4] >> (8*(s % 4))) & 0xFF; const mmq_few_wmma_y yf = mmq_few_wmma_load_y(y, s); mmq_few_tile_c C; mmq_few_wmma(C, yf.qs[0], b + i0 + 0); mmq_few_wmma(C, yf.qs[1], b + i0 + 4); #pragma unroll for (int v = 0; v < mmq_few_wmma_nv(); ++v) { sum_d[v] += mmq_few_wmma_get_d(yf, v) * float(C.x[v]*ls); sum_m[v] += m * mmq_few_wmma_get_sum(yf, v); } } } #pragma unroll for (int v = 0; v < 8; ++v) { sum[v] += dm.x*sum_d[v] - dm.y*sum_m[v]; } } // Q6_K has a scale per 16 values, one WMMA per half of a sub-block. template static __device__ __forceinline__ void mmq_few_wmma_vec_dot_q6_K(const char * x, const int4 * y, float (&sum)[8]) { const block_q6_K * bx = (const block_q6_K *) x; const float d = __half2float(bx->d); float sum_d[8] = {0.0f}; const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16); #pragma unroll for (int n = 0; n < 2; ++n) { int ql[2][8]; // [ql offset 0 or 32] int qh[8]; #pragma unroll for (int i = 0; i < 8; ++i) { ql[0][i] = get_int_b2(bx->ql + 64*n, i); ql[1][i] = get_int_b2(bx->ql + 64*n + 32, i); qh[i] = get_int_b2(bx->qh + 32*n, i); } const int sc[2] = {get_int_b2(bx->scales + 8*n, 0), get_int_b2(bx->scales + 8*n, 1)}; #pragma unroll for (int j = 0; j < 4; ++j) { const int s = 4*n + j; int b[8]; #pragma unroll for (int i = 0; i < 8; ++i) { b[i] = __vsub4(((ql[j % 2][i] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[i] >> (2*j)) & 0x03030303) << 4), 0x20202020); } const int sc_lo = (int8_t) (sc[j/2] >> (16*(j % 2) + 0)); // scale of the values [0, 16) const int sc_hi = (int8_t) (sc[j/2] >> (16*(j % 2) + 8)); // scale of the values [16, 32) const mmq_few_wmma_y yf = mmq_few_wmma_load_y(y, s); mmq_few_tile_c C_lo; mmq_few_tile_c C_hi; mmq_few_wmma(C_lo, yf.qs[0], b + i0 + 0); mmq_few_wmma(C_hi, yf.qs[1], b + i0 + 4); #pragma unroll for (int v = 0; v < mmq_few_wmma_nv(); ++v) { sum_d[v] += mmq_few_wmma_get_d(yf, v) * float(C_lo.x[v]*sc_lo + C_hi.x[v]*sc_hi); } } } #pragma unroll for (int v = 0; v < 8; ++v) { sum[v] += d*sum_d[v]; } } // IQ4_NL has a block with its own scale per 32 values. template static __device__ __forceinline__ void mmq_few_wmma_vec_dot_iq4_nl(const char * x, const int4 * y, float (&sum)[8]) { const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16); #pragma unroll for (int s = 0; s < 8; ++s) { // a unit starts 16 byte aligned, the qs of every second block 2 bytes off a 4 byte boundary const char * xa = (const char *) __builtin_assume_aligned(x, 16); int q4[4]; mmq_few_wmma_get_ints_b2<4>(xa, int(sizeof(block_iq4_nl))*s + 2, q4); int b[8]; #pragma unroll for (int i = 0; i < 4; ++i) { const int2 v = get_int_from_table_16(q4[i], kvalues_iq4nl); b[i + 0] = v.x; b[i + 4] = v.y; } const float d = __half2float(((const block_iq4_nl *) xa + s)->d); const mmq_few_wmma_y yf = mmq_few_wmma_load_y(y, s); mmq_few_tile_c C; mmq_few_wmma(C, yf.qs[0], b + i0 + 0); mmq_few_wmma(C, yf.qs[1], b + i0 + 4); #pragma unroll for (int v = 0; v < mmq_few_wmma_nv(); ++v) { sum[v] += d*mmq_few_wmma_get_d(yf, v) * float(C.x[v]); } } } template static __device__ __forceinline__ void mmq_few_wmma_vec_dot(const char * x, const int4 * y, float (&sum)[8]) { if constexpr (type == GGML_TYPE_IQ4_NL) { mmq_few_wmma_vec_dot_iq4_nl(x, y, sum); } else if constexpr (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { mmq_few_wmma_vec_dot_q45_K(x, y, sum); } else if constexpr (type == GGML_TYPE_Q6_K) { mmq_few_wmma_vec_dot_q6_K(x, y, sum); } else { static_assert(type == GGML_TYPE_COUNT, "unsupported type"); } } #endif // defined(AMD_WMMA_AVAILABLE) // The warps split K in units of 256 values, a block has 16 src0 rows. half: at most 8 src1 columns. template __launch_bounds__(MMQ_FEW_NWARPS*WARP_SIZE, 1) static __global__ void mul_mat_q_few_wmma( const char * x, const int4 * y_ptr, float * dst, const int nunits, const int nrows_x, const int ncols_dst, const int64_t stride_row_x, const int stride_col_dst, const int channel_ratio, const int64_t stride_channel_x, const int stride_channel_dst, const int sample_ratio, const int64_t stride_sample_x, const int stride_sample_dst) { #if defined(AMD_WMMA_AVAILABLE) constexpr int nwarps = MMQ_FEW_NWARPS; constexpr int warp_size = WARP_SIZE; constexpr int unit_size = mmq_few_unit_size(type); static_assert(mmq_few_wmma_supported(type), "unsupported type"); extern __shared__ float buf_sum_mmq_few_wmma[]; const int row0 = blockIdx.x*MMQ_FEW_NROWS; const int channel_dst = blockIdx.y; const int sample_dst = blockIdx.z; const int nchannels = gridDim.y; x += int64_t(sample_dst/sample_ratio)*stride_sample_x + int64_t(channel_dst/channel_ratio)*stride_channel_x; dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst; const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*MMQ_FEW_WMMA_Q8_1_INT4; const char * xr = x + int64_t(min(row0 + int(threadIdx.x) % 16, nrows_x - 1))*stride_row_x; float sum[8] = {0.0f}; for (int iu = threadIdx.y; iu < nunits; iu += nwarps) { mmq_few_wmma_vec_dot(xr + int64_t(iu)*unit_size, y + int64_t(iu)*MMQ_FEW_WMMA_Q8_1_INT4, sum); } // reduce the sums over the warps float * buf_sum = buf_sum_mmq_few_wmma; if (threadIdx.y > 0) { #pragma unroll for (int v = 0; v < 8; ++v) { buf_sum[((threadIdx.y - 1)*8 + v)*warp_size + threadIdx.x] = sum[v]; } } __syncthreads(); if (threadIdx.y > 0) { return; } #pragma unroll for (int w = 0; w < nwarps - 1; ++w) { #pragma unroll for (int v = 0; v < 8; ++v) { sum[v] += buf_sum[(w*8 + v)*warp_size + threadIdx.x]; } } const int i = row0 + mmq_few_tile_c::get_j(0); #pragma unroll for (int v = 0; v < mmq_few_wmma_nv(); ++v) { const int j = mmq_few_tile_c::get_i(v); if (i < nrows_x && j < ncols_dst) { dst[int64_t(j)*stride_col_dst + i] = sum[v]; } } #else GGML_UNUSED_VARS(x, y_ptr, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_dst); NO_DEVICE_CODE; #endif // defined(AMD_WMMA_AVAILABLE) } // ggml_is_constant (static in ggml.c) on the tensor that a view points to static bool mmq_few_is_constant(const ggml_tensor * src0) { const ggml_tensor * x_root = src0->view_src ? src0->view_src : src0; return x_root->buffer && ggml_backend_buffer_get_usage(x_root->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && !(x_root->flags & GGML_TENSOR_FLAG_PARAM); } // MUL_MAT_ID: grid y is the pairs, the kernel takes the expert from the pair and does not use the channel and sample ratios. template static void launch_mul_mat_q_few(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const int4 * src1_q, const float * y_scale, const float * x_scale, cudaStream_t stream, const int * pairs = nullptr, const int npairs_max = 0) { GGML_TENSOR_BINARY_OP_LOCALS; const int nunits = ne00 / QK_K; GGML_ASSERT(nunits % mmq_few_nunits_stage(type, ncg, nmt, fp4) == 0); const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; const int nbytes_shared = mmq_few_nbytes_shared(type, ncg, nmt, fp4); CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_few), nbytes_shared); const bool x_is_constant = mmq_few_is_constant(src0); const int nrows_blk = (mmq_few_ksplit(has_ids, nunits) ? 1 : MMQ_FEW_NWARPS)*nmt*MMQ_FEW_NROWS; const dim3 block_nums((ne01 + nrows_blk - 1) / nrows_blk, has_ids ? npairs_max : ne12, ne13); const dim3 block_dims(warp_size, MMQ_FEW_NWARPS, 1); const ggml_cuda_kernel_launch_params params(block_nums, block_dims, nbytes_shared, stream); ggml_cuda_kernel_launch(mul_mat_q_few, params, (const char *) src0->data, src1_q, y_scale, x_scale, (float *) dst->data, nunits, (int) ne01, (int) ne1, (int64_t) nb01, (int) (nb1/sizeof(float)), (int) (ne12/ne02), (int64_t) nb02, (int) (nb2/sizeof(float)), (int) (ne13/ne03), (int64_t) nb03, (int) (nb3/sizeof(float)), x_is_constant, pairs); } static int mmq_few_ncg(const int64_t ncols) { return (ncols + MMQ_FEW_NCOLS - 1) / MMQ_FEW_NCOLS; } // With 2 column groups, 32-row tiles halve the src1 loads per src0 byte. With 3 column groups they spill registers. // With 4-bit src1 (fp4) there are few src1 loads per unit and the 32-row tiles are slower. static int mmq_few_nmt(const ggml_type type, const int ncg, const int64_t nrows_x, const bool fp4) { const int nsm = ggml_cuda_info().devices[ggml_cuda_get_device()].nsm; return mmq_few_tall_supported(type) && !fp4 && ncg == 2 && nrows_x >= int64_t(nsm)*2*MMQ_FEW_NROWS ? 2 : 1; } template static void launch_mul_mat_q_few_tall(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const int4 * src1_q, const float * y_scale, const float * x_scale, cudaStream_t stream) { if constexpr (mmq_few_tall_supported(type) && !fp4) { if (mmq_few_nmt(type, 2, src0->ne[1], fp4) == 2) { launch_mul_mat_q_few(src0, src1, dst, src1_q, y_scale, x_scale, stream); return; } } launch_mul_mat_q_few(src0, src1, dst, src1_q, y_scale, x_scale, stream); } template static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const int4 * src1_q, const float * y_scale, const float * x_scale, const int * pairs, const int npairs_max, const int ncg, cudaStream_t stream) { if (pairs) { if constexpr (mmq_few_id_supported(type)) { launch_mul_mat_q_few(src0, src1, dst, src1_q, y_scale, x_scale, stream, pairs, npairs_max); } else { GGML_ABORT("fatal error"); // see ggml_cuda_mmq_few_min_ncols } return; } switch (ncg) { case 1: launch_mul_mat_q_few(src0, src1, dst, src1_q, y_scale, x_scale, stream); break; case 2: launch_mul_mat_q_few_tall(src0, src1, dst, src1_q, y_scale, x_scale, stream); break; case 3: launch_mul_mat_q_few(src0, src1, dst, src1_q, y_scale, x_scale, stream); break; default: GGML_ABORT("fatal error"); } } template static void launch_mul_mat_q_few_wmma(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const int4 * src1_q, cudaStream_t stream) { GGML_TENSOR_BINARY_OP_LOCALS; const int nunits = ne00 / QK_K; const dim3 block_nums((ne01 + MMQ_FEW_NROWS - 1) / MMQ_FEW_NROWS, ne12, ne13); const dim3 block_dims(WARP_SIZE, MMQ_FEW_NWARPS, 1); const ggml_cuda_kernel_launch_params params(block_nums, block_dims, MMQ_FEW_WMMA_NBYTES_SHARED, stream); ggml_cuda_kernel_launch(mul_mat_q_few_wmma, params, (const char *) src0->data, src1_q, (float *) dst->data, nunits, (int) ne01, (int) ne1, (int64_t) nb01, (int) (nb1/sizeof(float)), (int) (ne12/ne02), (int64_t) nb02, (int) (nb2/sizeof(float)), (int) (ne13/ne03), (int64_t) nb03, (int) (nb3/sizeof(float))); } template static void launch_mul_mat_q_few_wmma_switch_ncols(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const int4 * src1_q, cudaStream_t stream) { if (src1->ne[1] <= MMQ_FEW_WMMA_NCOLS/2) { launch_mul_mat_q_few_wmma(src0, src1, dst, src1_q, stream); } else { launch_mul_mat_q_few_wmma(src0, src1, dst, src1_q, stream); } } // Min. and max. number of src1 columns for RDNA3 and RDNA4, 0 if the type is not supported. // Below the min. MMVQ is faster, above the max. MMQ. Q8_0 would need more than 16 columns to beat MMQ. static int2 mmq_few_wmma_ncols_range(const ggml_type type, const int cc) { if (GGML_CUDA_CC_IS_RDNA4(cc)) { // tuned on the Radeon RX 9070 XT (gfx1201) switch (type) { case GGML_TYPE_Q4_K: return make_int2(3, 16); case GGML_TYPE_Q5_K: return make_int2(3, 16); case GGML_TYPE_Q6_K: return make_int2(5, 16); case GGML_TYPE_IQ4_NL: return make_int2(6, 16); default: return make_int2(0, 0); } } if (GGML_CUDA_CC_IS_RDNA3_0(cc)) { // tuned on the Radeon RX 7900 XTX (gfx1100) switch (type) { case GGML_TYPE_Q4_K: return make_int2(2, 16); case GGML_TYPE_Q5_K: return make_int2(2, 16); case GGML_TYPE_Q6_K: return make_int2(5, 16); case GGML_TYPE_IQ4_NL: return make_int2(5, 16); default: return make_int2(0, 0); } } switch (type) { // tuned on the Radeon 8060S (gfx1151) case GGML_TYPE_Q4_K: return make_int2(3, 16); case GGML_TYPE_Q5_K: return make_int2(3, 8); case GGML_TYPE_Q6_K: return make_int2(6, 16); case GGML_TYPE_IQ4_NL: return make_int2(7, 16); default: return make_int2(0, 0); } } static bool mmq_few_use_wmma(const int cc) { return GGML_CUDA_CC_IS_RDNA3(cc) || GGML_CUDA_CC_IS_RDNA4(cc); } static void ggml_cuda_mul_mat_q_few_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_TENSOR_BINARY_OP_LOCALS; GGML_ASSERT(ne11 <= MMQ_FEW_WMMA_NCOLS); cudaStream_t stream = ctx.stream(); const int nunits = ne00 / QK_K; ggml_cuda_pool_alloc src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*MMQ_FEW_WMMA_Q8_1_INT4); quantize_mmq_few_wmma_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream); switch (src0->type) { case GGML_TYPE_Q4_K: launch_mul_mat_q_few_wmma_switch_ncols(src0, src1, dst, src1_q.get(), stream); break; case GGML_TYPE_Q5_K: launch_mul_mat_q_few_wmma_switch_ncols(src0, src1, dst, src1_q.get(), stream); break; case GGML_TYPE_Q6_K: launch_mul_mat_q_few_wmma_switch_ncols(src0, src1, dst, src1_q.get(), stream); break; case GGML_TYPE_IQ4_NL: launch_mul_mat_q_few_wmma_switch_ncols(src0, src1, dst, src1_q.get(), stream); break; default: GGML_ABORT("unsupported type for few-row MMQ with WMMA"); } } // NVFP4: whether src1 is 4-bit (the native FP4 MMA) or 8-bit. // 8-bit unless 4-bit is requested (GGML_CUDA_MMQ_PREC=q4 or by the graph): few-row batches are decode batches (one or more sequences, // draft tokens), whose precision should not depend on how many tokens are in the batch. 4-bit src1 changes the results much more. static bool mmq_few_use_fp4(const ggml_type type, const ggml_prec prec_requested, const int cc) { if (type != GGML_TYPE_NVFP4) { return false; } return ggml_cuda_mmq_get_prec_src1(type, prec_requested == GGML_PREC_UNDEFINED ? GGML_PREC_Q8 : prec_requested, cc) == GGML_PREC_Q4; } void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion) { GGML_TENSOR_BINARY_OP_LOCALS; GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); GGML_ASSERT( dst->type == GGML_TYPE_F32); GGML_ASSERT(nb00 == ggml_type_size(src0->type)); GGML_ASSERT(nb10 == ggml_type_size(src1->type)); GGML_ASSERT(nb0 == sizeof(float)); GGML_ASSERT(ne00 % QK_K == 0); if (mmq_few_use_wmma(ggml_cuda_info().devices[ctx.device].cc)) { GGML_ASSERT(!ids && !fusion); ggml_cuda_mul_mat_q_few_wmma(ctx, src0, src1, dst); return; } // fusion: only the scale of an NVFP4 or F8_E4M3 src0 const ggml_tensor * x_scale = fusion ? fusion->x_scale : nullptr; GGML_ASSERT(!fusion || (!ids && (src0->type == GGML_TYPE_NVFP4 || src0->type == GGML_TYPE_F8_E4M3) && !fusion->x_bias && !fusion->gate && !fusion->gate_bias && !fusion->gate_scale && !fusion->shared_up && !fusion->shared_gate && !fusion->shared_dst)); GGML_ASSERT(!x_scale || (x_scale->type == GGML_TYPE_F32 && ggml_nelements(x_scale) == 1)); const float * x_scale_d = x_scale ? (const float *) x_scale->data : nullptr; cudaStream_t stream = ctx.stream(); const int nunits = ne00 / QK_K; const int ncg = ids ? 1 : mmq_few_ncg(ne11); const int cc = ggml_cuda_info().devices[ctx.device].cc; const bool fp4 = !ids && mmq_few_use_fp4(src0->type, fusion ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc); if (src0->type == GGML_TYPE_F8_E4M3) { GGML_ASSERT(!ids); GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS); GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0); ggml_cuda_pool_alloc src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_F16_INT4); quantize_mmq_few_f16_cuda(src1->data, src1->type, src1_q.get(), ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream); launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, nullptr, 0, ncg, stream); return; } if (fp4) { GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS); GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0); ggml_cuda_pool_alloc src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_FP4_INT4); ggml_cuda_pool_alloc y_scale(ctx.pool(), int64_t(ne12)*ne13*ncg*MMQ_FEW_NCOLS); quantize_mmq_few_nvfp4_cuda(src1->data, src1->type, src1_q.get(), y_scale.get(), ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream); launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), y_scale.get(), x_scale_d, nullptr, 0, ncg, stream); return; } ggml_cuda_pool_alloc pairs(ctx.pool()); ggml_cuda_pool_alloc src1_q(ctx.pool()); int npairs_max = 0; if (ids) { GGML_ASSERT(ids->type == GGML_TYPE_I32); GGML_ASSERT(ids->nb[0] == ggml_type_size(ids->type)); GGML_ASSERT(ne1 == ids->ne[0] && ne13 == 1 && ne3 == 1); const int64_t n_expert_used = ids->ne[0]; const int64_t n_tokens = ids->ne[1]; const int64_t nentries = n_tokens*n_expert_used; const int64_t nused = std::min(ne02, nentries); // an expert with c > 0 entries (at most one per token) has ceil(c/MMQ_FEW_NCOLS) pairs npairs_max = (int) std::min(nused + (nentries - nused)/MMQ_FEW_NCOLS, ne02*((n_tokens + MMQ_FEW_NCOLS - 1) / MMQ_FEW_NCOLS)); pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS); src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4); quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type), ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream); } else { GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS); GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0); src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4); quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), src0->type == GGML_TYPE_NVFP4, ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream); } switch (src0->type) { case GGML_TYPE_Q8_0: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_Q3_K: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_Q4_K: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_Q5_K: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_Q6_K: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_IQ3_S: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_IQ4_NL: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_IQ4_XS: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; case GGML_TYPE_NVFP4: launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream); break; default: GGML_ABORT("unsupported type for few-row MMQ"); } } // Min. number of src1 columns (MUL_MAT_ID: tokens) for the few-row MMQ, 0 if it is not used for this type, GPU and row length. // fp4: NVFP4 with 4-bit src1 (only when requested, see mmq_few_use_fp4). static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const int64_t ne00, const bool has_ids, const bool fp4) { #ifdef GGML_CUDA_FORCE_CUBLAS return 0; #endif // GGML_CUDA_FORCE_CUBLAS if (mmq_few_use_wmma(cc)) { return has_ids || !mmq_few_wmma_supported(type) || ne00 < 8*QK_K ? 0 : mmq_few_wmma_ncols_range(type, cc).x; } // NVIDIA Ampere to Blackwell if (!ampere_mma_available(cc) || cc >= GGML_CUDA_CC_RUBIN) { return 0; } // on DGX Spark the kernel needs its L2 prefetch, which is only in the DGX Spark device code if (cc == GGML_CUDA_CC_GB10 && ggml_cuda_highest_compiled_arch(cc) != GGML_CUDA_CC_GB10) { return 0; } // with fewer than 8 units of 256 values per row the warps idle, MMVQ and MMQ are better there (MUL_MAT_ID splits the rows instead) if (mmq_few_unit_size(type) == 0 || (!has_ids && ne00 < 8*QK_K)) { return 0; } if (has_ids && !mmq_few_id_supported(type)) { return 0; } // NVFP4: only on Blackwell (cc 12.x), tuned on RTX 5090 and DGX Spark if (type == GGML_TYPE_NVFP4) { if (!blackwell_mma_available(cc)) { return 0; } if (cc == GGML_CUDA_CC_GB10) { return fp4 ? 8 : 9; // 8-bit src1 only gains from 9 columns } return fp4 ? 6 : 7; } // F8_E4M3: tuned on RTX 5090 and DGX Spark (Blackwell), RTX 4090 (Ada) and RTX 3090 Ti (Ampere) if (type == GGML_TYPE_F8_E4M3) { if (blackwell_mma_available(cc)) { return 2; } // Ada needs its own device code, as the E4M3 to FP16 conversion has a hardware instruction only from sm_89 if (cc == GGML_CUDA_CC_ADA_LOVELACE && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ADA_LOVELACE) { return 4; // equal to MMVF at 2-3 columns } if (cc == GGML_CUDA_CC_AMPERE_GA10X) { return 6; // slower than MMVF at 2-4 columns, equal at 5 } return 0; } if (cc == GGML_CUDA_CC_GB10) { // tuned on DGX Spark GB10, also for MUL_MAT_ID return type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_IQ4_NL ? 8 : 2; } if (has_ids) { // after MMVQ, which is faster up to its max. batch size return get_mmvq_mmid_max_batch(type, cc) + 1; } switch (type) { // all GPUs except DGX Spark, tuned on RTX 5090 case GGML_TYPE_Q3_K: return 3; case GGML_TYPE_Q5_K: return 3; case GGML_TYPE_Q4_K: return 4; case GGML_TYPE_IQ4_NL: return 4; case GGML_TYPE_Q6_K: return 4; case GGML_TYPE_Q8_0: return 5; case GGML_TYPE_IQ3_S: return 5; case GGML_TYPE_IQ4_XS: return 6; default: return 0; } } bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const ggml_tensor * dst, const int cc) { if (src0->nb[0] != ggml_type_size(src0->type) || src1->nb[0] != ggml_type_size(src1->type)) { return false; } const int64_t ncols = ids ? ids->ne[1] : src1->ne[1]; const ggml_prec prec_requested = ggml_prec_get_src(dst, 1); // NVFP4: src1 precisions that MMQ does not take (e.g. F16 without GGML_CUDA_MMQ_PREC) stay with MMVQ and MMQ, like without few-row if (src0->type == GGML_TYPE_NVFP4 && !ggml_cuda_mmq_prec_src1_supported(prec_requested)) { return false; } // F8_E4M3: few-row converts src1 to F16, F32 and BF16 requests do not allow that if (src0->type == GGML_TYPE_F8_E4M3 && (prec_requested == GGML_PREC_F32 || prec_requested == GGML_PREC_BF16)) { return false; } const bool fp4 = !ids && mmq_few_use_fp4(src0->type, prec_requested, cc); const int min_ncols = ggml_cuda_mmq_few_min_ncols(src0->type, cc, src0->ne[0], ids != nullptr, fp4); if (min_ncols == 0 || ncols < min_ncols || ncols > MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS) { return false; } // MUL_MAT: the src1 quantizer launches ne12*ne13 CUDA blocks in z, the limit is 65535 if (!ids && src1->ne[2]*src1->ne[3] > 65535) { return false; } // MUL_MAT_ID: the pairs are built in shared memory if (ids && (2*src0->ne[2] + 1)*sizeof(int) > ggml_cuda_info().devices[ggml_cuda_get_device()].smpb) { return false; } if (mmq_few_use_wmma(cc)) { if (src1->ne[1] > mmq_few_wmma_ncols_range(src0->type, cc).y || src0->ne[0] % QK_K != 0) { return false; } // the decoders read whole 4 byte values from 16 byte aligned units, Q6_K values 2 bytes at a time const int x_alignment = mmq_few_unaligned(src0->type, 1) ? 2 : 16; return ggml_cuda_is_aligned(src0, x_alignment) && ggml_cuda_is_aligned(src1, 16); } // the row must hold a whole number of ring stages of the launched kernel const int ncg = ids ? 1 : mmq_few_ncg(ncols); const int nmt = ids ? 1 : mmq_few_nmt(src0->type, ncg, src0->ne[1], fp4); const int nunits_stage = mmq_few_nunits_stage(src0->type, ncg, nmt, fp4); if (src0->ne[0] % (nunits_stage*QK_K) != 0) { return false; } // unaligned data needs the alignment of the decoder loads const int x_alignment = mmq_few_unaligned(src0->type, nunits_stage) ? (ggml_type_size(src0->type) % 4 == 0 ? 4 : 2) : 16; return ggml_cuda_is_aligned(src0, x_alignment) && ggml_cuda_is_aligned(src1, 16); } #else // !defined(GGML_USE_MUSA) void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion) { GGML_UNUSED_VARS(ctx, src0, src1, ids, dst, fusion); GGML_ABORT("few-row MMQ is not supported on MUSA"); } bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const ggml_tensor * dst, const int cc) { GGML_UNUSED_VARS(src0, src1, ids, dst, cc); return false; } #endif // !defined(GGML_USE_MUSA)