Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions ggml/src/ggml-cuda/fusion.cu
Original file line number Diff line number Diff line change
Expand Up @@ -2446,6 +2446,50 @@ static int ggml_cuda_try_fuse_rms_norm_set_rows(ggml_backend_cuda_context * cuda
return last - i;
}

// the Q rotation of a rotated KV cache folded into the fused norm + rope kernel, GGML_CUDA_NO_ROPE_FWHT_FUSION=1 turns it off
static bool ggml_cuda_rope_fwht_fusion_disabled() {
static const bool disabled = getenv("GGML_CUDA_NO_ROPE_FWHT_FUSION") != nullptr;
return disabled;
}

// RMS_NORM, MUL, ROPE, RESHAPE, MUL_MAT (Hadamard hint, rows of the whole head) -> one kernel: the Q of build_attn with a rotated K cache
// (the K chain is left to the K store fusions, which also quantize and store the rotated rows)
static int ggml_cuda_try_fuse_rms_norm_mul_rope_fwht(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
if (ggml_cuda_rope_fwht_fusion_disabled() || cuda_ctx->curr_stream_no != 0 || i + 4 >= cgraph->n_nodes) {
return 0;
}
ggml_tensor ** n = cgraph->nodes + i;
const ggml_tensor * rms_norm = n[0];
const ggml_tensor * mul = n[1];
const ggml_tensor * rope = n[2];
const ggml_tensor * mm = n[4];
if (n[0]->op != GGML_OP_RMS_NORM || n[1]->op != GGML_OP_MUL || n[2]->op != GGML_OP_ROPE || n[3]->op != GGML_OP_RESHAPE ||
n[3]->src[0] != rope || !ggml_cuda_op_mul_mat_use_fwht(mm) || mm->src[1] != n[3]) {
return 0;
}
const int64_t ncols = rope->ne[0];
if (ggml_cuda_info().devices[cuda_ctx->device].warp_size != 32 || (ncols != 128 && ncols != 256 && ncols != 512) ||
mm->src[0]->ne[0] != ncols || !ggml_is_contiguous(rope) || !ggml_is_contiguous(mm) || ggml_nelements(mm) != ggml_nelements(rope)) {
return 0;
}
// a K chain that stores into a quantized cache (RESHAPE, VIEW after the MUL_MAT) has its own fusion that also quantizes and stores
if (!ggml_cuda_kv_store_fusion_disabled() && i + 6 < cgraph->n_nodes && n[5]->op == GGML_OP_RESHAPE && n[5]->src[0] == mm &&
n[6]->op == GGML_OP_VIEW && n[6]->src[0] == n[5]) {
return 0;
}
if (!ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope)) {
return 0;
}
const ggml_op ops[] = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_RESHAPE, GGML_OP_MUL_MAT };
const int outputs[] = { i + 4 };
if (!ggml_can_fuse_subgraph(cgraph, i, 5, ops, outputs, 1) || !ggml_check_edges(cgraph, i, {{1, 0, 0}, {2, 0, 1}, {3, 0, 2}, {4, 1, 3}}) ||
!ggml_cuda_check_fusion_memory_ranges(cgraph, i, 5, outputs, 1)) {
return 0;
}
ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, n[0], n[1], n[2], nullptr, n[4]);
return 4;
}

// 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)) {
Expand All @@ -2464,6 +2508,9 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
if (int n = ggml_cuda_try_fuse_rms_norm_set_rows(cuda_ctx, cgraph, i)) {
return n;
}
if (int n = ggml_cuda_try_fuse_rms_norm_mul_rope_fwht(cuda_ctx, cgraph, i)) {
return n;
}
}

// a scaled matmul only takes part in the gate/up/GLU fusion, which passes its weight scale on
Expand Down
134 changes: 121 additions & 13 deletions ggml/src/ggml-cuda/rope.cu
Original file line number Diff line number Diff line change
Expand Up @@ -765,9 +765,12 @@ void ggml_cuda_op_rope_fused(ggml_backend_cuda_context & ctx, ggml_tensor * rope
ggml_cuda_op_rope_impl<true>(ctx, rope, set_rows);
}

// fused RMS_NORM + MUL + ROPE (+ VIEW + SET_ROWS)
// fused RMS_NORM + MUL + ROPE (+ VIEW + SET_ROWS), or (FWHT_N > 0) RMS_NORM + MUL + ROPE + RESHAPE + MUL_MAT (Hadamard, the Q rotation of
// a rotated KV cache)
// one block per row: block_reduce gives the norm scale, then each thread applies mul and rope to the elements it owns
template <int block_size, bool has_ff, typename D, bool supports_mrope>
// FWHT_N > 0: block_size is FWHT_N/2, ncols == FWHT_N, the rope result of the row is kept in shared memory and transformed by the
// butterfly of fwht_cuda (same stage order, same scale applied first, so the values are those of the separate kernels)
template <int block_size, bool has_ff, typename D, bool supports_mrope, int FWHT_N = 0>
static __global__ void rms_norm_mul_rope_f32(
const float * x, D * dst, const int ncols, const int nchannels, const int nsamples,
const int64_t s01, const int64_t s02, const int64_t s03,
Expand All @@ -783,13 +786,19 @@ static __global__ void rms_norm_mul_rope_f32(
const float * freq_factors,
const mrope_sections sections,
const int64_t * row_indices, const int set_rows_stride,
const bool is_neox, const bool is_mrope, const bool is_imrope) {
const bool is_neox, const bool is_mrope, const bool is_imrope, const float fwht_scale) {
ggml_cuda_pdl_lc();
const int row = blockIdx.x;
const int tid = threadIdx.x;

extern __shared__ float s_sum[];

// FWHT epilogue: the rope result of the row, and the exchange buffer of the stages across warps
constexpr int FWHT_SZ = FWHT_N > 0 ? FWHT_N : 1;
__shared__ float s_rot[FWHT_SZ];
__shared__ float s_xch[FWHT_SZ];
static_assert(FWHT_N == 0 || (block_size == FWHT_N/2 && block_size >= 2*WARP_SIZE), "bad FWHT epilogue shape");

ggml_cuda_pdl_sync();

// grid.y and grid.z are clamped to the CUDA limit, iterate over the excess channels/samples
Expand Down Expand Up @@ -834,8 +843,13 @@ static __global__ void rms_norm_mul_rope_f32(
const float x1 = scale * xc[ix1] * mulc[fastmodulo(ix1, mul_ncols_packed)];

if (i0 >= n_dims) {
dstc[ix0] = ggml_cuda_cast<D>(x0);
dstc[ix1] = ggml_cuda_cast<D>(x1);
if constexpr (FWHT_N > 0) {
s_rot[ix0] = x0;
s_rot[ix1] = x1;
} else {
dstc[ix0] = ggml_cuda_cast<D>(x0);
dstc[ix1] = ggml_cuda_cast<D>(x1);
}
continue;
}

Expand All @@ -848,8 +862,61 @@ static __global__ void rms_norm_mul_rope_f32(
float sin_theta;
rope_yarn<true>(theta_base/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, cos_theta, sin_theta);

dstc[ix0] = ggml_cuda_cast<D>(x0*cos_theta - x1*sin_theta);
dstc[ix1] = ggml_cuda_cast<D>(x0*sin_theta + x1*cos_theta);
if constexpr (FWHT_N > 0) {
s_rot[ix0] = x0*cos_theta - x1*sin_theta;
s_rot[ix1] = x0*sin_theta + x1*cos_theta;
} else {
dstc[ix0] = ggml_cuda_cast<D>(x0*cos_theta - x1*sin_theta);
dstc[ix1] = ggml_cuda_cast<D>(x0*sin_theta + x1*cos_theta);
}
}

if constexpr (FWHT_N > 0) {
// element j*block_size + tid of the row is register j (as in fwht_cuda_block)
__syncthreads();
float reg[2];
#pragma unroll
for (int j = 0; j < 2; ++j) {
reg[j] = s_rot[j*block_size + tid] * fwht_scale;
}
const int lane = tid % 32;
// stages within a warp: partner differs in the lane bits
#pragma unroll
for (int h = 1; h < 32; h *= 2) {
#pragma unroll
for (int j = 0; j < 2; j++) {
const float val = reg[j];
const float val2 = ggml_cuda_shfl_xor(val, h, 32);
reg[j] = (lane & h) == 0 ? val + val2 : val2 - val;
}
}
// stages across warps: partner differs in the thread-index bits above the lane
#pragma unroll
for (int h = 32; h < block_size; h *= 2) {
#pragma unroll
for (int j = 0; j < 2; j++) {
s_xch[j*block_size + tid] = reg[j];
}
__syncthreads();
#pragma unroll
for (int j = 0; j < 2; j++) {
const float val = reg[j];
const float val2 = s_xch[j*block_size + (tid ^ h)];
reg[j] = (tid & h) == 0 ? val + val2 : val2 - val;
}
__syncthreads();
}
// last stage: the partner is the other register of the thread
{
const float xl = reg[0];
const float xh = reg[1];
reg[0] = xl + xh;
reg[1] = xl - xh;
}
#pragma unroll
for (int j = 0; j < 2; ++j) {
dstc[j*block_size + tid] = reg[j];
}
}

if constexpr (block_size > WARP_SIZE) {
Expand Down Expand Up @@ -877,7 +944,7 @@ static void rms_norm_mul_rope_cuda(
const float * freq_factors,
const mrope_sections sections,
const int64_t * row_indices, const int set_rows_stride,
const bool is_neox, const bool is_mrope, const bool is_imrope, cudaStream_t stream) {
const bool is_neox, const bool is_mrope, const bool is_imrope, const float fwht_scale, cudaStream_t stream) {
GGML_ASSERT(ncols % 2 == 0);

const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX));
Expand All @@ -900,16 +967,48 @@ static void rms_norm_mul_rope_cuda(
x, dst, ncols, nchannels, nsamples, s01, s02, s03, s1, s2, s3, eps, mul, mul_s01, mul_s02, mul_s03,
mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed,
n_dims, pos, freq_scale, ext_factor, attn_factor, corr_dims, theta_scale,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope);
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale);
} else {
ggml_cuda_kernel_launch(rms_norm_mul_rope_f32<block_size, true, D, supports_mrope>, launch_params,
x, dst, ncols, nchannels, nsamples, s01, s02, s03, s1, s2, s3, eps, mul, mul_s01, mul_s02, mul_s03,
mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed,
n_dims, pos, freq_scale, ext_factor, attn_factor, corr_dims, theta_scale,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope);
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale);
}
};

// rope + Hadamard rotation of the whole row: one block of ncols/2 threads per row
if (fwht_scale != 0.0f) {
if constexpr (std::is_same_v<D, float>) {
auto launch_fwht = [&](auto n_tag) {
constexpr int n = decltype(n_tag)::value;
const dim3 block_dims(n/2, 1, 1);
const ggml_cuda_kernel_launch_params launch_params = {blocks_num, block_dims, 32 * sizeof(float), stream};
if (freq_factors == nullptr) {
ggml_cuda_kernel_launch(rms_norm_mul_rope_f32<n/2, false, D, true, n>, launch_params,
x, dst, ncols, nchannels, nsamples, s01, s02, s03, s1, s2, s3, eps, mul, mul_s01, mul_s02, mul_s03,
mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed,
n_dims, pos, freq_scale, ext_factor, attn_factor, corr_dims, theta_scale,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale);
} else {
ggml_cuda_kernel_launch(rms_norm_mul_rope_f32<n/2, true, D, true, n>, launch_params,
x, dst, ncols, nchannels, nsamples, s01, s02, s03, s1, s2, s3, eps, mul, mul_s01, mul_s02, mul_s03,
mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed,
n_dims, pos, freq_scale, ext_factor, attn_factor, corr_dims, theta_scale,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale);
}
};
switch (ncols) {
case 128: launch_fwht(std::integral_constant<int, 128>{}); return;
case 256: launch_fwht(std::integral_constant<int, 256>{}); return;
case 512: launch_fwht(std::integral_constant<int, 512>{}); return;
default: GGML_ABORT("unsupported FWHT row size");
}
} else {
GGML_ABORT("the rotated result is F32");
}
}

// Keep the wider launch and compile out multi-axis indexing for single-token NEOX.
if (is_neox && !is_mrope && nchannels == 1 && nsamples == 1 && ncols <= 8 * WARP_SIZE) {
launch_block(std::integral_constant<int, 256>{}, std::false_type{});
Expand All @@ -931,7 +1030,7 @@ static void rms_norm_mul_rope_cuda(
}

void ggml_cuda_op_rms_norm_mul_rope_fused(ggml_backend_cuda_context & ctx,
ggml_tensor * rms_norm, ggml_tensor * mul, ggml_tensor * rope, ggml_tensor * set_rows) {
ggml_tensor * rms_norm, ggml_tensor * mul, ggml_tensor * rope, ggml_tensor * set_rows, ggml_tensor * fwht_mm) {
const ggml_tensor * x = rms_norm->src[0];
const ggml_tensor * mul_src = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0];

Expand All @@ -948,11 +1047,20 @@ void ggml_cuda_op_rms_norm_mul_rope_fused(ggml_backend_cuda_context & ctx,
const int64_t * row_indices = nullptr;
int set_rows_stride = 0;

float fwht_scale = 0.0f;

if (set_rows != nullptr) {
dst_d = set_rows->data;
dst_type = set_rows->type;
row_indices = (const int64_t *) set_rows->src[1]->data;
set_rows_stride = set_rows->nb[1] / ggml_type_size(set_rows->type);
} else if (fwht_mm != nullptr) {
// the Hadamard MUL_MAT of the rope result: its F32 result is what the kernel writes, in the layout of the rope result
GGML_ASSERT(fwht_mm->type == GGML_TYPE_F32 && ggml_nelements(fwht_mm) == ggml_nelements(rope));
GGML_ASSERT(ggml_is_contiguous(fwht_mm) && ggml_is_contiguous(rope) && rope->ne[0] == fwht_mm->src[1]->ne[0]);
dst_d = fwht_mm->data;
dst_type = GGML_TYPE_F32;
fwht_scale = 1 / sqrtf(rope->ne[0]); // as ggml_cuda_op_fwht_impl
}

const int n_dims = ((const int32_t *) rope->op_params)[1];
Expand Down Expand Up @@ -1011,14 +1119,14 @@ void ggml_cuda_op_rms_norm_mul_rope_fused(ggml_backend_cuda_context & ctx,
(const float *) mul_src->data, mul_s01, mul_s02, mul_s03,
mul_src->ne[0], mul_src->ne[1], mul_src->ne[2], mul_src->ne[3],
n_dims, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, stream);
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale, stream);
} else if (dst_type == GGML_TYPE_F16) {
rms_norm_mul_rope_cuda((const float *) x->data, (half *) dst_d,
x->ne[0], x->ne[1], x->ne[2], x->ne[3], s01, s02, s03, s1, s2, s3, eps,
(const float *) mul_src->data, mul_s01, mul_s02, mul_s03,
mul_src->ne[0], mul_src->ne[1], mul_src->ne[2], mul_src->ne[3],
n_dims, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims,
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, stream);
freq_factors, sections, row_indices, set_rows_stride, is_neox, is_mrope, is_imrope, fwht_scale, stream);
} else {
GGML_ABORT("fatal error");
}
Expand Down
2 changes: 1 addition & 1 deletion ggml/src/ggml-cuda/rope.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ void ggml_cuda_op_rope_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst);

void ggml_cuda_op_rope_fused(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * set_rows);

void ggml_cuda_op_rms_norm_mul_rope_fused(ggml_backend_cuda_context & ctx, ggml_tensor * rms_norm, ggml_tensor * mul, ggml_tensor * rope, ggml_tensor * set_rows);
void ggml_cuda_op_rms_norm_mul_rope_fused(ggml_backend_cuda_context & ctx, ggml_tensor * rms_norm, ggml_tensor * mul, ggml_tensor * rope, ggml_tensor * set_rows, ggml_tensor * fwht_mm = nullptr);
Loading
Loading