From 4d476676c0da1e6533f8433f523fe61350ec2c69 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:44:57 +0000 Subject: [PATCH 1/2] CUDA: fuse the Inkling 2 dynamic conv tail, depth mix and MoE expert scale; in-place element-wise fusions Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/ggml-cuda.cu | 309 +++++++++++++++++- ggml/src/ggml-cuda/moe-weighted-reduction.cu | 24 ++ ggml/src/ggml-cuda/moe-weighted-reduction.cuh | 4 + ggml/src/ggml-cuda/norm.cu | 90 +++++ ggml/src/ggml-cuda/norm.cuh | 7 + ggml/src/ggml-cuda/ssm-conv.cu | 45 +++ ggml/src/ggml-cuda/ssm-conv.cuh | 15 + tests/test-backend-ops.cpp | 181 ++++++++++ 8 files changed, 673 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 154fd760aa7a..b444c16d0b7f 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -4805,6 +4805,256 @@ static bool ggml_cuda_match_dot_sigmoid_gate_add( return !overlaps(w, dst) && !overlaps(x, dst); } +// memory check of an element-wise fused kernel: dst may be exactly one of the inputs it reads at the same index (the graph +// allocator reuses them in place), it must not overlap any other input +static bool ggml_cuda_fusion_dst_ok(const ggml_tensor * dst, std::initializer_list same_index, + std::initializer_list other) { + auto overlap = [](const ggml_tensor * a, const ggml_tensor * b) { + const char * a0 = (const char *) a->data; + const char * b0 = (const char *) b->data; + return a0 < b0 + ggml_nbytes(b) && b0 < a0 + ggml_nbytes(a); + }; + for (const ggml_tensor * t : same_index) { + if (overlap(dst, t) && !(t->data == dst->data && ggml_is_contiguous(t) && ggml_nbytes(t) == ggml_nbytes(dst))) { + return false; + } + } + for (const ggml_tensor * t : other) { + if (overlap(dst, t)) { + return false; + } + } + return true; +} + +// every node of [i0, i0 + n) but out_idx is consumed only inside the range and is not a graph output +// unlike ggml_can_fuse_subgraph() it accepts views of tensors computed before the range +static bool ggml_cuda_fusion_uses_inside(const ggml_cgraph * cgraph, const int i0, const int n, const int out_idx) { + if (i0 + n > cgraph->n_nodes) { + return false; + } + for (int k = i0; k < i0 + n; ++k) { + if (k == out_idx) { + continue; + } + const ggml_tensor * node = cgraph->nodes[k]; + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + return false; + } + int uses = 0; + for (int l = k + 1; l < i0 + n; ++l) { + for (int s = 0; s < GGML_MAX_SRC; ++s) { + uses += cgraph->nodes[l]->src[s] == node; + } + } + if (uses != ggml_node_get_use_count(cgraph, k)) { + return false; + } + } + return true; +} + +static bool ggml_cuda_is_f32_rows(const ggml_tensor * t, int64_t ne0, int64_t ne1) { + return t && t->type == GGML_TYPE_F32 && ggml_is_contiguous(t) && t->ne[0] == ne0 && ggml_nrows(t) == ne1; +} + +// CONT of the transposed conv input, then per lag [views] MUL RESHAPE ADD, then ADD (residual) and SCALE, see ggml_cuda_op_dyn_conv_tail +static int ggml_cuda_match_dyn_conv_tail(const ggml_cgraph * cgraph, const int i, ggml_cuda_dyn_conv_taps & taps, + const ggml_tensor *& x, const ggml_tensor *& base, const ggml_tensor *& cur, int & head_dim) { + const ggml_tensor * cont = cgraph->nodes[i]; + const ggml_tensor * tr = cont->src[0]; + if (cont->type != GGML_TYPE_F32 || !tr || tr->op != GGML_OP_TRANSPOSE || !tr->src[0]) { + return 0; + } + x = tr->src[0]; + if (x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || x->ne[3] != 1 || x->ne[0] > INT_MAX || x->ne[1] > INT_MAX) { + return 0; + } + const int64_t n_rows = x->ne[0]; + const int64_t n_ch = x->ne[1]; + const int64_t n_seqs = x->ne[2]; + + taps.n = 0; + head_dim = 0; + int64_t n_seq_tokens = -1; + const ggml_tensor * prev = nullptr; + int j = i + 1; + while (true) { + while (j < cgraph->n_nodes && ggml_cuda_is_view_or_noop(cgraph->nodes[j])) { + j++; + } + if (j + 2 >= cgraph->n_nodes || cgraph->nodes[j]->op != GGML_OP_MUL) { + break; + } + const ggml_tensor * mul = cgraph->nodes[j]; + const ggml_tensor * w = mul->src[0]; + const ggml_tensor * tp = mul->src[1]; + if (taps.n == GGML_CUDA_DYN_CONV_MAX_TAPS || w->op != GGML_OP_VIEW || w->view_src != cont || w->type != GGML_TYPE_F32 || + w->nb[0] != sizeof(float) || w->nb[1] != w->ne[0]*sizeof(float) || w->ne[0]*w->ne[1] != n_ch || + w->nb[2] != cont->nb[1] || w->nb[3] != cont->nb[2] || w->ne[3] != n_seqs || w->view_offs % cont->nb[1] != 0) { + return 0; + } + const int64_t row = w->view_offs / cont->nb[1]; + if (n_seq_tokens < 0) { + n_seq_tokens = w->ne[2]; + head_dim = w->ne[0]; + } + if (w->ne[2] != n_seq_tokens || w->ne[0] != head_dim || row + n_seq_tokens > n_rows) { + return 0; + } + if (tp->type != GGML_TYPE_F32 || tp->ne[0] != 1 || tp->ne[1] != w->ne[1] || tp->ne[2] != n_seq_tokens || tp->ne[3] != n_seqs || + tp->nb[1] % sizeof(float) || tp->nb[2] % sizeof(float) || tp->nb[3] % sizeof(float) || !ggml_are_same_shape(mul, w)) { + return 0; + } + const ggml_tensor * reshape = cgraph->nodes[j + 1]; + const ggml_tensor * add = cgraph->nodes[j + 2]; + if (reshape->op != GGML_OP_RESHAPE || reshape->src[0] != mul || add->op != GGML_OP_ADD || add->src[1] != reshape || + (prev && add->src[0] != prev)) { + return 0; + } + if (!prev) { + base = add->src[0]; + } + taps.data[taps.n] = (const float *) tp->data; + taps.nb1[taps.n] = tp->nb[1]/sizeof(float); + taps.nb2[taps.n] = tp->nb[2]/sizeof(float); + taps.nb3[taps.n] = tp->nb[3]/sizeof(float); + taps.row[taps.n] = (int) row; + taps.n++; + prev = add; + j += 3; + } + if (taps.n == 0 || j + 1 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * add = cgraph->nodes[j]; + const ggml_tensor * scale = cgraph->nodes[j + 1]; + if (add->op != GGML_OP_ADD || add->src[1] != prev || scale->op != GGML_OP_SCALE || scale->src[0] != add) { + return 0; + } + cur = add->src[0]; + const int64_t n_tokens = n_seq_tokens*n_seqs; + for (const ggml_tensor * t : { base, cur, (const ggml_tensor *) prev, (const ggml_tensor *) add, (const ggml_tensor *) scale }) { + if (!ggml_cuda_is_f32_rows(t, n_ch, n_tokens)) { + return 0; + } + } + taps.n_conv = (int) (n_rows - n_seq_tokens + 1); + const int n_nodes = j + 2 - i; + return ggml_cuda_fusion_uses_inside(cgraph, i, n_nodes, j + 1) ? n_nodes : 0; +} + +// RMS_NORM [CONCAT] TRANSPOSE CONT, then MUL_MAT(query) RESHAPE or REPEAT MUL_MAT, then SOFT_MAX and MUL_MAT, see ggml_cuda_op_depth_mix +static int ggml_cuda_match_depth_mix(const ggml_cgraph * cgraph, const int i, const ggml_tensor *& stack, const ggml_tensor *& cur, + const ggml_tensor *& query, float & eps, float & scale) { + const ggml_tensor * rms = cgraph->nodes[i]; + if (rms->type != GGML_TYPE_F32 || i + 6 >= cgraph->n_nodes) { + return 0; + } + cur = rms->src[0]; + const int64_t n_embd = rms->ne[0]; + const int64_t n_tokens = rms->ne[2]; + if (rms->ne[1] != 1 || rms->ne[3] != 1 || !ggml_cuda_is_f32_rows(cur, n_embd, n_tokens) || n_embd > INT_MAX) { + return 0; + } + eps = ggml_get_op_params_f32(rms, 0); + + int j = i + 1; + const ggml_tensor * states = rms; + stack = nullptr; + if (cgraph->nodes[j]->op == GGML_OP_CONCAT && cgraph->nodes[j]->src[1] == rms && ggml_get_op_params_i32(cgraph->nodes[j], 0) == 1) { + states = cgraph->nodes[j]; + stack = states->src[0]; + if (stack->type != GGML_TYPE_F32 || !ggml_is_contiguous(stack) || stack->ne[0] != n_embd || stack->ne[2] != n_tokens || stack->ne[3] != 1) { + return 0; + } + j++; + } + const int64_t n_states = states->ne[1]; + if (n_states > GGML_CUDA_DEPTH_MIX_MAX_STATES || j + 4 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * tr = cgraph->nodes[j]; + const ggml_tensor * cont = cgraph->nodes[j + 1]; + if (tr->op != GGML_OP_TRANSPOSE || tr->src[0] != states || cont->op != GGML_OP_CONT || cont->src[0] != tr) { + return 0; + } + j += 2; + const ggml_tensor * scores = nullptr; + if (cgraph->nodes[j]->op == GGML_OP_REPEAT) { + const ggml_tensor * rep = cgraph->nodes[j]; + const ggml_tensor * mm = cgraph->nodes[j + 1]; + query = rep->src[0]; + if (mm->op != GGML_OP_MUL_MAT || mm->src[0] != states || mm->src[1] != rep) { + return 0; + } + scores = mm; + } else { + const ggml_tensor * mm = cgraph->nodes[j]; + const ggml_tensor * reshape = cgraph->nodes[j + 1]; + query = mm->src[0]; + if (mm->op != GGML_OP_MUL_MAT || mm->src[1] != states || reshape->op != GGML_OP_RESHAPE || reshape->src[0] != mm || + query->ne[1] != 1) { + return 0; + } + scores = reshape; + } + j += 2; + if (query->type != GGML_TYPE_F32 || !ggml_is_contiguous(query) || query->ne[0] != n_embd || query->ne[1] > GGML_CUDA_DEPTH_MIX_MAX_QUERY || + query->ne[2] != 1 || query->ne[3] != 1 || j + 1 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * sm = cgraph->nodes[j]; + const ggml_tensor * out = cgraph->nodes[j + 1]; + if (sm->op != GGML_OP_SOFT_MAX || sm->src[0] != scores || sm->src[1] || sm->src[2] || ggml_get_op_params_f32(sm, 1) != 0.0f || + out->op != GGML_OP_MUL_MAT || out->src[0] != cont || out->src[1] != sm) { + return 0; + } + if (out->type != GGML_TYPE_F32 || !ggml_is_contiguous(out) || out->ne[0] != n_embd || out->ne[1] != query->ne[1] || out->ne[2] != n_tokens || + out->ne[3] != 1) { + return 0; + } + scale = ggml_get_op_params_f32(sm, 0); + const int n_nodes = j + 2 - i; + return ggml_cuda_fusion_uses_inside(cgraph, i, n_nodes, j + 1) ? n_nodes : 0; +} + +// REPEAT of a per-expert scale, GET_ROWS by the selected experts, MUL with the MUL_MAT_ID result +static int ggml_cuda_match_moe_expert_scale(const ggml_cgraph * cgraph, const int i) { + int j = i + 1; + while (j < cgraph->n_nodes && ggml_cuda_is_view_or_noop(cgraph->nodes[j])) { + j++; + } + const int i_gr = j++; + while (j < cgraph->n_nodes && ggml_cuda_is_view_or_noop(cgraph->nodes[j])) { + j++; + } + if (j >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * rep = cgraph->nodes[i]; + const ggml_tensor * gr = cgraph->nodes[i_gr]; + const ggml_tensor * mul = cgraph->nodes[j]; + const ggml_tensor * ws = rep->src[0]; + if (rep->type != GGML_TYPE_F32 || !ws || ws->type != GGML_TYPE_F32 || !ggml_is_contiguous(ws) || ws->ne[0] != 1 || ws->ne[2] != 1 || + ws->ne[3] != 1 || rep->ne[0] != 1 || rep->ne[1] != ws->ne[1] || rep->ne[3] != 1) { + return 0; + } + if (gr->op != GGML_OP_GET_ROWS || gr->src[0] != rep || mul->op != GGML_OP_MUL || mul->src[1] != gr) { + return 0; + } + const ggml_tensor * ids = gr->src[1]; + const ggml_tensor * res = mul->src[0]; + if (ids->type != GGML_TYPE_I32 || ids->ne[1] != rep->ne[2] || ids->ne[2] != 1 || ids->nb[0] % sizeof(int32_t) || ids->nb[1] % sizeof(int32_t)) { + return 0; + } + if (res->type != GGML_TYPE_F32 || !ggml_is_contiguous(res) || res->ne[1] != ids->ne[0] || res->ne[2] != ids->ne[1] || res->ne[3] != 1 || + !ggml_is_contiguous(mul) || !ggml_are_same_shape(mul, res) || res->ne[1] > INT_MAX) { + return 0; + } + return ggml_cuda_fusion_uses_inside(cgraph, i, j + 1 - i, j) ? j + 1 - i : 0; +} + // try and fuse nodes and return the number of nodes to skip static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { @@ -5763,6 +6013,61 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } } + if (node->op == GGML_OP_CONT) { + ggml_cuda_dyn_conv_taps taps; + const ggml_tensor * x = nullptr; + const ggml_tensor * base = nullptr; + const ggml_tensor * cur = nullptr; + int head_dim = 0; + const int n_nodes = ggml_cuda_match_dyn_conv_tail(cgraph, i, taps, x, base, cur, head_dim); + bool dst_ok = n_nodes > 0; + if (dst_ok) { + const ggml_tensor * dst = cgraph->nodes[i + n_nodes - 1]; + dst_ok = ggml_cuda_fusion_dst_ok(dst, { base, cur }, { x }); + for (int j = i; dst_ok && j < i + n_nodes; ++j) { + // the taps: views of the tensors in front of the range + const ggml_tensor * t = cgraph->nodes[j]; + if (t->op == GGML_OP_MUL) { + dst_ok = ggml_cuda_fusion_dst_ok(dst, {}, { t->src[1]->view_src ? t->src[1]->view_src : t->src[1] }); + } + } + } + if (dst_ok) { + const int out_idx = i + n_nodes - 1; + { + ggml_cuda_op_dyn_conv_tail(*cuda_ctx, x, base, cur, taps, head_dim, cgraph->nodes[out_idx], cgraph->nodes[out_idx]); + return n_nodes - 1; + } + } + } + + if (node->op == GGML_OP_RMS_NORM) { + const ggml_tensor * stack = nullptr; + const ggml_tensor * cur = nullptr; + const ggml_tensor * query = nullptr; + float eps = 0.0f; + float scale = 0.0f; + const int n_nodes = ggml_cuda_match_depth_mix(cgraph, i, stack, cur, query, eps, scale); + if (n_nodes > 0) { + const int out_idx = i + n_nodes - 1; + if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_nodes, &out_idx, 1)) { + ggml_cuda_op_depth_mix(*cuda_ctx, stack, cur, query, eps, scale, cgraph->nodes[out_idx]); + return n_nodes - 1; + } + } + } + + if (node->op == GGML_OP_REPEAT) { + const int n_nodes = ggml_cuda_match_moe_expert_scale(cgraph, i); + const int out_idx = i + n_nodes - 1; + if (n_nodes > 0 && ggml_cuda_fusion_dst_ok(cgraph->nodes[out_idx], { cgraph->nodes[out_idx]->src[0] }, + { node->src[0], cgraph->nodes[out_idx]->src[1]->src[1] })) { + ggml_tensor * mul = cgraph->nodes[out_idx]; + ggml_cuda_op_moe_expert_scale(*cuda_ctx, mul->src[0], node->src[0], mul->src[1]->src[1], mul); + return n_nodes - 1; + } + } + // clip of the row l2 norms, optionally after a MUL: [MUL] SQR SUM_ROWS SQRT SCALE FILL DIV CLAMP MUL if (node->op == GGML_OP_MUL || node->op == GGML_OP_SQR) { static const ggml_op clip_ops[] = { GGML_OP_MUL, GGML_OP_SQR, GGML_OP_SUM_ROWS, GGML_OP_SQRT, GGML_OP_SCALE, @@ -5796,7 +6101,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph const ggml_tensor * cur = cgraph->nodes[i + 1]->src[1]; const ggml_tensor * msg = cgraph->nodes[i + 4]->src[1]; if (ggml_cuda_should_fuse_tanh_gate(cur, node->src[0], cgraph->nodes[i + 3]->src[0], msg, cgraph->nodes[i + 5]) && - ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 1)) { + ggml_cuda_fusion_dst_ok(cgraph->nodes[i + 5], { cur, node->src[0], cgraph->nodes[i + 3]->src[0], msg }, {})) { ggml_cuda_op_tanh_gate_fused(*cuda_ctx, cur, node->src[0], cgraph->nodes[i + 3]->src[0], msg, cgraph->nodes[i + 5]); return 5; } @@ -5808,7 +6113,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph const int outputs[] = { i + 1 }; if (ggml_can_fuse_subgraph(cgraph, i, 2, ops, outputs, 1) && cgraph->nodes[i + 1]->src[0] == node && ggml_cuda_should_fuse_add_scale(node, cgraph->nodes[i + 1]) && - ggml_cuda_check_fusion_memory_ranges(cgraph, i, 2, outputs, 1)) { + ggml_cuda_fusion_dst_ok(cgraph->nodes[i + 1], { node->src[0], node->src[1] }, {})) { ggml_cuda_op_add_scale_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); return 1; } diff --git a/ggml/src/ggml-cuda/moe-weighted-reduction.cu b/ggml/src/ggml-cuda/moe-weighted-reduction.cu index 11ec58497f1e..6b1fadbbd2e9 100644 --- a/ggml/src/ggml-cuda/moe-weighted-reduction.cu +++ b/ggml/src/ggml-cuda/moe-weighted-reduction.cu @@ -63,3 +63,27 @@ void ggml_cuda_op_moe_weighted_reduction(ggml_backend_cuda_context & ctx, (float *) dst->data, n_embd, n_tokens, (int) n_expert_used, stream); CUDA_CHECK(cudaGetLastError()); } + +// per-expert weight scale of a MUL_MAT_ID result: dst[:, k, t] = res[:, k, t] * scale[ids[k, t]] (REPEAT, GET_ROWS and MUL) +static __global__ void moe_expert_scale_f32(const float * __restrict__ res, const float * __restrict__ scale, const int32_t * __restrict__ ids, + float * __restrict__ dst, const int64_t n0, const int n_used, const int n_expert, const int64_t ids_nb0, const int64_t ids_nb1, const int64_t n) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + if (i >= n) { + return; + } + const int64_t row = i / n0; + const int k = row % n_used; + const int64_t t = row / n_used; + const int32_t id = ids[k*ids_nb0 + t*ids_nb1]; + dst[i] = res[i] * (uint32_t(id) < uint32_t(n_expert) ? scale[id] : 0.0f); +} + +void ggml_cuda_op_moe_expert_scale(ggml_backend_cuda_context & ctx, const ggml_tensor * res, const ggml_tensor * scale, const ggml_tensor * ids, + ggml_tensor * dst) { + const int64_t n = ggml_nelements(dst); + const int block_size = 256; + const int64_t n_blocks = (n + block_size - 1) / block_size; + GGML_ASSERT(n_blocks <= INT_MAX); + moe_expert_scale_f32<<>>((const float *) res->data, (const float *) scale->data, (const int32_t *) ids->data, + (float *) dst->data, res->ne[0], res->ne[1], ggml_nelements(scale), ids->nb[0]/sizeof(int32_t), ids->nb[1]/sizeof(int32_t), n); +} diff --git a/ggml/src/ggml-cuda/moe-weighted-reduction.cuh b/ggml/src/ggml-cuda/moe-weighted-reduction.cuh index b72f947ab398..e77466355b40 100644 --- a/ggml/src/ggml-cuda/moe-weighted-reduction.cuh +++ b/ggml/src/ggml-cuda/moe-weighted-reduction.cuh @@ -5,3 +5,7 @@ void ggml_cuda_op_moe_weighted_reduction(ggml_backend_cuda_context & ctx, const ggml_tensor * expert_scale, const ggml_tensor * weights, ggml_tensor * dst); + +// res [n0, n_used, n_tokens] F32, scale [n_expert] F32, ids [n_used, n_tokens] I32 +void ggml_cuda_op_moe_expert_scale(ggml_backend_cuda_context & ctx, const ggml_tensor * res, const ggml_tensor * scale, const ggml_tensor * ids, + ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index ce9cdc76e06e..914eaef89ee1 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -1159,3 +1159,93 @@ void ggml_cuda_op_l2_clip_fused(ggml_backend_cuda_context & ctx, const ggml_tens x->ne[0], x->ne[1], x->ne[2], x->ne[3], x->nb[1]/ts, x->nb[2]/ts, x->nb[3]/ts, scale ? scale->ne[1] : 1, scale ? scale->ne[2] : 1, scale ? scale->ne[3] : 1, a, b, c, lo, hi, ctx.stream()); } + +// attention over the depth (Inkling 2), one block per token: +// states = [stack rows..., rms_norm(cur)], p_q = softmax(scale * states . query_q), dst_q = sum_s p_q[s] * states[s] +#define DEPTH_MIX_BLOCK_SIZE 256 +static __global__ void depth_mix_f32(const float * __restrict__ stack, const float * __restrict__ cur, const float * __restrict__ query, + float * __restrict__ dst, const int n_embd, const int n_stack, const int n_query, const float eps, const float scale) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int n_warps = DEPTH_MIX_BLOCK_SIZE / warp_size; + __shared__ float s_sum[32]; + __shared__ float s_p[GGML_CUDA_DEPTH_MIX_MAX_QUERY*GGML_CUDA_DEPTH_MIX_MAX_STATES]; + + const int64_t t = blockIdx.x; + const int tid = threadIdx.x; + const int n_states = n_stack + 1; + + const float * cur_t = cur + t*n_embd; + const float * stack_t = stack + t*n_stack*n_embd; + + float tmp = 0.0f; + for (int e = tid; e < n_embd; e += DEPTH_MIX_BLOCK_SIZE) { + tmp += cur_t[e]*cur_t[e]; + } + tmp = block_reduce(tmp, s_sum); + const float rs = rsqrtf(tmp/n_embd + eps); + + const int warp = tid / warp_size; + const int lane = tid % warp_size; + for (int p = warp; p < n_states*n_query; p += n_warps) { + const int s = p % n_states; + const int q = p / n_states; + const float * qv = query + q*n_embd; + float dot = 0.0f; + if (s < n_stack) { + const float * st = stack_t + s*n_embd; + for (int e = lane; e < n_embd; e += warp_size) { + dot += st[e]*qv[e]; + } + } else { + for (int e = lane; e < n_embd; e += warp_size) { + dot += (cur_t[e]*rs)*qv[e]; + } + } + dot = warp_reduce_sum(dot); + if (lane == 0) { + s_p[q*n_states + s] = dot*scale; + } + } + __syncthreads(); + + if (tid < n_query) { + float * pq = s_p + tid*n_states; + float mx = -INFINITY; + for (int s = 0; s < n_states; ++s) { + mx = fmaxf(mx, pq[s]); + } + float sum = 0.0f; + for (int s = 0; s < n_states; ++s) { + pq[s] = expf(pq[s] - mx); + sum += pq[s]; + } + for (int s = 0; s < n_states; ++s) { + pq[s] /= sum; + } + } + __syncthreads(); + + for (int e = tid; e < n_embd; e += DEPTH_MIX_BLOCK_SIZE) { + const float xc = cur_t[e]*rs; + for (int q = 0; q < n_query; ++q) { + const float * pq = s_p + q*n_states; + float acc = 0.0f; + for (int s = 0; s < n_stack; ++s) { + acc += pq[s]*stack_t[s*n_embd + e]; + } + acc += pq[n_stack]*xc; + dst[(t*n_query + q)*n_embd + e] = acc; + } + } +} + +void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur, const ggml_tensor * query, + const float eps, const float scale, ggml_tensor * dst) { + const int n_embd = dst->ne[0]; + const int n_query = dst->ne[1]; + const int n_stack = stack ? stack->ne[1] : 0; + const int64_t n_tokens = dst->ne[2]; + GGML_ASSERT(n_tokens <= INT_MAX); + depth_mix_f32<<>>(stack ? (const float *) stack->data : nullptr, (const float *) cur->data, + (const float *) query->data, (float *) dst->data, n_embd, n_stack, n_query, eps, scale); +} diff --git a/ggml/src/ggml-cuda/norm.cuh b/ggml/src/ggml-cuda/norm.cuh index 0fc6f550d3d0..4b670750fe5f 100644 --- a/ggml/src/ggml-cuda/norm.cuh +++ b/ggml/src/ggml-cuda/norm.cuh @@ -30,3 +30,10 @@ bool ggml_cuda_should_fuse_l2_clip(const ggml_tensor * x, const ggml_tensor * sc void ggml_cuda_op_l2_clip_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * scale, const ggml_tensor * norm_scale, const ggml_tensor * fill, const ggml_tensor * clamp, ggml_tensor * dst); + +#define GGML_CUDA_DEPTH_MIX_MAX_QUERY 4 +#define GGML_CUDA_DEPTH_MIX_MAX_STATES 64 + +// stack [n_embd, n_stack, n_tokens] (or nullptr), cur [n_embd, n_tokens], query [n_embd, n_query], dst [n_embd, n_query, n_tokens] +void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur, const ggml_tensor * query, + float eps, float scale, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/ssm-conv.cu b/ggml/src/ggml-cuda/ssm-conv.cu index 5e4099034d1b..f96467c13f32 100644 --- a/ggml/src/ggml-cuda/ssm-conv.cu +++ b/ggml/src/ggml-cuda/ssm-conv.cu @@ -364,3 +364,48 @@ void ggml_cuda_op_ssm_conv_mul(ggml_backend_cuda_context & ctx, ggml_tensor * co ctx.q8_1_cache.set(q8_1_src1, q_args, mul); } } + +// the element-wise tail of a causal convolution with input-dependent taps per head (Inkling 2): +// dst = (cur + base + sum_j x[t + row_j] * tap_j[head, t]) * scale + bias +// x is time major, [n_rows, n_channels, n_seqs] with n_rows = n_conv - 1 + n_seq_tokens; the products and sums keep the +// order and the rounding of the separate MUL and ADD nodes +static __global__ void dyn_conv_tail_f32(const float * __restrict__ x, const float * __restrict__ base, const float * __restrict__ cur, + const ggml_cuda_dyn_conv_taps taps, float * __restrict__ dst, + const int n_channels, const int n_seq_tokens, const int n_rows, const int head_dim, const int64_t n, + const float scale, const float bias) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + if (i >= n) { + return; + } + const int c = i % n_channels; + const int64_t t = i / n_channels; + const int64_t seq = t / n_seq_tokens; + const int tt = t % n_seq_tokens; + const int h = c / head_dim; + + const float * xc = x + (seq*n_channels + c)*n_rows + tt; + + float acc = base[i]; + for (int j = 0; j < taps.n; ++j) { + const float tap = taps.data[j][h*taps.nb1[j] + tt*taps.nb2[j] + seq*taps.nb3[j]]; + acc = __fadd_rn(acc, __fmul_rn(xc[taps.row[j]], tap)); + } + dst[i] = __fadd_rn(cur[i], acc)*scale + bias; +} + +void ggml_cuda_op_dyn_conv_tail(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * base, const ggml_tensor * cur, + const ggml_cuda_dyn_conv_taps & taps, const int head_dim, const ggml_tensor * scale_node, ggml_tensor * dst) { + const int n_channels = dst->ne[0]; + const int n_rows = x->ne[0]; + const int n_seq_tokens = n_rows - taps.n_conv + 1; + const int64_t n = ggml_nelements(dst); + + const float scale = ggml_get_op_params_f32(scale_node, 0); + const float bias = ggml_get_op_params_f32(scale_node, 1); + + const int block_size = 256; + const int64_t n_blocks = (n + block_size - 1) / block_size; + GGML_ASSERT(n_blocks <= INT_MAX); + dyn_conv_tail_f32<<>>((const float *) x->data, (const float *) base->data, (const float *) cur->data, + taps, (float *) dst->data, n_channels, n_seq_tokens, n_rows, head_dim, n, scale, bias); +} diff --git a/ggml/src/ggml-cuda/ssm-conv.cuh b/ggml/src/ggml-cuda/ssm-conv.cuh index a3d54846ce59..0208f65baf39 100644 --- a/ggml/src/ggml-cuda/ssm-conv.cuh +++ b/ggml/src/ggml-cuda/ssm-conv.cuh @@ -6,3 +6,18 @@ void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, g // of the result for the mat-vec that reads it (q8_1_src1) bool ggml_cuda_can_ssm_conv_mul(const ggml_tensor * conv, const ggml_tensor * mul); void ggml_cuda_op_ssm_conv_mul(ggml_backend_cuda_context & ctx, ggml_tensor * conv, ggml_tensor * mul, const ggml_tensor * q8_1_src1); + +// taps of ggml_cuda_op_dyn_conv_tail: one strided [1, n_head, n_seq_tokens, n_seqs] view and one row offset of x per lag +#define GGML_CUDA_DYN_CONV_MAX_TAPS 8 +struct ggml_cuda_dyn_conv_taps { + const float * data[GGML_CUDA_DYN_CONV_MAX_TAPS]; + int64_t nb1[GGML_CUDA_DYN_CONV_MAX_TAPS]; // in floats + int64_t nb2[GGML_CUDA_DYN_CONV_MAX_TAPS]; + int64_t nb3[GGML_CUDA_DYN_CONV_MAX_TAPS]; + int row[GGML_CUDA_DYN_CONV_MAX_TAPS]; + int n; + int n_conv; +}; + +void ggml_cuda_op_dyn_conv_tail(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * base, const ggml_tensor * cur, + const ggml_cuda_dyn_conv_taps & taps, int head_dim, const ggml_tensor * scale_node, ggml_tensor * dst); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index f1352b339076..0d9dbba9c3ea 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -4282,6 +4282,172 @@ struct test_add_scale : public test_case { } }; +// tail of a causal convolution with input-dependent taps per head, as in Inkling 2 +struct test_dyn_conv_tail : public test_case { + const int64_t head_dim; + const int64_t n_head; + const int64_t n_conv; + const int64_t n_seq_tokens; + const int64_t n_seqs; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "DYN_CONV_TAIL"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR5(head_dim, n_head, n_conv, n_seq_tokens, n_seqs); + } + + test_dyn_conv_tail(int64_t head_dim = 128, int64_t n_head = 8, int64_t n_conv = 4, int64_t n_seq_tokens = 1, int64_t n_seqs = 1) + : head_dim(head_dim), n_head(n_head), n_conv(n_conv), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t n_ch = head_dim*n_head; + const int64_t n_tokens = n_seq_tokens*n_seqs; + + ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_conv - 1 + n_seq_tokens, n_ch, n_seqs); + ggml_tensor * dyn = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_conv*n_head, n_tokens); + ggml_tensor * base = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ch, n_tokens); + ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ch, n_tokens); + ggml_set_name(x, "x"); + ggml_set_name(dyn, "dyn"); + ggml_set_name(base, "base"); + ggml_set_name(cur, "cur"); + + ggml_tensor * xt = ggml_cont(ctx, ggml_transpose(ctx, x)); + ggml_tensor * dyn3 = ggml_reshape_3d(ctx, dyn, n_conv, n_head, n_tokens); + + ggml_tensor * out = base; + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_4d(ctx, dyn3, 1, n_head, n_seq_tokens, n_seqs, + dyn3->nb[1], dyn3->nb[2], n_seq_tokens*dyn3->nb[2], lag*dyn3->nb[0]); + ggml_tensor * window = ggml_view_4d(ctx, xt, head_dim, n_head, n_seq_tokens, n_seqs, + head_dim*xt->nb[0], xt->nb[1], xt->nb[2], (n_conv - 1 - lag)*xt->nb[1]); + out = ggml_add(ctx, out, ggml_reshape_2d(ctx, ggml_mul(ctx, window, tap), n_ch, n_tokens)); + } + + ggml_tensor * res = ggml_scale(ctx, ggml_add(ctx, cur, out), 1.0f/sqrtf(2*n_conv + 1)); + ggml_set_name(res, "out"); + return res; + } +}; + +// attention over the depth as in Inkling 2: rms_norm(cur) after the stacked blocks, softmax of the query scores, weighted sum +struct test_depth_mix : public test_case { + const int64_t n_embd; + const int64_t n_stack; + const int64_t n_query; + const int64_t n_tokens; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "DEPTH_MIX"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR4(n_embd, n_stack, n_query, n_tokens); + } + + double max_nmse_err() override { + return 1e-6; + } + + test_depth_mix(int64_t n_embd = 512, int64_t n_stack = 3, int64_t n_query = 1, int64_t n_tokens = 1) + : n_embd(n_embd), n_stack(n_stack), n_query(n_query), n_tokens(n_tokens) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tokens); + ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_query); + ggml_set_name(cur, "cur"); + ggml_set_name(query, "query"); + + ggml_tensor * states = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens), 1e-6f); + if (n_stack > 0) { + ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, n_stack, n_tokens); + ggml_set_name(stack, "stack"); + states = ggml_concat(ctx, stack, states, 1); + } + + ggml_tensor * scores = nullptr; + if (n_query == 1) { + scores = ggml_reshape_3d(ctx, ggml_mul_mat(ctx, query, states), states->ne[1], 1, n_tokens); + } else { + ggml_tensor * queries = ggml_repeat(ctx, query, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, n_query, n_tokens)); + scores = ggml_mul_mat(ctx, states, queries); + } + scores = ggml_soft_max_ext(ctx, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); + + ggml_tensor * out = ggml_mul_mat(ctx, ggml_cont(ctx, ggml_transpose(ctx, states)), scores); + ggml_set_name(out, "out"); + return out; + } +}; + +// per-expert weight scale of a MUL_MAT_ID result: REPEAT, GET_ROWS by the selected experts, MUL +struct test_moe_expert_scale : public test_case { + const int64_t n0; + const int64_t n_expert; + const int64_t n_used; + const int64_t n_tokens; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MOE_EXPERT_SCALE"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR4(n0, n_expert, n_used, n_tokens); + } + + test_moe_expert_scale(int64_t n0 = 64, int64_t n_expert = 16, int64_t n_used = 4, int64_t n_tokens = 5) + : n0(n0), n_expert(n_expert), n_used(n_used), n_tokens(n_tokens) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * res = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n0, n_used, n_tokens); + ggml_tensor * ws = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_expert); + ggml_tensor * all = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_expert, n_tokens); + ggml_set_name(res, "res"); + ggml_set_name(ws, "ws"); + ggml_set_name(all, "ids"); + + // the selected experts are the first n_used of each row, like a view of the argsort + ggml_tensor * ids = ggml_view_2d(ctx, all, n_used, n_tokens, all->nb[1], 0); + + ggml_tensor * s = ggml_reshape_3d(ctx, ws, 1, n_expert, 1); + s = ggml_repeat_4d(ctx, s, 1, n_expert, n_tokens, 1); + s = ggml_get_rows(ctx, s, ids); + + ggml_tensor * out = ggml_mul(ctx, res, s); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 gen(0x5CA1E); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->type == GGML_TYPE_I32) { + std::vector data(ggml_nelements(t)); + for (int64_t r = 0; r < t->ne[1]; ++r) { + std::vector perm(t->ne[0]); + std::iota(perm.begin(), perm.end(), 0); + std::shuffle(perm.begin(), perm.end(), gen); + std::copy(perm.begin(), perm.end(), data.begin() + r*t->ne[0]); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(int32_t)); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_RMS_NORM + GGML_OP_MUL + GGML_OP_ADD (+ GGML_OP_MUL) struct test_rms_norm_mul_add : public test_case { const ggml_type type; @@ -14650,6 +14816,21 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_tanh_gate({2304, 1, 1, 1})); test_cases.emplace_back(new test_tanh_gate({2304, 7, 1, 1})); + for (int64_t n_seq_tokens : {1, 7, 64}) { + test_cases.emplace_back(new test_dyn_conv_tail(128, 8, 4, n_seq_tokens, 1)); + } + test_cases.emplace_back(new test_dyn_conv_tail(128, 8, 4, 5, 3)); + test_cases.emplace_back(new test_dyn_conv_tail( 64, 3, 3, 9, 2)); + for (int64_t n_stack : {0, 1, 5}) { + for (int64_t n_query : {1, 3, 4}) { + test_cases.emplace_back(new test_depth_mix(2304, n_stack, n_query, 1)); + } + } + test_cases.emplace_back(new test_depth_mix(512, 7, 1, 9)); + test_cases.emplace_back(new test_depth_mix(512, 7, 4, 33)); + test_cases.emplace_back(new test_moe_expert_scale(64, 16, 4, 5)); + test_cases.emplace_back(new test_moe_expert_scale(1152, 128, 8, 1)); + test_cases.emplace_back(new test_moe_expert_scale(1152, 128, 8, 17)); test_cases.emplace_back(new test_add_scale({2304, 1, 1, 1})); test_cases.emplace_back(new test_add_scale({1024, 7, 2, 1}, 0.2f, 0.5f)); From f6440835ed560223c87eaeb2c6bc81a8ac2b318d Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:44:57 +0000 Subject: [PATCH 2/2] inkling2: order the dynamic taps for fusion; dense rel-pos bias fallback in F16 Assisted-by: Claude Opus 5.5 --- src/llama-graph.cpp | 11 +++++------ src/models/inkling2.cpp | 3 +++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index e6a4d9e7dc25..e71731c056e9 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -4470,15 +4470,14 @@ ggml_tensor * llm_graph_context::build_attn_rel_mask(ggml_tensor * mask, const l const int64_t n_rows = hparams.is_swa(il) ? n_tps : std::max(32, (n_tps + 31)/32); if (n_rows >= n_tps) { - // [n_head, n_kv, n_tokens] -> [n_kv, n_tps, n_head, n_stream] + // [n_head, n_kv, n_tokens] -> [n_kv, n_tps, n_head, n_stream], in the type of the mask ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tps, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + kq_b = ggml_permute(ctx0, kq_b, 2, 0, 1, 3); + kq_b = mask->type == GGML_TYPE_F32 ? ggml_cont(ctx0, kq_b) : + ggml_cpy(ctx0, kq_b, ggml_new_tensor_4d(ctx0, mask->type, n_kv, n_tps, n_head, n_stream)); - kq_mask = ggml_add(ctx0, kq_b, mask->type == GGML_TYPE_F32 ? mask : ggml_cast(ctx0, mask, GGML_TYPE_F32)); - if (mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, mask->type); - } + kq_mask = ggml_add(ctx0, kq_b, mask); } else { // the scheduler copies each view of an input to the device on its own, copy the whole input once instead rel_pos = ggml_cont(ctx0, rel_pos); diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 0e2f5ed32a0c..75207b04dd8e 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -238,6 +238,9 @@ ggml_tensor * llama_model_inkling2::graph::convolve( out = ggml_reshape_2d(ctx0, out, n_channels, n_tokens); if (dynamic) { + // the taps first, so that the element-wise tail of the convolution is one run of nodes + ggml_build_forward_expand(gf, dynamic); + const int64_t n_heads = dynamic->ne[0]/n_conv; dynamic = ggml_reshape_3d(ctx0, dynamic, n_conv, n_heads, n_tokens);