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
85 changes: 85 additions & 0 deletions ggml/src/ggml-cuda/fusion.cu
Original file line number Diff line number Diff line change
Expand Up @@ -2215,6 +2215,85 @@ static bool ggml_cuda_match_dot_sigmoid_gate_add(
return !overlaps(w, dst) && !overlaps(x, dst);
}

// rms_norm*w1 + r [*scale] -> rms_norm*w2: two norms in a row (post-norm blocks: Gemma 4, LFM3), one launch for both.
// The residual (add or scale) and the second product are the outputs.
static int ggml_cuda_try_fuse_rms_norm2(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
static const bool disabled = getenv("GGML_CUDA_NO_RMS_NORM2") != nullptr;
if (disabled) {
return 0;
}
ggml_tensor ** n = cgraph->nodes + i;
int n1 = 0;
if (i + 5 < cgraph->n_nodes && n[0]->op == GGML_OP_RMS_NORM && n[1]->op == GGML_OP_MUL && n[2]->op == GGML_OP_ADD &&
n[3]->op == GGML_OP_MUL && n[4]->op == GGML_OP_RMS_NORM && n[5]->op == GGML_OP_MUL && n[4]->src[0] == n[3] &&
(n[3]->src[0] == n[2] || n[3]->src[1] == n[2])) {
n1 = 4;
} else if (i + 4 < cgraph->n_nodes && n[0]->op == GGML_OP_RMS_NORM && n[1]->op == GGML_OP_MUL && n[2]->op == GGML_OP_ADD &&
n[3]->op == GGML_OP_RMS_NORM && n[4]->op == GGML_OP_MUL && n[3]->src[0] == n[2]) {
n1 = 3;
}
if (n1 == 0) {
return 0;
}
ggml_tensor * norm1 = n[0];
ggml_tensor * mul1 = n[1];
ggml_tensor * add = n[2];
ggml_tensor * scale = n1 == 4 ? n[3] : nullptr;
ggml_tensor * norm2 = n[n1];
ggml_tensor * mul2 = n[n1 + 1];
if ((mul1->src[0] != norm1 && mul1->src[1] != norm1) || (add->src[0] != mul1 && add->src[1] != mul1) ||
(mul2->src[0] != norm2 && mul2->src[1] != norm2)) {
return 0;
}
const ggml_op ops3[] = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD, GGML_OP_RMS_NORM, GGML_OP_MUL };
const ggml_op ops4[] = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD, GGML_OP_MUL, GGML_OP_RMS_NORM, GGML_OP_MUL };
const int outputs[] = { i + n1 - 1, i + n1 + 1 };
if (!ggml_can_fuse_subgraph(cgraph, i, n1 + 2, n1 == 4 ? ops4 : ops3, outputs, 2)) {
return 0;
}
// the kernel does not write norm1, mul1, norm2 (and the add before a scale): each must have one use, not be an operand of the chain too
for (int k = 0; k <= n1; k++) {
if (i + k != outputs[0] && ggml_node_get_use_count(cgraph, i + k) != 1) {
return 0;
}
}
// A thread writes only values of the row it has read, after the reads (block barriers in between), so an output may take
// the exact place of x or r (in-place add), but not overlap them otherwise.
{
const ggml_tensor * x = norm1->src[0];
const ggml_tensor * r = add->src[0] == mul1 ? add->src[1] : add->src[0];
const ggml_tensor * w1 = mul1->src[0] == norm1 ? mul1->src[1] : mul1->src[0];
const ggml_tensor * w2 = mul2->src[0] == norm2 ? mul2->src[1] : mul2->src[0];
const ggml_tensor * s = scale ? (scale->src[0] == add ? scale->src[1] : scale->src[0]) : nullptr;
const ggml_tensor * y = scale ? scale : add;
auto overlap = [](const ggml_tensor * a, const ggml_tensor * b) {
const char * a0 = (const char *) a->data; const char * a1 = a0 + ggml_nbytes(a);
const char * b0 = (const char *) b->data; const char * b1 = b0 + ggml_nbytes(b);
return a0 < b1 && b0 < a1;
};
auto exact = [](const ggml_tensor * a, const ggml_tensor * b) {
return a->data == b->data && ggml_nbytes(a) == ggml_nbytes(b) && a->nb[1] == b->nb[1];
};
for (const ggml_tensor * out : { y, (const ggml_tensor *) mul2 }) {
for (const ggml_tensor * in : { x, r }) {
if (overlap(out, in) && !exact(out, in)) {
return 0;
}
}
if (overlap(out, w1) || overlap(out, w2) || (s && overlap(out, s))) {
return 0;
}
}
if (overlap(y, mul2)) {
return 0;
}
}
if (!ggml_cuda_op_rms_norm2(*cuda_ctx, norm1, mul1, add, scale, norm2, mul2, ggml_cuda_q8_1_consumer(cuda_ctx, cgraph, i + n1 + 1, true, true))) {
return 0;
}
return n1 + 1;
}

// 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 Down Expand Up @@ -2869,6 +2948,12 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
return 2;
}

if (node->op == GGML_OP_RMS_NORM) {
if (int n = ggml_cuda_try_fuse_rms_norm2(cuda_ctx, cgraph, i)) {
return n;
}
}

if (node->op == GGML_OP_RMS_NORM && ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD, GGML_OP_MUL }, {})) {
ggml_cuda_op_rms_norm_fused_add(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], nullptr, cgraph->nodes[i + 3]);
return 3;
Expand Down
198 changes: 198 additions & 0 deletions ggml/src/ggml-cuda/norm.cu
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "convert.cuh"
#include "mmvq.cuh"
#include <cstdint>
#include <climits>

// sum over groups of `width` consecutive lanes (warp_reduce_sum reduces the whole warp on some devices)
template <int width>
Expand Down Expand Up @@ -320,6 +321,108 @@ static __global__ void rms_norm_f32(const T * x,
}
}

// two RMS norms in a row, as after a block with post-norm: y = (rms_norm(x)*w1 + r) [*scale], z = rms_norm(y)*w2.
// y is the residual stream and z the input of the next block, both are written; z also as q8_1 blocks when do_quantize.
// Rows are contiguous F32, w1 and w2 are one row each. A thread keeps the same values of the row for both norms.
template <int block_size, int vpt, bool do_scale, bool do_quantize>
static __global__ void rms_norm2_f32(const float * x, const float * w1, const float * r, const float * scale_ptr, float * y,
const float * w2, float * z, void * q8_1, const int ncols, const int64_t stride_x,
const int64_t stride_r, const float eps1, const float eps2) {
ggml_cuda_pdl_lc();
const int row = blockIdx.x;
const int tid = threadIdx.x;
const int ncols4 = ncols / 4;

extern __shared__ float s_sum[];

ggml_cuda_pdl_sync();

const float4 * x4 = (const float4 *) (x + row*stride_x);
const float4 * r4 = (const float4 *) (r + row*stride_r);
const float4 * w14 = (const float4 *) w1;
const float4 * w24 = (const float4 *) w2;
float4 * y4 = (float4 *) (y + (int64_t) row*ncols);
float4 * z4 = (float4 *) (z + (int64_t) row*ncols);

float4 v[vpt];
float tmp = 0.0f;
#pragma unroll
for (int k = 0; k < vpt; k++) {
const int i = tid + k*block_size;
if (i < ncols4) {
v[k] = x4[i];
tmp += v[k].x*v[k].x + v[k].y*v[k].y + v[k].z*v[k].z + v[k].w*v[k].w;
}
}
tmp = block_reduce<block_reduce_method::SUM, block_size>(tmp, s_sum);
const float scale1 = rsqrtf(tmp / ncols + eps1);

[[maybe_unused]] float scale_out = 1.0f;
if constexpr (do_scale) {
scale_out = *scale_ptr;
}

tmp = 0.0f;
#pragma unroll
for (int k = 0; k < vpt; k++) {
const int i = tid + k*block_size;
if (i < ncols4) {
const float4 m = w14[i];
const float4 a = r4[i];
float4 t = make_float4(scale1*v[k].x, scale1*v[k].y, scale1*v[k].z, scale1*v[k].w);
t.x *= m.x; t.y *= m.y; t.z *= m.z; t.w *= m.w;
t.x += a.x; t.y += a.y; t.z += a.z; t.w += a.w;
if constexpr (do_scale) {
t.x *= scale_out; t.y *= scale_out; t.z *= scale_out; t.w *= scale_out;
}
v[k] = t;
y4[i] = t;
tmp += t.x*t.x + t.y*t.y + t.z*t.z + t.w*t.w;
}
}
if constexpr (block_size > WARP_SIZE) {
__syncthreads(); // s_sum is reused
}
tmp = block_reduce<block_reduce_method::SUM, block_size>(tmp, s_sum);
const float scale2 = rsqrtf(tmp / ncols + eps2);

#pragma unroll
for (int k = 0; k < vpt; k++) {
const int i = tid + k*block_size;
if (i < ncols4) {
const float4 m = w24[i];
float4 o = make_float4(scale2*v[k].x, scale2*v[k].y, scale2*v[k].z, scale2*v[k].w);
o.x *= m.x; o.y *= m.y; o.z *= m.z; o.w *= m.w;
z4[i] = o;

if constexpr (do_quantize) {
// same arithmetic as quantize_q8_1, see rms_norm_f32
float amax = fmaxf(fmaxf(fabsf(o.x), fabsf(o.y)), fmaxf(fabsf(o.z), fabsf(o.w)));
amax = warp_reduce_max<8>(amax);

const float d = amax / 127.0f;
const int8_t q0 = amax == 0.0f ? 0 : roundf(o.x / d);
const int8_t q1 = amax == 0.0f ? 0 : roundf(o.y / d);
const int8_t q2 = amax == 0.0f ? 0 : roundf(o.z / d);
const int8_t q3 = amax == 0.0f ? 0 : roundf(o.w / d);

const int sum = lane_group_reduce_sum<8>((int) q0 + (int) q1 + (int) q2 + (int) q3);

block_q8_1 * yq = (block_q8_1 *) q8_1 + (int64_t) row*(GGML_PAD(ncols, MATRIX_ROW_PADDING)/QK8_1) + i / (QK8_1/4);
const int iqs = 4*(i % (QK8_1/4));

yq->qs[iqs + 0] = q0;
yq->qs[iqs + 1] = q1;
yq->qs[iqs + 2] = q2;
yq->qs[iqs + 3] = q3;
if (iqs == 0) {
yq->ds = make_half2(d, d * sum);
}
}
}
}
}

template <int block_size>
static __global__ void rms_norm_back_f32(
const float * grad, const float * xf, float * dst, const int ncols, const float eps) {
Expand Down Expand Up @@ -1135,6 +1238,101 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx,
}
}

bool ggml_cuda_op_rms_norm2(ggml_backend_cuda_context & ctx, const ggml_tensor * norm1, const ggml_tensor * mul1, const ggml_tensor * add,
const ggml_tensor * scale, const ggml_tensor * norm2, ggml_tensor * mul2, const ggml_tensor * q8_1_src1) {
const ggml_tensor * x = norm1->src[0];
const ggml_tensor * w1 = mul1->src[0] == norm1 ? mul1->src[1] : mul1->src[0];
const ggml_tensor * r = add->src[0] == mul1 ? add->src[1] : add->src[0];
const ggml_tensor * w2 = mul2->src[0] == norm2 ? mul2->src[1] : mul2->src[0];
ggml_tensor * y = (ggml_tensor *) (scale ? scale : add);

float eps1 = 0.0f;
float eps2 = 0.0f;
memcpy(&eps1, norm1->op_params, sizeof(float));
memcpy(&eps2, norm2->op_params, sizeof(float));

const int64_t ncols = x->ne[0];
const int64_t nrows = ggml_nrows(x);
const int n4 = ncols / 4;

const bool rows_ok = [&](const ggml_tensor * t) {
return t->type == GGML_TYPE_F32 && t->nb[0] == sizeof(float) && t->ne[0] == ncols && ggml_nrows(t) == nrows &&
t->nb[2] == t->nb[1]*t->ne[1] && t->nb[3] == t->nb[2]*t->ne[2] && ggml_cuda_is_aligned(t, 16) && t->nb[1] % 16 == 0;
}(x) && [&](const ggml_tensor * t) {
return t->type == GGML_TYPE_F32 && t->nb[0] == sizeof(float) && t->ne[0] == ncols && ggml_nrows(t) == nrows &&
t->nb[2] == t->nb[1]*t->ne[1] && t->nb[3] == t->nb[2]*t->ne[2] && ggml_cuda_is_aligned(t, 16) && t->nb[1] % 16 == 0;
}(r);
// w1 and w2 are read as one row of ncols values: a weight broadcast over the rows can have ncols values in another shape
const bool weights_ok = w1->type == GGML_TYPE_F32 && w2->type == GGML_TYPE_F32 && w1->ne[0] == ncols && w2->ne[0] == ncols &&
ggml_nelements(w1) == ncols && ggml_nelements(w2) == ncols &&
ggml_is_contiguous(w1) && ggml_is_contiguous(w2) && ggml_cuda_is_aligned(w1, 16) && ggml_cuda_is_aligned(w2, 16);
const bool outs_ok = y->type == GGML_TYPE_F32 && mul2->type == GGML_TYPE_F32 && ggml_is_contiguous(y) && ggml_is_contiguous(mul2) &&
ggml_nelements(y) == ncols*nrows && ggml_nelements(mul2) == ncols*nrows &&
ggml_cuda_is_aligned(y, 16) && ggml_cuda_is_aligned(mul2, 16);
const ggml_tensor * scale_src = scale ? (scale->src[0] == add ? scale->src[1] : scale->src[0]) : nullptr;
const bool scale_ok = scale == nullptr || (scale->type == GGML_TYPE_F32 && scale_src->type == GGML_TYPE_F32 && ggml_nelements(scale_src) == 1);
if (ncols % 4 != 0 || n4 > 4096 || nrows > INT_MAX || !rows_ok || !weights_ok || !outs_ok || !scale_ok) {
return false;
}

const float * scale_ptr = scale_src ? (const float *) scale_src->data : nullptr;

void * q8_1 = nullptr;
int64_t q_args[8];
const bool quantize = q8_1_src1 != nullptr && ncols % QK8_1 == 0;
if (quantize) {
GGML_ASSERT(q8_1_src1->data == mul2->data && ggml_nelements(q8_1_src1) == ggml_nelements(mul2));
ggml_cuda_mmvq_q8_1_args(q8_1_src1, q_args);
ctx.q8_1_cache.clear();
ctx.q8_1_cache.buf = std::make_unique<ggml_cuda_pool_alloc<char>>(
ctx.pool(), q_args[7]*q_args[6]*q_args[5]*q_args[4] * sizeof(block_q8_1) / QK8_1);
q8_1 = ctx.q8_1_cache.buf->get();
}

cudaStream_t stream = ctx.stream();
const int64_t stride_x = x->nb[1] / sizeof(float);
const int64_t stride_r = r->nb[1] / sizeof(float);
const dim3 blocks_num(nrows, 1, 1);

#define RMS_NORM2_LAUNCH(BS, VPT) \
do { \
const dim3 block_dims(BS, 1, 1); \
const ggml_cuda_kernel_launch_params launch_params{ blocks_num, block_dims, BS > WARP_SIZE ? 32 * sizeof(float) : 0, stream }; \
if (scale_ptr) { \
if (quantize) ggml_cuda_kernel_launch(rms_norm2_f32<BS, VPT, true, true>, launch_params, (const float *) x->data, (const float *) w1->data, (const float *) r->data, scale_ptr, (float *) y->data, (const float *) w2->data, (float *) mul2->data, q8_1, (int) ncols, stride_x, stride_r, eps1, eps2); \
else ggml_cuda_kernel_launch(rms_norm2_f32<BS, VPT, true, false>, launch_params, (const float *) x->data, (const float *) w1->data, (const float *) r->data, scale_ptr, (float *) y->data, (const float *) w2->data, (float *) mul2->data, q8_1, (int) ncols, stride_x, stride_r, eps1, eps2); \
} else { \
if (quantize) ggml_cuda_kernel_launch(rms_norm2_f32<BS, VPT, false, true>, launch_params, (const float *) x->data, (const float *) w1->data, (const float *) r->data, scale_ptr, (float *) y->data, (const float *) w2->data, (float *) mul2->data, q8_1, (int) ncols, stride_x, stride_r, eps1, eps2); \
else ggml_cuda_kernel_launch(rms_norm2_f32<BS, VPT, false, false>, launch_params, (const float *) x->data, (const float *) w1->data, (const float *) r->data, scale_ptr, (float *) y->data, (const float *) w2->data, (float *) mul2->data, q8_1, (int) ncols, stride_x, stride_r, eps1, eps2); \
} \
} while (0)

// the block sizes of rms_norm_f32_dispatch, so that both norms sum in the same order as the unfused kernels
if (n4 <= 32) {
RMS_NORM2_LAUNCH(32, 1);
} else if (n4 <= 128) {
RMS_NORM2_LAUNCH(128, 1);
} else if (n4 <= 256) {
RMS_NORM2_LAUNCH(256, 1);
} else if (n4 <= 512) {
RMS_NORM2_LAUNCH(512, 1);
} else if (n4 <= 1024) {
RMS_NORM2_LAUNCH(1024, 1);
} else {
RMS_NORM2_LAUNCH(1024, 4);
}
#undef RMS_NORM2_LAUNCH

if (q8_1_src1 != nullptr) {
if (quantize) {
ctx.q8_1_cache.set(q8_1_src1, q_args, mul2);
} else {
ctx.q8_1_cache.clear();
}
}
return true;
}

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
Expand Down
5 changes: 5 additions & 0 deletions ggml/src/ggml-cuda/norm.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx,
const ggml_tensor * q8_1_src1 = nullptr,
ggml_tensor * scale_tensor = nullptr);

// rms_norm*w1 + r [*scale] -> rms_norm*w2 in one kernel (two norms in a row): writes the residual (add or scale node) and mul2.
// Returns false (nothing launched) when the shapes are not supported.
bool ggml_cuda_op_rms_norm2(ggml_backend_cuda_context & ctx, const ggml_tensor * norm1, const ggml_tensor * mul1, const ggml_tensor * add,
const ggml_tensor * scale, const ggml_tensor * norm2, ggml_tensor * mul2, const ggml_tensor * q8_1_src1 = nullptr);

void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst);

void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
Expand Down
Loading
Loading