diff --git a/ggml/src/ggml-cuda/fusion.cu b/ggml/src/ggml-cuda/fusion.cu index 48879aae96ed..d5eff36cb844 100644 --- a/ggml/src/ggml-cuda/fusion.cu +++ b/ggml/src/ggml-cuda/fusion.cu @@ -4,6 +4,7 @@ #include "concat.cuh" #include "dsv4-hc.cuh" #include "fp8.cuh" +#include "fwht.cuh" #include "gated_delta_net.cuh" #include "inkling2.cuh" #include "mmsm.cuh" @@ -2354,6 +2355,97 @@ static int ggml_cuda_try_fuse_rms_norm2(ggml_backend_cuda_context * cuda_ctx, gg return n1 + 1; } +// the K/V cache stores fused with the op that makes the rows, GGML_CUDA_NO_KV_STORE_FUSION=1 turns them off +static bool ggml_cuda_kv_store_fusion_disabled() { + static const bool disabled = getenv("GGML_CUDA_NO_KV_STORE_FUSION") != nullptr; + return disabled; +} + +// Hadamard rotation of K or V (MUL_MAT with the Hadamard hint) stored in a quantized cache: MUL_MAT, RESHAPE, VIEW, +// [RESHAPE of the cache,] SET_ROWS -> one kernel that rotates, quantizes and stores +static int ggml_cuda_try_fuse_fwht_set_rows(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + if (ggml_cuda_kv_store_fusion_disabled() || cuda_ctx->curr_stream_no != 0) { + return 0; + } + ggml_tensor ** n = cgraph->nodes + i; + if (i + 3 >= cgraph->n_nodes || !ggml_cuda_op_mul_mat_use_fwht(n[0]) || n[1]->op != GGML_OP_RESHAPE || n[1]->src[0] != n[0] || + n[2]->op != GGML_OP_VIEW || n[2]->src[0] != n[1] || n[2]->view_offs != 0) { + return 0; + } + int last = i + 3; + if (n[3]->op == GGML_OP_RESHAPE && i + 4 < cgraph->n_nodes && n[4]->op == GGML_OP_SET_ROWS && n[4]->src[2] == n[3]) { + last = i + 4; + } + ggml_tensor * set_rows = cgraph->nodes[last]; + if (set_rows->op != GGML_OP_SET_ROWS || set_rows->src[0] != n[2] || (set_rows->type != GGML_TYPE_Q8_0 && set_rows->type != GGML_TYPE_Q4_0) || + !ggml_is_contiguous(n[2])) { + return 0; + } + const ggml_op ops4[] = { GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; + const ggml_op ops5[] = { GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_RESHAPE, GGML_OP_SET_ROWS }; + const int outputs[] = { last }; + if (!ggml_can_fuse_subgraph(cgraph, i, last - i + 1, last == i + 3 ? ops4 : ops5, outputs, 1)) { + return 0; + } + if (!ggml_cuda_op_fwht_set_rows(*cuda_ctx, n[0]->src[1], set_rows)) { + return 0; + } + return last - i; +} + +// RMS norm without weight of V stored in the cache (Gemma 4, Inkling 2) -> one kernel: RMS_NORM, VIEW, [RESHAPE of the cache,] +// SET_ROWS for a F16 / F32 / BF16 cache, RMS_NORM, RESHAPE, MUL_MAT (Hadamard), RESHAPE, VIEW, [RESHAPE,] SET_ROWS for a rotated q8_0 / q4_0 cache +static int ggml_cuda_try_fuse_rms_norm_set_rows(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + if (ggml_cuda_kv_store_fusion_disabled() || cuda_ctx->curr_stream_no != 0) { + return 0; + } + ggml_tensor ** n = cgraph->nodes + i; + if (n[0]->op != GGML_OP_RMS_NORM) { + return 0; + } + // rotated quantized cache: RMS_NORM, RESHAPE, MUL_MAT (Hadamard), RESHAPE, VIEW, [RESHAPE of the cache,] SET_ROWS + if (i + 5 < cgraph->n_nodes && n[1]->op == GGML_OP_RESHAPE && n[1]->src[0] == n[0] && ggml_cuda_op_mul_mat_use_fwht(n[2]) && + n[2]->src[1] == n[1] && n[3]->op == GGML_OP_RESHAPE && n[3]->src[0] == n[2] && n[4]->op == GGML_OP_VIEW && + n[4]->src[0] == n[3] && n[4]->view_offs == 0 && ggml_is_contiguous(n[4])) { + int last = i + 5; + if (n[5]->op == GGML_OP_RESHAPE && i + 6 < cgraph->n_nodes && n[6]->op == GGML_OP_SET_ROWS && n[6]->src[2] == n[5]) { + last = i + 6; + } + ggml_tensor * set_rows = cgraph->nodes[last]; + if (set_rows->op != GGML_OP_SET_ROWS || set_rows->src[0] != n[4]) { + return 0; + } + const ggml_op ops6[] = { GGML_OP_RMS_NORM, GGML_OP_RESHAPE, GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; + const ggml_op ops7[] = { GGML_OP_RMS_NORM, GGML_OP_RESHAPE, GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_RESHAPE, GGML_OP_SET_ROWS }; + const int outputs[] = { last }; + if (!ggml_can_fuse_subgraph(cgraph, i, last - i + 1, last == i + 5 ? ops6 : ops7, outputs, 1)) { + return 0; + } + return ggml_cuda_op_rms_norm_fwht_set_rows(*cuda_ctx, n[0], n[2], set_rows) ? last - i : 0; + } + if (i + 2 >= cgraph->n_nodes || n[1]->op != GGML_OP_VIEW || n[1]->src[0] != n[0] || n[1]->view_offs != 0 || !ggml_is_contiguous(n[1])) { + return 0; + } + int last = i + 2; + if (n[2]->op == GGML_OP_RESHAPE && i + 3 < cgraph->n_nodes && n[3]->op == GGML_OP_SET_ROWS && n[3]->src[2] == n[2]) { + last = i + 3; + } + ggml_tensor * set_rows = cgraph->nodes[last]; + if (set_rows->op != GGML_OP_SET_ROWS || set_rows->src[0] != n[1]) { + return 0; + } + const ggml_op ops3[] = { GGML_OP_RMS_NORM, GGML_OP_VIEW, GGML_OP_SET_ROWS }; + const ggml_op ops4[] = { GGML_OP_RMS_NORM, GGML_OP_VIEW, GGML_OP_RESHAPE, GGML_OP_SET_ROWS }; + const int outputs[] = { last }; + if (!ggml_can_fuse_subgraph(cgraph, i, last - i + 1, last == i + 2 ? ops3 : ops4, outputs, 1)) { + return 0; + } + if (!ggml_cuda_op_rms_norm_set_rows(*cuda_ctx, n[0], set_rows)) { + return 0; + } + return last - i; +} + // try and fuse nodes and return the number of nodes to skip int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { if (int n = ggml_cuda_try_fuse_inkling2(cuda_ctx, cgraph, i)) { @@ -2362,6 +2454,18 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap ggml_tensor * node = cgraph->nodes[i]; + if (node->op == GGML_OP_MUL_MAT) { + if (int n = ggml_cuda_try_fuse_fwht_set_rows(cuda_ctx, cgraph, i)) { + return n; + } + } + + if (node->op == GGML_OP_RMS_NORM) { + if (int n = ggml_cuda_try_fuse_rms_norm_set_rows(cuda_ctx, cgraph, i)) { + return n; + } + } + // a scaled matmul only takes part in the gate/up/GLU fusion, which passes its weight scale on const bool scaled_mm = (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) && ggml_get_src_scale(node, 0); diff --git a/ggml/src/ggml-cuda/fwht.cu b/ggml/src/ggml-cuda/fwht.cu index 0ee3da6a3cb3..f9cd140cf1a9 100644 --- a/ggml/src/ggml-cuda/fwht.cu +++ b/ggml/src/ggml-cuda/fwht.cu @@ -2,6 +2,8 @@ #include "convert.cuh" #include "fwht.cuh" +#include + // wide FWHT blocks use one row per thread block with this many threads #define GGML_CUDA_FWHT_BLOCK_NT 256 @@ -240,3 +242,315 @@ bool ggml_cuda_op_fwht(ggml_backend_cuda_context & ctx, const ggml_tensor * src, return false; } } + +// quantization of one block of 32 values held by the 32 lanes of a warp (value v of lane l is element l of the block), +// the arithmetic of quantize_f32_q8_0_block / quantize_f32_q4_0_block +template +static __device__ __forceinline__ void fwht_quantize_block_warp(const float v, block_t * y, const int lane) { + constexpr int warp_size = 32; + const float amax = warp_reduce_max<32>(fabsf(v)); + if constexpr (std::is_same_v) { + const float d = amax / ((1 << 7) - 1); + const float id = d ? 1.0f/d : 0.0f; + y->qs[lane] = roundf(v*id); + if (lane == 0) { + y->d = d; + } + } else { + static_assert(std::is_same_v, "unsupported block type"); + // the value of the first element with the largest magnitude + int first = fabsf(v) == amax ? lane : warp_size; +#pragma unroll + for (int offset = warp_size/2; offset > 0; offset >>= 1) { + first = min(first, ggml_cuda_shfl_xor(first, offset, warp_size)); + } + const float vfirst = ggml_cuda_shfl(v, first < warp_size ? first : 0, warp_size); + const float vmax = amax == 0.0f ? 0.0f : vfirst; + const float d = vmax / -8; + const float id = d ? 1.0f/d : 0.0f; + const float v_hi = ggml_cuda_shfl_xor(v, QK4_0/2, warp_size); + if (lane < QK4_0/2) { + const float x0 = v*id; + const float x1 = v_hi*id; + + const uint8_t xi0 = min(15, (int8_t)(x0 + 8.5f)); + const uint8_t xi1 = min(15, (int8_t)(x1 + 8.5f)); + + y->qs[lane] = xi0 | (xi1 << 4); + } + if (lane == 0) { + y->d = d; + } + } +} + +// FWHT of rows of N values, quantized to q8_0 / q4_0 and stored as rows of a K/V cache (MUL_MAT Hadamard + SET_ROWS). +// One warp per FWHT row as in fwht_cuda; quantization block j is register j of the 32 lanes. The arithmetic is that of +// fwht_cuda followed by k_set_rows_quant, so the stored blocks are the same. +template +__launch_bounds__(4*ggml_cuda_get_physical_warp_size(), 1) +__global__ void fwht_set_rows_q(const float * src, const idx_t * idxs, char * dst, const int64_t n_rows, + const int rows_per_idx, const int64_t nb_dst_row, const float scale) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + if constexpr (warp_size != 32) { + GGML_UNUSED_VARS(src, idxs, dst, n_rows, rows_per_idx, nb_dst_row, scale); + NO_DEVICE_CODE; + } else { + const int64_t r = (int64_t) blockIdx.x * blockDim.y + threadIdx.y; + if (r >= n_rows) { + return; + } + src += r * N; + + static constexpr int el_w = N / warp_size; + float reg[el_w]; + const int lane = threadIdx.x; + + ggml_cuda_pdl_sync(); +#pragma unroll + for (int i = 0; i < el_w; ++i) { + reg[i] = src[i * warp_size + lane] * scale; + } + +#pragma unroll + for (int h = 1; h < warp_size; h *= 2) { +#pragma unroll + for (int j = 0; j < el_w; j++) { + const float val = reg[j]; + const float val2 = ggml_cuda_shfl_xor(val, h, warp_size); + + reg[j] = (lane & h) == 0 ? val + val2 : val2 - val; + } + } + +#pragma unroll + for (int h = warp_size; h < N; h *= 2) { + const int step = h / warp_size; +#pragma unroll + for (int j = 0; j < el_w; j += 2 * step) { +#pragma unroll + for (int k = 0; k < step; k++) { + const float x = reg[j + k]; + const float y = reg[j + k + step]; + + reg[j + k] = x + y; + reg[j + k + step] = x - y; + } + } + } + + const int64_t t = r / rows_per_idx; + const int c = (int) (r - t * rows_per_idx); + block_t * y_row = (block_t *) (dst + (int64_t) idxs[t] * nb_dst_row) + c * (N / 32); + +#pragma unroll + for (int j = 0; j < el_w; ++j) { + fwht_quantize_block_warp(reg[j], y_row + j, lane); + } + } +} + +template +static bool ggml_cuda_op_fwht_set_rows_impl(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * set_rows, const int rows_per_idx) { + const int n = x->ne[0]; + const int64_t n_rows = ggml_nrows(x); + + const float * x_d = (const float *) x->data; + const idx_t * idx_d = (const idx_t *) set_rows->src[1]->data; + char * dst_d = (char *) set_rows->data; + + const int rows_per_block = 4; + const dim3 grid_dims((n_rows + rows_per_block - 1) / rows_per_block, 1, 1); + const dim3 block_dims(32, rows_per_block, 1); + const ggml_cuda_kernel_launch_params launch_params(grid_dims, block_dims, 0, ctx.stream()); + + const float scale = 1 / sqrtf(n); + + switch (n) { + case 64: + ggml_cuda_kernel_launch(fwht_set_rows_q<64, block_t, idx_t>, launch_params, x_d, idx_d, dst_d, n_rows, rows_per_idx, (int64_t) set_rows->nb[1], scale); + return true; + case 128: + ggml_cuda_kernel_launch(fwht_set_rows_q<128, block_t, idx_t>, launch_params, x_d, idx_d, dst_d, n_rows, rows_per_idx, (int64_t) set_rows->nb[1], scale); + return true; + case 256: + ggml_cuda_kernel_launch(fwht_set_rows_q<256, block_t, idx_t>, launch_params, x_d, idx_d, dst_d, n_rows, rows_per_idx, (int64_t) set_rows->nb[1], scale); + return true; + case 512: + ggml_cuda_kernel_launch(fwht_set_rows_q<512, block_t, idx_t>, launch_params, x_d, idx_d, dst_d, n_rows, rows_per_idx, (int64_t) set_rows->nb[1], scale); + return true; + default: + return false; + } +} + +// x: the F32 rows of the Hadamard MUL_MAT (src1), set_rows: the SET_ROWS that stores its result (through views) +bool ggml_cuda_op_fwht_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * set_rows) { + const ggml_tensor * rows = set_rows->src[0]; + const ggml_tensor * idx = set_rows->src[1]; + + const int n = x->ne[0]; + if (ggml_cuda_info().devices[ctx.device].warp_size != 32 || x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || + (n != 64 && n != 128 && n != 256 && n != 512)) { + return false; + } + // 2D rows and indices only, every stored row made of whole FWHT rows + if (rows->ne[2] != 1 || rows->ne[3] != 1 || idx->ne[1] != 1 || idx->ne[2] != 1 || !ggml_is_contiguous(idx) || + set_rows->ne[2] != 1 || set_rows->ne[3] != 1 || rows->ne[0] % n != 0 || idx->ne[0] != rows->ne[1] || + ggml_nrows(x) != (rows->ne[0] / n) * rows->ne[1] || set_rows->nb[0] != ggml_type_size(set_rows->type)) { + return false; + } + const int rows_per_idx = rows->ne[0] / n; + + if (set_rows->type == GGML_TYPE_Q8_0) { + return idx->type == GGML_TYPE_I64 ? ggml_cuda_op_fwht_set_rows_impl(ctx, x, set_rows, rows_per_idx) + : ggml_cuda_op_fwht_set_rows_impl(ctx, x, set_rows, rows_per_idx); + } + if (set_rows->type == GGML_TYPE_Q4_0) { + return idx->type == GGML_TYPE_I64 ? ggml_cuda_op_fwht_set_rows_impl(ctx, x, set_rows, rows_per_idx) + : ggml_cuda_op_fwht_set_rows_impl(ctx, x, set_rows, rows_per_idx); + } + return false; +} + +// RMS norm without weight of each head row (V of Gemma 4 / Inkling 2), FWHT of its NROT-value rows, quantized and stored as cache +// rows: rms_norm_f32 (vector path with the same block size) + fwht_cuda + k_set_rows_quant in one kernel, with the same arithmetic. +template +__launch_bounds__(BLOCK, 1) +__global__ void rms_norm_fwht_set_rows_q(const float * x, const idx_t * idxs, char * dst, const int nheads, const int64_t nb_dst_row, + const float eps, const float scale_h) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + if constexpr (warp_size != 32) { + GGML_UNUSED_VARS(x, idxs, dst, nheads, nb_dst_row, eps, scale_h); + NO_DEVICE_CODE; + } else { + static_assert(HEAD % NROT == 0 && HEAD/4 <= BLOCK && BLOCK % 32 == 0 && (HEAD/NROT) % (BLOCK/32) == 0, "bad shape"); + constexpr int n4 = HEAD/4; + constexpr int nwarps = BLOCK/32; + constexpr int el_w = NROT/32; + + __shared__ float s_sum[32]; + __shared__ float4 s_row[n4]; + + const int row = blockIdx.x; + const int tid = threadIdx.x; + + ggml_cuda_pdl_sync(); + + const float4 * x4 = (const float4 *) (x + (int64_t) row*HEAD); + float4 xs = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float tmp = 0.0f; + if (tid < n4) { + xs = x4[tid]; + tmp = xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + } + tmp = block_reduce(tmp, s_sum); + const float scale = rsqrtf(tmp / HEAD + eps); + if (tid < n4) { + s_row[tid] = make_float4(scale*xs.x, scale*xs.y, scale*xs.z, scale*xs.w); + } + __syncthreads(); + + const float * v = (const float *) s_row; + const int lane = tid % 32; + const int warp = tid / 32; + const int t = row / nheads; + const int h = row - t*nheads; + block_t * y_head = (block_t *) (dst + (int64_t) idxs[t]*nb_dst_row) + h*(HEAD/32); + +#pragma unroll + for (int rr = warp; rr < HEAD/NROT; rr += nwarps) { + float reg[el_w]; +#pragma unroll + for (int i = 0; i < el_w; ++i) { + reg[i] = v[rr*NROT + i*32 + lane] * scale_h; + } +#pragma unroll + for (int hh = 1; hh < 32; hh *= 2) { +#pragma unroll + for (int j = 0; j < el_w; j++) { + const float val = reg[j]; + const float val2 = ggml_cuda_shfl_xor(val, hh, 32); + reg[j] = (lane & hh) == 0 ? val + val2 : val2 - val; + } + } +#pragma unroll + for (int hh = 32; hh < NROT; hh *= 2) { + const int step = hh / 32; +#pragma unroll + for (int j = 0; j < el_w; j += 2 * step) { +#pragma unroll + for (int k = 0; k < step; k++) { + const float a = reg[j + k]; + const float b = reg[j + k + step]; + reg[j + k] = a + b; + reg[j + k + step] = a - b; + } + } + } +#pragma unroll + for (int j = 0; j < el_w; ++j) { + fwht_quantize_block_warp(reg[j], y_head + rr*(NROT/32) + j, lane); + } + } + } +} + +template +static bool ggml_cuda_op_rms_norm_fwht_set_rows_impl(ggml_backend_cuda_context & ctx, const float * x, const idx_t * idx, char * dst, + const int head, const int nrot, const int nheads, const int nrows, const int64_t nb_dst_row, const float eps) { + const dim3 grid_dims(nrows, 1, 1); + const float scale_h = 1 / sqrtf(nrot); + cudaStream_t stream = ctx.stream(); + // block sizes of rms_norm_f32_dispatch for HEAD/4 float4 values + if (head == 256 && nrot == 64) { + ggml_cuda_kernel_launch(rms_norm_fwht_set_rows_q<256, 64, 128, block_t, idx_t>, + ggml_cuda_kernel_launch_params(grid_dims, dim3(128, 1, 1), 0, stream), x, idx, dst, nheads, nb_dst_row, eps, scale_h); + return true; + } + if (head == 512 && nrot == 64) { + ggml_cuda_kernel_launch(rms_norm_fwht_set_rows_q<512, 64, 128, block_t, idx_t>, + ggml_cuda_kernel_launch_params(grid_dims, dim3(128, 1, 1), 0, stream), x, idx, dst, nheads, nb_dst_row, eps, scale_h); + return true; + } + if (head == 128 && nrot == 64) { + ggml_cuda_kernel_launch(rms_norm_fwht_set_rows_q<128, 64, 32, block_t, idx_t>, + ggml_cuda_kernel_launch_params(grid_dims, dim3(32, 1, 1), 0, stream), x, idx, dst, nheads, nb_dst_row, eps, scale_h); + return true; + } + return false; +} + +bool ggml_cuda_op_rms_norm_fwht_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * norm, const ggml_tensor * mm, const ggml_tensor * set_rows) { + const ggml_tensor * x = norm->src[0]; + const ggml_tensor * rows = set_rows->src[0]; + const ggml_tensor * idx = set_rows->src[1]; + + float eps = 0.0f; + memcpy(&eps, norm->op_params, sizeof(float)); + + const int64_t head = x->ne[0]; + const int64_t nheads = x->ne[1]; + const int64_t ntok = x->ne[2]; + const int64_t nrot = mm->src[1]->ne[0]; + if (ggml_cuda_info().devices[ctx.device].warp_size != 32 || x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || x->ne[3] != 1 || + !ggml_cuda_is_aligned(x, 16) || rows->ne[0] != head*nheads || rows->ne[1] != ntok || rows->ne[2] != 1 || rows->ne[3] != 1 || + idx->ne[0] != ntok || idx->ne[1] != 1 || idx->ne[2] != 1 || !ggml_is_contiguous(idx) || + set_rows->ne[2] != 1 || set_rows->ne[3] != 1 || set_rows->nb[0] != ggml_type_size(set_rows->type) || ntok*nheads > INT_MAX) { + return false; + } + const float * x_d = (const float *) x->data; + char * dst_d = (char *) set_rows->data; + const int nrows = (int) (ntok*nheads); + if (set_rows->type == GGML_TYPE_Q8_0) { + return idx->type == GGML_TYPE_I64 + ? ggml_cuda_op_rms_norm_fwht_set_rows_impl(ctx, x_d, (const int64_t *) idx->data, dst_d, head, nrot, nheads, nrows, set_rows->nb[1], eps) + : ggml_cuda_op_rms_norm_fwht_set_rows_impl(ctx, x_d, (const int32_t *) idx->data, dst_d, head, nrot, nheads, nrows, set_rows->nb[1], eps); + } + if (set_rows->type == GGML_TYPE_Q4_0) { + return idx->type == GGML_TYPE_I64 + ? ggml_cuda_op_rms_norm_fwht_set_rows_impl(ctx, x_d, (const int64_t *) idx->data, dst_d, head, nrot, nheads, nrows, set_rows->nb[1], eps) + : ggml_cuda_op_rms_norm_fwht_set_rows_impl(ctx, x_d, (const int32_t *) idx->data, dst_d, head, nrot, nheads, nrows, set_rows->nb[1], eps); + } + return false; +} diff --git a/ggml/src/ggml-cuda/fwht.cuh b/ggml/src/ggml-cuda/fwht.cuh index e7ad53475b1e..07be190e4442 100644 --- a/ggml/src/ggml-cuda/fwht.cuh +++ b/ggml/src/ggml-cuda/fwht.cuh @@ -4,3 +4,9 @@ bool ggml_cuda_op_mul_mat_use_fwht(const struct ggml_tensor * op); // Returns whether the Fast Walsh-Hadamard transform could be used. bool ggml_cuda_op_fwht(ggml_backend_cuda_context & ctx, const ggml_tensor * src, ggml_tensor * dst); + +// FWHT of the rows of x, quantized and stored by set_rows (q8_0 / q4_0); false if the shapes are not supported +bool ggml_cuda_op_fwht_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * set_rows); + +// RMS_NORM without weight -> Hadamard MUL_MAT (mm) -> SET_ROWS into a q8_0 / q4_0 cache in one kernel; false if not supported +bool ggml_cuda_op_rms_norm_fwht_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * norm, const ggml_tensor * mm, const ggml_tensor * set_rows); diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index dda3faaa37d2..9ceaca6ef87c 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -1333,6 +1333,121 @@ bool ggml_cuda_op_rms_norm2(ggml_backend_cuda_context & ctx, const ggml_tensor * return true; } +// RMS norm without weight of the rows of V, stored in the K/V cache (VIEW + SET_ROWS): one block per row as the vector path of +// rms_norm_f32 with the same block size, so the norm is the same; the row goes to cache row idx[token] at column head*ncols. +template +static __global__ void rms_norm_set_rows_f32(const float * x, const idx_t * idxs, char * dst, const int ncols, const int nheads, + const int64_t nb_dst_row, const float eps) { + ggml_cuda_pdl_lc(); + const int row = blockIdx.x; + const int tid = threadIdx.x; + + extern __shared__ float s_sum[]; + + ggml_cuda_pdl_sync(); + + const int ncols4 = ncols / 4; + const float4 * x4 = (const float4 *) (x + (int64_t) row*ncols); + + float4 xs = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float tmp = 0.0f; + if (tid < ncols4) { + xs = x4[tid]; + tmp = xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + } + tmp = block_reduce(tmp, s_sum); + const float scale = rsqrtf(tmp / ncols + eps); + + if (tid < ncols4) { + const int t = row / nheads; + const int h = row - t*nheads; + D * d = (D *) (dst + (int64_t) idxs[t]*nb_dst_row) + (int64_t) h*ncols + 4*tid; + float4 r = make_float4(scale*xs.x, scale*xs.y, scale*xs.z, scale*xs.w); +#if defined(GGML_USE_HIP) + // the F32 product is rounded before the conversion, as in the unfused path: no mixed-precision FMA to F16 + asm volatile("" : "+v"(r.x), "+v"(r.y), "+v"(r.z), "+v"(r.w)); +#endif // defined(GGML_USE_HIP) + d[0] = ggml_cuda_cast(r.x); + d[1] = ggml_cuda_cast(r.y); + d[2] = ggml_cuda_cast(r.z); + d[3] = ggml_cuda_cast(r.w); + } +} + +template +static void rms_norm_set_rows_f32_cuda(const float * x, const idx_t * idxs, char * dst, const int ncols, const int nheads, const int nrows, + const int64_t nb_dst_row, const float eps, cudaStream_t stream) { + const int n4 = ncols / 4; + const dim3 blocks_num(nrows, 1, 1); +#define RMS_NORM_SET_ROWS_LAUNCH(BS) \ + do { \ + const ggml_cuda_kernel_launch_params launch_params{ blocks_num, dim3(BS, 1, 1), BS > WARP_SIZE ? 32 * sizeof(float) : 0, stream }; \ + ggml_cuda_kernel_launch(rms_norm_set_rows_f32, launch_params, x, idxs, dst, ncols, nheads, nb_dst_row, eps); \ + } while (0) + // the block sizes of rms_norm_f32_dispatch for one float4 per thread + if (n4 <= 32) { + RMS_NORM_SET_ROWS_LAUNCH(32); + } else if (n4 <= 128) { + RMS_NORM_SET_ROWS_LAUNCH(128); + } else if (n4 <= 256) { + RMS_NORM_SET_ROWS_LAUNCH(256); + } else if (n4 <= 512) { + RMS_NORM_SET_ROWS_LAUNCH(512); + } else { + RMS_NORM_SET_ROWS_LAUNCH(1024); + } +#undef RMS_NORM_SET_ROWS_LAUNCH +} + +bool ggml_cuda_op_rms_norm_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * norm, const ggml_tensor * set_rows) { + const ggml_tensor * x = norm->src[0]; + const ggml_tensor * rows = set_rows->src[0]; + const ggml_tensor * idx = set_rows->src[1]; + + float eps = 0.0f; + memcpy(&eps, norm->op_params, sizeof(float)); + + const int64_t ncols = x->ne[0]; + const int64_t nheads = x->ne[1]; + const int64_t ntok = x->ne[2]; + // contiguous F32 rows of whole float4 (the vector path of rms_norm_f32), 2D rows and indices + if (x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || x->ne[3] != 1 || ncols % 4 != 0 || ncols/4 > 1024 || !ggml_cuda_is_aligned(x, 16) || + rows->ne[0] != ncols*nheads || rows->ne[1] != ntok || rows->ne[2] != 1 || rows->ne[3] != 1 || + idx->ne[0] != ntok || idx->ne[1] != 1 || idx->ne[2] != 1 || !ggml_is_contiguous(idx) || + set_rows->ne[2] != 1 || set_rows->ne[3] != 1 || ntok*nheads > INT_MAX) { + return false; + } + + const char * idx_d = (const char *) idx->data; + char * dst_d = (char *) set_rows->data; + const float * x_d = (const float *) x->data; + const int64_t nb1 = set_rows->nb[1]; + cudaStream_t stream = ctx.stream(); + +#define RMS_NORM_SET_ROWS_TYPES(D) \ + do { \ + if (idx->type == GGML_TYPE_I64) { \ + rms_norm_set_rows_f32_cuda(x_d, (const int64_t *) idx_d, dst_d, ncols, nheads, ntok*nheads, nb1, eps, stream); \ + } else { \ + rms_norm_set_rows_f32_cuda(x_d, (const int32_t *) idx_d, dst_d, ncols, nheads, ntok*nheads, nb1, eps, stream); \ + } \ + } while (0) + switch (set_rows->type) { + case GGML_TYPE_F16: + RMS_NORM_SET_ROWS_TYPES(half); + return true; + case GGML_TYPE_F32: + RMS_NORM_SET_ROWS_TYPES(float); + return true; + case GGML_TYPE_BF16: + RMS_NORM_SET_ROWS_TYPES(nv_bfloat16); + return true; + default: + return false; + } +#undef RMS_NORM_SET_ROWS_TYPES +} + void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * grad = dst->src[0]; // gradients const ggml_tensor * src0f = dst->src[1]; // src0 from forward pass diff --git a/ggml/src/ggml-cuda/norm.cuh b/ggml/src/ggml-cuda/norm.cuh index 4594b51f0bfa..2ecb85cb05c8 100644 --- a/ggml/src/ggml-cuda/norm.cuh +++ b/ggml/src/ggml-cuda/norm.cuh @@ -34,3 +34,6 @@ void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst); // [MUL by w ->] L2_NORM -> SCALE [-> MUL by f], w broadcasts over the rows, f is one value per channel/sample void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm, const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst); + +// RMS_NORM without weight -> VIEW -> SET_ROWS (F16 / F32 / BF16 cache) in one kernel; false (nothing launched) if not supported +bool ggml_cuda_op_rms_norm_set_rows(ggml_backend_cuda_context & ctx, const ggml_tensor * norm, const ggml_tensor * set_rows); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index bb13d5510a00..7a5411d17a4a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3502,8 +3502,13 @@ ggml_tensor * llm_graph_context::build_attn( // these nodes are added to the graph together so that they are not reordered // by doing so, the number of splits in the graph is reduced // expand k later to enable rope fusion which directly writes into k-v cache + // with the K/V cache on the device, V is stored right after it is made, so that the store can be fused with the op that makes V + const bool store_v_early = !cparams.training && cparams.offload_kqv; ggml_build_forward_expand(gf, q_cur); ggml_build_forward_expand(gf, v_cur); + if (store_v_early) { + ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, inp->get_v_idxs(), il)); + } ggml_build_forward_expand(gf, k_cur); ggml_tensor * q = q_cur; @@ -3521,7 +3526,9 @@ ggml_tensor * llm_graph_context::build_attn( const auto & v_idxs = inp->get_v_idxs(); ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); - ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); + if (!store_v_early) { + ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); + } } k = mctx_cur->get_k(ctx0, il); @@ -3785,26 +3792,35 @@ static ggml_tensor * build_attn_iswa_impl( build_attn_scale_kv_inputs(ctx0, mctx_cur, k_cur, v_cur, il); + // whole seq fits into batch in training mode + const bool use_kv_cur = cparams.training && k_cur && v_cur; + if (use_kv_cur) { + GGML_ASSERT(mctx_cur->get_n_kv() == gctx.n_tokens); + } + + const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; + // these nodes are added to the graph together so that they are not reordered // by doing so, the number of splits in the graph is reduced // expand k later to enable rope fusion which directly writes into k-v cache + // with the K/V cache on the device, V is stored right after it is made, so that the store can be fused with the op that makes V + const bool store_v_early = store_kv && v_cur && cparams.offload_kqv; + ggml_build_forward_expand(gf, q_cur); if (v_cur) { ggml_build_forward_expand(gf, v_cur); } - if (k_cur) { - ggml_build_forward_expand(gf, k_cur); - } + if (store_v_early) { + const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); - // whole seq fits into batch in training mode - const bool use_kv_cur = cparams.training && k_cur && v_cur; - if (use_kv_cur) { - GGML_ASSERT(mctx_cur->get_n_kv() == gctx.n_tokens); + ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); } - const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; + if (k_cur) { + ggml_build_forward_expand(gf, k_cur); + } // optionally store to KV cache if (store_kv && k_cur) { @@ -3813,7 +3829,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); } - if (store_kv && v_cur) { + if (store_kv && v_cur && !store_v_early) { const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 8d763f613f6a..c3aa490e347b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10079,6 +10079,145 @@ struct test_rms_norm2_alias : public test_case { } }; +// V of Gemma 4: RMS norm without weight of each head, stored in the cache (RMS_NORM, VIEW, SET_ROWS). Backends may fuse it. +struct test_rms_norm_set_rows : public test_case { + const ggml_type type_dst; + const ggml_type type_idx; + const int64_t head_dim; + const int64_t n_head; + const int64_t n_tokens; + const int64_t n_cache; + + test_rms_norm_set_rows(ggml_type type_dst, ggml_type type_idx, int64_t head_dim, int64_t n_head, int64_t n_tokens, int64_t n_cache) + : type_dst(type_dst), type_idx(type_idx), head_dim(head_dim), n_head(n_head), n_tokens(n_tokens), n_cache(n_cache) {} + + std::string vars() override { + return VARS_TO_STR6(type_dst, type_idx, head_dim, n_head, n_tokens, n_cache); + } + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "RMS_NORM_SET_ROWS"; + } + + bool run_whole_graph() override { return true; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, head_dim, n_head, n_tokens); + ggml_set_name(x, "x"); + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type_dst, head_dim*n_head, n_cache); + ggml_set_name(cache, "cache"); + ggml_tensor * idxs = ggml_new_tensor_1d(ctx, type_idx, n_tokens); + ggml_set_name(idxs, "idxs"); + + // the input of the norm is made by an op, as V is + x = ggml_scale(ctx, x, 1.5f); + ggml_tensor * v = ggml_rms_norm(ctx, x, 1e-6f); + ggml_tensor * rows = ggml_view_2d(ctx, v, head_dim*n_head, n_tokens, v->nb[2], 0); + + ggml_tensor * out = ggml_set_rows(ctx, cache, rows, idxs); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (ggml_is_view_op(t->op)) { + continue; + } + if (t->type == GGML_TYPE_I64 || t->type == GGML_TYPE_I32) { + init_set_rows_row_ids(t, n_cache); + } else { + init_tensor_uniform(t); + } + } + } +}; + +// Rows of K or V rotated with a Hadamard matrix and stored in a quantized cache, as build_attn does for a rotated cache: +// MUL_MAT (Hadamard hint), RESHAPE, VIEW, SET_ROWS. Backends may run the chain as one kernel. +struct test_fwht_set_rows : public test_case { + const ggml_type type_dst; + const ggml_type type_idx; + const int64_t n_rot; + const int64_t head_dim; + const int64_t n_head; + const int64_t n_tokens; + const int64_t n_cache; + + const bool norm; // RMS norm without weight before the rotation, as the V of Gemma 4 + + test_fwht_set_rows(ggml_type type_dst, ggml_type type_idx, int64_t n_rot, int64_t head_dim, int64_t n_head, int64_t n_tokens, int64_t n_cache, + bool norm = false) + : type_dst(type_dst), type_idx(type_idx), n_rot(n_rot), head_dim(head_dim), n_head(n_head), n_tokens(n_tokens), n_cache(n_cache), norm(norm) {} + + std::string vars() override { + return VARS_TO_STR8(type_dst, type_idx, n_rot, head_dim, n_head, n_tokens, n_cache, norm); + } + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "FWHT_SET_ROWS"; + } + + bool run_whole_graph() override { return true; } + + // the reference multiplies by the matrix, the backend may use the fast transform: a value rarely rounds the other way + double max_nmse_err() override { + return 5e-4; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * rot = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_rot, n_rot); + ggml_set_name(rot, "rot"); + ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, head_dim, n_head, n_tokens); + ggml_set_name(x, "x"); + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type_dst, head_dim*n_head, n_cache); + ggml_set_name(cache, "cache"); + ggml_tensor * idxs = ggml_new_tensor_1d(ctx, type_idx, n_tokens); + ggml_set_name(idxs, "idxs"); + + // the input of the rotation is made by an op, as K and V are + x = ggml_scale(ctx, x, 1.5f); + if (norm) { + x = ggml_rms_norm(ctx, x, 1e-6f); + } + + ggml_tensor * r = ggml_reshape_2d(ctx, x, n_rot, ggml_nelements(x)/n_rot); + r = ggml_mul_mat(ctx, rot, r); + ggml_mul_mat_set_hint(r, GGML_HINT_SRC0_IS_HADAMARD); + r = ggml_reshape_4d(ctx, r, head_dim, n_head, n_tokens, 1); + ggml_tensor * rows = ggml_view_2d(ctx, r, head_dim*n_head, n_tokens, r->nb[2], 0); + + ggml_tensor * out = ggml_set_rows(ctx, cache, rows, idxs); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (ggml_is_view_op(t->op)) { + continue; + } + if (strcmp(t->name, "rot") == 0) { + const int64_t n = t->ne[0]; + std::vector data(n*n); + const float scale = 1.0f/sqrtf((float) n); + for (int64_t r = 0; r < n; r++) { + for (int64_t i = 0; i < n; i++) { + data[r*n + i] = __builtin_popcountll((uint64_t) (r & i)) % 2 == 0 ? scale : -scale; + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } else if (t->type == GGML_TYPE_I64 || t->type == GGML_TYPE_I32) { + init_set_rows_row_ids(t, n_cache); + } else { + init_tensor_uniform(t); + } + } + } +}; + struct test_rms_norm_mul_mat : public test_case { const ggml_type type_a; const int64_t m; @@ -14910,6 +15049,35 @@ static std::vector> make_test_cases_eval() { } } + // V of Gemma 4 normed and stored: 256 and 512 heads, the 128 of other models, one or more tokens + for (ggml_type t : { GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16 }) { + for (int64_t n_tokens : { 1, 4, 64 }) { + test_cases.emplace_back(new test_rms_norm_set_rows(t, GGML_TYPE_I64, 256, 2, n_tokens, 96)); + test_cases.emplace_back(new test_rms_norm_set_rows(t, GGML_TYPE_I64, 512, 2, n_tokens, 96)); + test_cases.emplace_back(new test_rms_norm_set_rows(t, GGML_TYPE_I64, 128, 8, n_tokens, 96)); + } + } + test_cases.emplace_back(new test_rms_norm_set_rows(GGML_TYPE_F16, GGML_TYPE_I32, 256, 4, 3, 16)); + test_cases.emplace_back(new test_rms_norm_set_rows(GGML_TYPE_F16, GGML_TYPE_I64, 4096, 1, 2, 16)); + + // K / V rows of a rotated quantized cache: Gemma 4 (256 and 512 heads, V in rows of 64), Qwen 3.x, Inkling (128) + for (ggml_type t : { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }) { + for (int64_t n_tokens : { 1, 4, 7, 64 }) { + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 256, 256, 4, n_tokens, 96)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 512, 512, 2, n_tokens, 96)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 64, 256, 4, n_tokens, 96)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 128, 128, 8, n_tokens, 96)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 64, 128, 8, n_tokens, 96)); + } + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I32, 256, 256, 2, 3, 16)); + for (int64_t n_tokens : { 1, 7, 64 }) { + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 64, 256, 4, n_tokens, 96, true)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 64, 512, 2, n_tokens, 96, true)); + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I64, 64, 128, 8, n_tokens, 96, true)); + } + test_cases.emplace_back(new test_fwht_set_rows(t, GGML_TYPE_I32, 64, 256, 2, 3, 16, true)); + } + // norm of a layer input followed by quantized mat-vecs: row lengths with and without padding of the q8_1 copy, // every block size of the vectorized norm kernel, mat-vec (<= 8 tokens) and mat-mul for (ggml_type type_a : {GGML_TYPE_Q4_0, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K}) {