From 222a7d33f6f9688ae5862adb2fd2d37eab18049d Mon Sep 17 00:00:00 2001 From: co-seven Date: Fri, 27 Nov 2026 03:20:30 +0000 Subject: [PATCH 1/2] spacemit: optimize SSM state handling and cache graph execution plans Assisted-by: Codex --- ggml/src/ggml-spacemit/ggml-spacemit.cpp | 370 +++++++++++++++++++++- ggml/src/ggml-spacemit/ime.cpp | 24 +- ggml/src/ggml-spacemit/rvv_kernels.cpp | 287 +++++++++++++++++ ggml/src/ggml-spacemit/rvv_kernels.h | 5 + ggml/src/ggml-spacemit/spacemit-opnode.h | 2 + ggml/src/ggml-spacemit/spacemit-session.h | 7 +- 6 files changed, 677 insertions(+), 18 deletions(-) diff --git a/ggml/src/ggml-spacemit/ggml-spacemit.cpp b/ggml/src/ggml-spacemit/ggml-spacemit.cpp index a1c253350d32..de468fd42a6b 100644 --- a/ggml/src/ggml-spacemit/ggml-spacemit.cpp +++ b/ggml/src/ggml-spacemit/ggml-spacemit.cpp @@ -236,6 +236,63 @@ static int64_t concat_view_first_col(const ggml_tensor * c, const ggml_tensor * // SSM_CONV op param set by graph_optimize when the concat inputs are kept allocated until the ssm_conv static constexpr int SSM_CONV_PARAM_INPUTS_KEPT = GGML_MAX_OP_PARAMS / sizeof(int32_t) - 1; +static const ggml_tensor * tensor_storage_root(const ggml_tensor * t); + +// build_conv_state_store's rollback window: [3, Kw, channels, sequences], +// Kw=min(tokens,4). Windows overlap by two columns; their union is exactly +// [tokens-(Kw-1), tokens+3), in every channel/sequence of the concat. Restrict +// this extension to the model's four-slot layout rather than accepting +// arbitrary strided aliases of a partially materialized tensor. +static int64_t concat_mtp_window_first_col(const ggml_tensor * c, const ggml_tensor * v) { + const int64_t tokens = c->src[1]->ne[0]; + const int64_t kw = std::min(tokens, 4); + if (tokens < 1 || v->op != GGML_OP_VIEW || v->view_src != c || v->type != c->type || + v->ne[0] != 3 || v->ne[1] != kw || v->ne[2] != c->ne[1] || v->ne[3] != c->ne[2] || + v->nb[0] != sizeof(float) || v->nb[1] != sizeof(float) || + v->nb[2] != c->nb[1] || v->nb[3] != c->nb[2] || + v->view_offs != (size_t) (tokens - (kw - 1)) * sizeof(float) || + c->ne[0] != tokens + 3 || c->nb[1] < (size_t) c->ne[0] * sizeof(float) || + c->nb[2] < (size_t) c->ne[1] * c->nb[1]) { + return -1; + } + return tokens - (kw - 1); +} + +// SET_ROWS reads src[0] and writes its separate destination src[2]. For the +// new rollback-window path accept only these read-only consumers; in-place +// aliases (CPY/SET_ROWS destinations, SCALE_INPLACE, etc.) and further view +// transformations must retain the full concat. Also reject writes to either +// concat input between its original copy and the fused convolution: allocation +// dependencies extend lifetimes, but do not prevent an explicit in-place write. +static bool concat_mtp_consumers_readonly(const ggml_cgraph * graph, const ggml_tensor * c, + int ci, int ssm_idx) { + const ggml_tensor * input0 = tensor_storage_root(c->src[0]); + const ggml_tensor * input1 = tensor_storage_root(c->src[1]); + for (int i = 0; i < graph->n_nodes; ++i) { + const ggml_tensor * t = graph->nodes[i]; + if (t->view_src == c && concat_mtp_window_first_col(c, t) < 0) { + return false; + } + if (i > ci && i < ssm_idx && !ggml_op_is_empty(t->op) && + (tensor_storage_root(t) == input0 || tensor_storage_root(t) == input1)) { + return false; + } + for (int j = 0; j < GGML_MAX_SRC; ++j) { + const ggml_tensor * s = t->src[j]; + if (s && s->view_src == c && + (concat_mtp_window_first_col(c, s) < 0 || t->op != GGML_OP_SET_ROWS || j != 0 || + t->view_src == c || !t->src[2] || t->src[2]->type != GGML_TYPE_F32 || + t->src[2]->ne[0] != 3 || t->src[2]->ne[1] != 4 || + t->src[2]->ne[2] != c->ne[1] || t->src[2]->ne[3] != c->ne[2])) { + return false; + } + } + } + return true; +} + + + // concat -> ssm_conv fusion analysis: SSM_CONV reads the two concat inputs directly and CONCAT only // writes the trailing columns that are read back through views (the conv state update). Returns the // single ssm_conv consumer (with its graph index) and the first column any view reads back. Fails if @@ -252,11 +309,22 @@ static bool ssm_conv_concat_fusable(const ggml_cgraph * graph, int ci, bool need int ssm_idx = -1; int64_t col0 = c->ne[0]; // min column read back through views + bool mtp_window = false; + auto view_first_col = [&](const ggml_tensor * v) { + const int64_t plain_col = concat_view_first_col(c, v); + if (plain_col >= 0) { + return plain_col; + } + const int64_t col = concat_mtp_window_first_col(c, v); + mtp_window |= col >= 0; + return col; + }; + for (int i = 0; i < graph->n_nodes; ++i) { ggml_tensor * t = graph->nodes[i]; if (t->view_src == c) { - const int64_t col = concat_view_first_col(c, t); + const int64_t col = view_first_col(t); if (col < 0) { return false; } @@ -280,7 +348,7 @@ static bool ssm_conv_concat_fusable(const ggml_cgraph * graph, int ci, bool need return false; // some other consumer needs the full concat output } } else if (s->view_src == c) { - const int64_t col = concat_view_first_col(c, s); + const int64_t col = view_first_col(s); if (col < 0) { return false; } @@ -293,6 +361,33 @@ static bool ssm_conv_concat_fusable(const ggml_cgraph * graph, int ci, bool need return false; } + if (mtp_window && !concat_mtp_consumers_readonly(graph, c, ci, ssm_idx)) { + return false; + } + + // Both inputs are now read at SSM instead of at CONCAT. Allocation + // dependencies preserve their lifetime, but an intervening in-place write + // must retain the ordinary CONCAT snapshot, including external aliases. + for (int i = ci + 1; i < ssm_idx; ++i) { + const ggml_tensor * t = graph->nodes[i]; + if (!op_is_compute(const_cast(t))) { + continue; + } + for (const ggml_tensor * input : {c->src[0], c->src[1]}) { + if (tensor_storage_root(t) == tensor_storage_root(input)) { + return false; + } + // The post-allocation check covers physically aliased distinct roots. + if (need_kept && t->data && input->data) { + const uintptr_t x = reinterpret_cast(t->data); + const uintptr_t y = reinterpret_cast(input->data); + if (x <= y ? y - x < ggml_nbytes(t) : x - y < ggml_nbytes(input)) { + return false; + } + } + } + } + // The fused kernels re-check their layouts at compute time and abort on a mismatch (there is no // fallback once the concat half has materialized only its trailing columns), so the gate must be // a superset of forward_concat_dim0_transposed_f32 + forward_ssm_conv_concat_f32: types, element @@ -310,6 +405,192 @@ static bool ssm_conv_concat_fusable(const ggml_cgraph * graph, int ci, bool need return true; } +static constexpr int SSM_PERSISTENT_PARAM_INPUTS_KEPT = GGML_MAX_OP_PARAMS / sizeof(int32_t) - 2; + +static const ggml_tensor * tensor_storage_root(const ggml_tensor * t) { + while (t && t->view_src) { + t = t->view_src; + } + return t; +} + +static size_t tensor_storage_offset(const ggml_tensor * t) { + size_t offset = 0; + while (t && t->view_src) { + offset += t->view_offs; + t = t->view_src; + } + return offset; +} + +static int next_compute_index(const ggml_cgraph * graph, int i) { + for (++i; i < graph->n_nodes; ++i) { + if (op_is_compute(graph->nodes[i])) { + return i; + } + } + return -1; +} + + +// Materialize the next state directly at the original CPY; SSM still reads the old gather. +static ggml_tensor * ssm_conv_state_store_match(const ggml_cgraph * graph, int ci, int si, + ggml_tensor * ssm, int * copy_index) { + ggml_tensor * cat = graph->nodes[ci]; + const ggml_tensor * st = cat->src[0]; + const ggml_tensor * q = cat->src[1]; + const ggml_tensor * w = ssm->src[1]; + const int64_t channels = cat->ne[1]; + if (channels <= 0 || cat->ne[0] != 4 || cat->ne[2] != 1 || cat->ne[3] != 1 || + !ggml_is_contiguous(cat) || !ggml_is_contiguous(st) || st->ne[0] != 3 || + st->ne[1] != channels || st->ne[2] != 1 || st->ne[3] != 1 || + tensor_storage_root(st)->op != GGML_OP_GET_ROWS || q->ne[0] != 1 || + q->ne[1] != channels || q->ne[2] != 1 || q->ne[3] != 1 || + ssm->ne[0] != channels || ssm->ne[1] != 1 || ssm->ne[2] != 1 || ssm->ne[3] != 1 || + !ggml_is_contiguous(ssm) || w->ne[1] != channels || w->ne[2] != 1 || w->ne[3] != 1) { + return nullptr; + } + const int pi = next_compute_index(graph, ci); + if (pi < 0 || pi >= si) { + return nullptr; + } + ggml_tensor * copy = graph->nodes[pi]; + const ggml_tensor * last = copy->src[0]; + const ggml_tensor * cache = tensor_storage_root(copy); + const size_t state_bytes = 3 * channels * sizeof(float); + if (copy->op != GGML_OP_CPY || copy->type != GGML_TYPE_F32 || !last || !copy->src[1] || + !ggml_is_contiguous(copy) || ggml_nbytes(copy) != state_bytes || + last->type != GGML_TYPE_F32 || last->ne[0] != 3 || last->ne[1] != channels || + last->ne[2] != 1 || last->ne[3] != 1 || last->nb[0] != sizeof(float) || last->nb[1] != cat->nb[1] || + tensor_storage_root(last) != cat || tensor_storage_offset(last) != sizeof(float) || + !cache || cache->op != GGML_OP_NONE || !cache->buffer || !cache->data || + tensor_storage_root(st) == cache || tensor_storage_root(q) == cache || tensor_storage_root(w) == cache) { + return nullptr; + } + for (int i = 0; i < graph->n_nodes + graph->n_leafs; ++i) { + const ggml_tensor * t = i < graph->n_nodes ? graph->nodes[i] : graph->leafs[i - graph->n_nodes]; + if (tensor_storage_root(t) == cat && (t->flags & GGML_TENSOR_FLAG_OUTPUT) && !ggml_is_empty(t)) { + return nullptr; + } + if (!op_is_compute(const_cast(t))) { + continue; + } + if (t != cat && tensor_storage_root(t) == cat) { + return nullptr; + } + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (t->src[j] && tensor_storage_root(t->src[j]) == cat && + !(t == ssm && j == 0) && !(t == copy && j == 0)) { + return nullptr; + } + } + } + *copy_index = pi; + return copy; +} + +// Delay this state update only across computations independent of both cache and index. +// The original gather can be recreated at SSM if a runtime alias defeats the direct path. +static ggml_tensor * ssm_conv_persistent_match(const ggml_cgraph * graph, int ci, int si, + ggml_tensor * ssm, bool need_kept, + ggml_tensor ** gather_out = nullptr, + int * copy_index_out = nullptr) { + if (need_kept && ggml_get_op_params_i32(ssm, SSM_PERSISTENT_PARAM_INPUTS_KEPT) != 1) { + return nullptr; + } + int pi = -1; + ggml_tensor * copy = ssm_conv_state_store_match(graph, ci, si, ssm, &pi); + if (!copy) { + return nullptr; + } + const ggml_tensor * cat = graph->nodes[ci]; + auto * gather = const_cast(tensor_storage_root(cat->src[0])); + const ggml_tensor * cache = gather->src[0]; + const ggml_tensor * index = gather->src[1]; + const ggml_tensor * dest = tensor_storage_root(copy); + const ggml_tensor * root = tensor_storage_root(cache); + const ggml_tensor * index_root = tensor_storage_root(index); + if (gather->type != GGML_TYPE_F32 || !ggml_is_contiguous(gather) || + tensor_storage_offset(cat->src[0]) != 0 || ggml_nbytes(gather) != ggml_nbytes(copy) || + !cache || cache->type != GGML_TYPE_F32 || !ggml_is_contiguous(cache) || + cache->ne[0] != ggml_nelements(copy) || cache->ne[2] != 1 || cache->ne[3] != 1 || + !root || root->op != GGML_OP_NONE || !root->buffer || !root->data || + !index || index->type != GGML_TYPE_I32 || ggml_nelements(index) != 1 || + !ggml_is_contiguous(index) || index_root == root || index_root == dest || + cat->src[1]->nb[1] != sizeof(float) || ssm->src[1]->nb[1] != 4 * sizeof(float) || + tensor_storage_root(cat->src[1]) == root || tensor_storage_root(ssm->src[1]) == root || + tensor_storage_root(ssm) == root || tensor_storage_root(ssm) == dest) { + return nullptr; + } + int gi = -1; + for (int i = 0; i < ci; ++i) { + if (graph->nodes[i] == gather) { + gi = i; + } + } + if (gi < 0) { + return nullptr; + } + for (int i = 0; i < graph->n_nodes + graph->n_leafs; ++i) { + const ggml_tensor * t = i < graph->n_nodes ? graph->nodes[i] : graph->leafs[i - graph->n_nodes]; + const ggml_tensor * tr = tensor_storage_root(t); + if (tr == gather && (t->flags & GGML_TENSOR_FLAG_OUTPUT) && !ggml_is_empty(t)) { + return nullptr; + } + if (!op_is_compute(const_cast(t))) { + continue; + } + if (t != gather && tr == gather) { + return nullptr; + } + // After allocation, also reject physical aliases between distinct roots. + // This prevents a delayed gather from observing an intervening in-place + // write that an externally supplied buffer hid from view-root identity. + auto overlaps = [](const ggml_tensor * a, const ggml_tensor * b) { + if (!a->data || !b->data) { + return false; + } + const uintptr_t x = reinterpret_cast(a->data); + const uintptr_t y = reinterpret_cast(b->data); + return x <= y ? y - x < ggml_nbytes(a) : x - y < ggml_nbytes(b); + }; + if (need_kept && i > gi && i < si && t != copy && + (overlaps(t, cache) || overlaps(t, index))) { + return nullptr; + } + if (need_kept && i > pi && i < si && overlaps(t, copy)) { + return nullptr; + } + // No mutation of the source snapshot or dynamic index until the delayed read. + // No read/write of the destination after its original CPY until delayed store. + if (i > gi && i < si && t != copy && (tr == root || tr == index_root)) { + return nullptr; + } + if (i > pi && i < si && tr == dest) { + return nullptr; + } + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (!t->src[j]) { + continue; + } + const ggml_tensor * sr = tensor_storage_root(t->src[j]); + if (sr == gather && !(t == cat && j == 0)) { + return nullptr; + } + if (i > pi && i < si && (sr == dest || (need_kept && overlaps(t->src[j], copy)))) { + return nullptr; + } + } + } + if (gather_out) { + *gather_out = gather; + } + if (copy_index_out) { + *copy_index_out = pi; + } + return copy; +} + static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vector & nodes, std::unordered_set & emitted) { ggml_tensor * n = graph->nodes[i]; @@ -318,9 +599,38 @@ static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vectornodes[ci] != n->src[0]) { + continue; + } + ggml_tensor * gather = nullptr; + if (ggml_tensor * copy = ssm_conv_persistent_match(graph, ci, i, n, true, &gather)) { + nodes.emplace_back(n, std::vector{}, SPACEMIT_OP_SSM_CONV_PERSISTENT, + std::vector{copy, gather}); + return true; + } + } + } nodes.emplace_back(n, std::vector{}, SPACEMIT_OP_SSM_CONV_CONCAT); return true; } + if (n->op == GGML_OP_GET_ROWS) { + for (int ci = i + 1; ci < graph->n_nodes; ++ci) { + if (graph->nodes[ci]->op != GGML_OP_CONCAT || + tensor_storage_root(graph->nodes[ci]->src[0]) != n) { + continue; + } + ggml_tensor * ssm = nullptr; + int si = -1; + int64_t col0 = 0; + ggml_tensor * gather = nullptr; + if (ssm_conv_concat_fusable(graph, ci, true, &ssm, &si, &col0) && + ssm_conv_persistent_match(graph, ci, si, ssm, true, &gather) && gather == n) { + return true; // no gather opnode: materialize only in the SSM runtime fallback + } + } + } // Find the next compute node, skipping empty (NONE) nodes. test-backend-ops // inserts NONE sentinels between ops for out-of-bounds detection, which must @@ -359,6 +669,19 @@ static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vector{}, SPACEMIT_OP_SSM_CONV_STATE_STORE, + std::vector{ssm}); + i = copy_index; + emitted.insert(ssm); + return true; + } spacemit_opnode cat(n, {}, SPACEMIT_OP_CONCAT_STATE); cat.kernel_params[0] = (int32_t) col0; nodes.push_back(std::move(cat)); @@ -573,10 +896,26 @@ static ggml_status ggml_backend_spacemit_graph_compute(ggml_backend_t backend, g // stable shape-class, so the list is only rebuilt when the topology changes. // try_fuse_node folds matching patterns into fused opnodes and consumes their // nodes; non-matching nodes are appended as single ops. - if (!(graph->uid != 0 && sess->cached_graph.uid == graph->uid)) { - sess->cached_graph.uid = graph->uid; - sess->cached_graph.nodes.clear(); - sess->cached_graph.nodes.reserve(graph->n_nodes); + spacemit_session::graph_cache_entry * cached = nullptr; + if (graph->uid != 0) { + for (auto & entry : sess->cached_graphs) { + if (entry.uid == graph->uid) { + cached = &entry; + break; + } + } + } + if (cached == nullptr) { + if (graph->uid != 0) { + cached = &sess->cached_graphs[sess->next_graph_cache]; + sess->next_graph_cache = (sess->next_graph_cache + 1) % sess->cached_graphs.size(); + } else { + cached = &sess->uncached_graph; + } + // Scheduler split UIDs are unique; never inspect tensors in an unmatched entry. + cached->uid = 0; + cached->nodes.clear(); + cached->nodes.reserve(graph->n_nodes); std::unordered_set emitted; // nodes already emitted by try_fuse_node for (int i = 0; i < graph->n_nodes; ++i) { ggml_tensor * n = graph->nodes[i]; @@ -585,22 +924,23 @@ static ggml_status ggml_backend_spacemit_graph_compute(ggml_backend_t backend, g } // On a match, try_fuse_node pushes the fused opnodes and advances i past // the nodes it consumed; otherwise the node is appended as a single op. - if (try_fuse_node(graph, i, sess->cached_graph.nodes, emitted)) { + if (try_fuse_node(graph, i, cached->nodes, emitted)) { continue; } - sess->cached_graph.nodes.emplace_back(n); + cached->nodes.emplace_back(n); } int n_fused = 0; - for (const auto & node : sess->cached_graph.nodes) { + for (const auto & node : cached->nodes) { if (!node.fused.empty() || node.opcode != SPACEMIT_OP_INVALID) { n_fused++; } } GGML_LOG_DEBUG("ggml-spacemit: %s graph %llu: %zu opnodes, %d fused\n", sess->c_name(), - (unsigned long long) graph->uid, sess->cached_graph.nodes.size(), n_fused); + (unsigned long long) graph->uid, cached->nodes.size(), n_fused); + cached->uid = graph->uid; } - const auto & opnodes = sess->cached_graph.nodes; + const auto & opnodes = cached->nodes; int n_threads = sess->num_cores > 0 ? sess->num_cores : 1; size_t workspace_size = 0; @@ -696,6 +1036,7 @@ static void ggml_backend_spacemit_graph_optimize(ggml_backend_t backend, ggml_cg for (int i = 0; i < graph->n_nodes; ++i) { if (graph->nodes[i]->op == GGML_OP_SSM_CONV) { ggml_set_op_params_i32(graph->nodes[i], SSM_CONV_PARAM_INPUTS_KEPT, 0); + ggml_set_op_params_i32(graph->nodes[i], SSM_PERSISTENT_PARAM_INPUTS_KEPT, 0); } } if (params == nullptr || params->add_alloc_dep == nullptr) { @@ -710,6 +1051,12 @@ static void ggml_backend_spacemit_graph_optimize(ggml_backend_t backend, ggml_cg params->add_alloc_dep(params->user_data, c->src[0], ssm); params->add_alloc_dep(params->user_data, c->src[1], ssm); ggml_set_op_params_i32(ssm, SSM_CONV_PARAM_INPUTS_KEPT, 1); + ggml_tensor * gather = nullptr; + if (ssm_conv_persistent_match(graph, i, ssm_idx, ssm, false, &gather)) { + params->add_alloc_dep(params->user_data, gather->src[0], ssm); + params->add_alloc_dep(params->user_data, gather->src[1], ssm); + ggml_set_op_params_i32(ssm, SSM_PERSISTENT_PARAM_INPUTS_KEPT, 1); + } } } @@ -833,6 +1180,7 @@ static bool ggml_backend_spacemit_device_supports_op(ggml_backend_dev_t dev, con supp = true; break; + case GGML_OP_ARANGE: case GGML_OP_SCALE: case GGML_OP_MUL_MAT: case GGML_OP_MUL_MAT_ID: diff --git a/ggml/src/ggml-spacemit/ime.cpp b/ggml/src/ggml-spacemit/ime.cpp index 493c989d4ccf..745b46fe1054 100644 --- a/ggml/src/ggml-spacemit/ime.cpp +++ b/ggml/src/ggml-spacemit/ime.cpp @@ -1420,6 +1420,9 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { default: return false; } + case GGML_OP_ARANGE: + spacemit_kernels::rvv::forward_arange_f32(ctx, op); + return true; case GGML_OP_SCALE: if (op->src[0]->type == GGML_TYPE_F32) { spacemit_kernels::rvv::forward_scale_f32(ctx, op); @@ -1530,6 +1533,10 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { } if (ggml_is_contiguous(op) && ggml_is_contiguous(src0) && ggml_nelements(src0) == ggml_nelements(op)) { + if (op->type == GGML_TYPE_I32 && src0->type == GGML_TYPE_F32) { + spacemit_kernels::rvv::forward_cpy_f32_to_i32(ctx, op); + return true; + } if (op->type == GGML_TYPE_F16 && src0->type == GGML_TYPE_F32) { spacemit_kernels::rvv::forward_cpy_f32_to_f16(ctx, op); return true; @@ -1860,10 +1867,6 @@ class tensor_traits_f16 : public ggml::spacemit::tensor_traits_base { const int ith = ctx.ith; const int nth = ctx.nth; - if (ith == 0 && getenv("GGML_SPACEMIT_Q41_TRACE") != nullptr) { - fprintf(stderr, "q41_mul_mat: N=%zu M=%zu K=%zu (%s)\n", N, M, K, M == 1 ? "decode" : "prefill"); - } - const size_t out_row_stride = dst->nb[1]; // bytes constexpr size_t m_tile = F16_M_TILE; @@ -2747,6 +2750,12 @@ bool ggml_spacemit_compute_opnode(ggml::spacemit::context & ctx, const spacemit_ // They run at their original graph positions (see try_fuse_node); the allocator plans buffer // reuse on that order, so they must not be merged into one opnode at the concat position. switch (node.opcode) { + case SPACEMIT_OP_SSM_CONV_PERSISTENT: + spacemit_kernels::rvv::forward_ssm_conv_persistent(ctx, node.node, node.extra_dsts[0], node.extra_dsts[1]); + return true; + case SPACEMIT_OP_SSM_CONV_STATE_STORE: + spacemit_kernels::rvv::forward_ssm_conv_state_store(ctx, node.extra_dsts[0], node.node); + return true; case SPACEMIT_OP_CONCAT_STATE: // only the trailing columns read back through views (the conv state update) if (!spacemit_kernels::rvv::forward_concat_dim0_transposed_f32(ctx, node.node, @@ -2806,6 +2815,11 @@ const ggml::spacemit::tensor_traits_base * ggml_spacemit_get_tensor_traits(const return common; } break; + case GGML_OP_ARANGE: + if (op->type == GGML_TYPE_F32 && ggml_is_vector(op) && ggml_is_contiguous(op)) { + return common; + } + break; case GGML_OP_SCALE: if (op->src[0] && op->src[0]->type == GGML_TYPE_F32) { return common; @@ -2896,7 +2910,7 @@ const ggml::spacemit::tensor_traits_base * ggml_spacemit_get_tensor_traits(const return common; } if (op->src[0] && - ((op->type == GGML_TYPE_F16 && op->src[0]->type == GGML_TYPE_F32) || + (((op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_I32) && op->src[0]->type == GGML_TYPE_F32) || (op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F16)) && ggml_is_contiguous(op) && ggml_is_contiguous(op->src[0]) && ggml_nelements(op->src[0]) == ggml_nelements(op)) { diff --git a/ggml/src/ggml-spacemit/rvv_kernels.cpp b/ggml/src/ggml-spacemit/rvv_kernels.cpp index a9b5032d9baa..6e65cc9ad675 100644 --- a/ggml/src/ggml-spacemit/rvv_kernels.cpp +++ b/ggml/src/ggml-spacemit/rvv_kernels.cpp @@ -4101,6 +4101,34 @@ void forward_gated_delta_net(ggml::spacemit::context & ctx, ggml_tensor * op) { } } +static bool gdn_state_ranges_overlap(const void * a, size_t na, const void * b, size_t nb) { + if (!na || !nb) { + return false; + } + const uintptr_t x = reinterpret_cast(a); + const uintptr_t y = reinterpret_cast(b); + return x <= y ? y - x < na : x - y < nb; +} + +void forward_arange_f32(ggml::spacemit::context & ctx, ggml_tensor * op) { + const float start = ggml_get_op_params_f32(op, 0); + const float step = ggml_get_op_params_f32(op, 2); + float * dst = static_cast(op->data); + + const int64_t n = ggml_nelements(op); + const int64_t chunk = (n + ctx.nth - 1) / ctx.nth; + const int64_t begin = chunk * ctx.ith; + const int64_t end = std::min(begin + chunk, n); + for (int64_t i = begin; i < end; ) { + const size_t vl = __riscv_vsetvl_e64m4(end - i); + vuint64m4_t index = __riscv_vadd_vx_u64m4(__riscv_vid_v_u64m4(vl), i, vl); + vfloat32m2_t values = __riscv_vfncvt_f_xu_w_f32m2(index, vl); + values = __riscv_vfmacc_vf_f32m2(__riscv_vfmv_v_f_f32m2(start, vl), step, values, vl); + __riscv_vse32_v_f32m2(dst + i, values, vl); + i += vl; + } +} + void forward_scale_f32(ggml::spacemit::context & ctx, ggml_tensor * op) { const ggml_tensor * src0 = op->src[0]; ggml_tensor * dst = op; @@ -4262,6 +4290,21 @@ void forward_cpy_f32_row_strided(ggml::spacemit::context & ctx, ggml_tensor * op } } +void forward_cpy_f32_to_i32(ggml::spacemit::context & ctx, ggml_tensor * op) { + const float * src = static_cast(op->src[0]->data); + int32_t * dst = static_cast(op->data); + const int64_t n = ggml_nelements(op); + const int64_t chunk = (n + ctx.nth - 1) / ctx.nth; + const int64_t begin = chunk * ctx.ith; + const int64_t end = std::min(begin + chunk, n); + for (int64_t i = begin; i < end; ) { + const size_t vl = __riscv_vsetvl_e32m4(end - i); + vfloat32m4_t values = __riscv_vle32_v_f32m4(src + i, vl); + __riscv_vse32_v_i32m4(dst + i, __riscv_vfcvt_rtz_x_f_v_i32m4(values, vl), vl); + i += vl; + } +} + void forward_cpy_f32_to_f16(ggml::spacemit::context & ctx, ggml_tensor * op) { const ggml_tensor * src0 = op->src[0]; ggml_tensor * dst = op; @@ -5043,6 +5086,57 @@ void forward_set_rows(ggml::spacemit::context & ctx, ggml_tensor * op) { const int64_t nc = src0->ne[0]; const int64_t nr = src0->ne[1]; + + const auto disjoint_from_dst = [dst](const ggml_tensor * src) { + const uintptr_t sb = reinterpret_cast(src->data); + const uintptr_t db = reinterpret_cast(dst->data); + return sb < db ? db - sb >= ggml_nbytes(src) : sb - db >= ggml_nbytes(dst); + }; + + // Convolution rollback windows contain three adjacent F32 fields per + // channel, with the snapshot slots outside the channel/sequence planes. + // These conservative stride guards make every channel/sequence group + // disjoint even when different source rows select the same slot. Inputs + // and indices must not alias destination writes. + const size_t channel_plane = static_cast(src0->ne[2]) * 3 * sizeof(float); + if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && + nc == 3 && nr > 0 && src0->ne[2] > 0 && src0->ne[3] > 0 && + src0->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float) && + src1->ne[1] == 1 && src1->ne[2] == 1 && + dst->nb[2] == 3 * sizeof(float) && dst->nb[3] >= channel_plane && + dst->nb[1] / static_cast(src0->ne[3]) >= dst->nb[3] && + disjoint_from_dst(src0) && disjoint_from_dst(src1)) { + const int64_t channels = src0->ne[2]; + const int64_t groups = channels * src0->ne[3]; + const int64_t dg = (groups + ctx.nth - 1) / ctx.nth; + const int64_t end = MIN(dg * (ctx.ith + 1), groups); + for (int64_t group = dg * ctx.ith; group < end;) { + const int64_t seq = group / channels; + const int64_t ch0 = group % channels; + const int64_t ch1 = MIN(channels, ch0 + end - group); + // Retain source-row order for every owned channel: repeated slot + // indices therefore keep the final source row, as in the fallback. + for (int64_t row = 0; row < nr; ++row) { + const char * index_ptr = (const char *) src1->data + row * src1->nb[0]; + const int64_t idx = src1->type == GGML_TYPE_I64 + ? *(const int64_t *) index_ptr : *(const int32_t *) index_ptr; + GGML_ASSERT(idx >= 0 && idx < dst->ne[1]); + for (int64_t ch = ch0; ch < ch1;) { + const size_t vl = __riscv_vsetvl_e32m1(ch1 - ch); + const float * src = (const float *) ((const char *) src0->data + + row * src0->nb[1] + ch * src0->nb[2] + seq * src0->nb[3]); + float * out = (float *) ((char *) dst->data + + idx * dst->nb[1] + ch * dst->nb[2] + seq * dst->nb[3]); + const vfloat32m1x3_t values = __riscv_vlsseg3e32_v_f32m1x3(src, src0->nb[2], vl); + __riscv_vsseg3e32_v_f32m1x3(out, values, vl); + ch += vl; + } + } + group += ch1 - ch0; + } + return; + } + const int64_t dc = (nc + ctx.nth - 1) / ctx.nth; const int64_t c0 = dc * ctx.ith; const int64_t c1 = MIN(c0 + dc, nc); @@ -5248,6 +5342,104 @@ void forward_rms_norm_mul_f32(ggml::spacemit::context & ctx, const ggml_tensor * // ssm_conv fused with its concat(conv_states, transpose(qkv)) input: reads the conv state (d_conv - 1 // columns per channel) and the untransposed qkv rows directly, so every token is one contiguous load across // channels instead of a strided gather. Same arithmetic order as forward_ssm_conv_f32 (bitwise identical). +void forward_ssm_conv_persistent(ggml::spacemit::context & ctx, ggml_tensor * ssm, + ggml_tensor * copy, ggml_tensor * gather) { + ggml_tensor * cat = ssm->src[0]; + const ggml_tensor * q = cat->src[1]; + const ggml_tensor * w = ssm->src[1]; + const ggml_tensor * cache = gather->src[0]; + const ggml_tensor * index = gather->src[1]; + const int64_t nr = ssm->ne[0]; + const size_t bytes = 3 * nr * sizeof(float); + const int32_t row = index->data ? *(const int32_t *) index->data : -1; + const float * old = row >= 0 && row < cache->ne[1] && cache->data ? + (const float *) ((const char *) cache->data + row * cache->nb[1]) : nullptr; + bool direct = old && copy->data && q->data && w->data && ssm->data && + ggml_is_contiguous(copy) && ggml_nbytes(copy) == bytes && q->nb[1] == sizeof(float) && + w->nb[1] == 4 * sizeof(float) && + (old == copy->data || !gdn_state_ranges_overlap(old, bytes, copy->data, bytes)); + for (const ggml_tensor * t : {q, w, index, static_cast(ssm)}) { + direct = direct && t->data && + !gdn_state_ranges_overlap(copy->data, bytes, t->data, ggml_nbytes(t)) && + !gdn_state_ranges_overlap(old, bytes, t->data, ggml_nbytes(t)); + } + if (!direct) { + // Reconstruct the full original CONCAT before CPY. The gather output and both + // CONCAT inputs remain allocated through SSM for this conservative path. + forward_get_rows(ctx, gather); + ctx.sync(); + if (!forward_concat_dim0_transposed_f32(ctx, cat, 0)) { + GGML_ABORT("ssm persistent fallback: unsupported concat"); + } + ctx.sync(); + forward_cpy_strided_f32(ctx, copy); + ctx.sync(); + if (!forward_ssm_conv_f32(ctx, ssm)) { + GGML_ABORT("ssm persistent fallback: unsupported convolution"); + } + return; + } + const int64_t dr = (nr + (int64_t) ctx.nth - 1) / (int64_t) ctx.nth; + const int64_t c0 = dr * (int64_t) ctx.ith; + const int64_t c1 = std::min(c0 + dr, nr); + for (int64_t c = c0; c < c1;) { + const size_t vl = __riscv_vsetvl_e32m2(c1 - c); + vfloat32m2x3_t state = __riscv_vlseg3e32_v_f32m2x3(old + 3 * c, vl); + const vfloat32m2_t x0 = __riscv_vget_v_f32m2x3_f32m2(state, 0); + const vfloat32m2_t x1 = __riscv_vget_v_f32m2x3_f32m2(state, 1); + const vfloat32m2_t x2 = __riscv_vget_v_f32m2x3_f32m2(state, 2); + const vfloat32m2_t x3 = __riscv_vle32_v_f32m2((const float *) q->data + c, vl); + const vfloat32m2x4_t weights = __riscv_vlseg4e32_v_f32m2x4((const float *) w->data + 4 * c, vl); + vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(weights, 0), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(weights, 1), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(weights, 2), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(weights, 3), vl); + __riscv_vse32_v_f32m2((float *) ssm->data + c, acc, vl); + // All three old values have reached registers before updating this channel. + state = __riscv_vset_v_f32m2_f32m2x3(state, 0, x1); + state = __riscv_vset_v_f32m2_f32m2x3(state, 1, x2); + state = __riscv_vset_v_f32m2_f32m2x3(state, 2, x3); + __riscv_vsseg3e32_v_f32m2x3((float *) copy->data + 3 * c, state, vl); + c += vl; + } +} + +// The old gathered state remains live until SSM; only its persistent destination changes here. +void forward_ssm_conv_state_store(ggml::spacemit::context & ctx, ggml_tensor * ssm, ggml_tensor * copy) { + ggml_tensor * cat = ssm->src[0]; + const ggml_tensor * st = cat->src[0]; + const ggml_tensor * q = cat->src[1]; + const int64_t nr = cat->ne[1]; + const size_t state_bytes = 3 * nr * sizeof(float); + const bool direct = st->nb[1] == 3 * sizeof(float) && q->nb[1] == sizeof(float) && + ggml_is_contiguous(copy) && ggml_nbytes(copy) == state_bytes && copy->data && st->data && q->data && + !gdn_state_ranges_overlap(copy->data, state_bytes, st->data, ggml_nbytes(st)) && + !gdn_state_ranges_overlap(copy->data, state_bytes, q->data, ggml_nbytes(q)); + if (!direct) { + if (!forward_concat_dim0_transposed_f32(ctx, cat, 1)) { + GGML_ABORT("fused ssm state store: unsupported concat"); + } + ctx.sync(); + forward_cpy_strided_f32(ctx, copy); + return; + } + const int64_t dr = (nr + (int64_t) ctx.nth - 1) / (int64_t) ctx.nth; + const int64_t c0 = dr * (int64_t) ctx.ith; + const int64_t c1 = std::min(c0 + dr, nr); + for (int64_t c = c0; c < c1;) { + const size_t vl = __riscv_vsetvl_e32m2(c1 - c); + vfloat32m2x3_t state = __riscv_vlseg3e32_v_f32m2x3((const float *) st->data + 3 * c, vl); + const vfloat32m2_t s1 = __riscv_vget_v_f32m2x3_f32m2(state, 1); + const vfloat32m2_t s2 = __riscv_vget_v_f32m2x3_f32m2(state, 2); + const vfloat32m2_t x = __riscv_vle32_v_f32m2((const float *) q->data + c, vl); + state = __riscv_vset_v_f32m2_f32m2x3(state, 0, s1); + state = __riscv_vset_v_f32m2_f32m2x3(state, 1, s2); + state = __riscv_vset_v_f32m2_f32m2x3(state, 2, x); + __riscv_vsseg3e32_v_f32m2x3((float *) copy->data + 3 * c, state, vl); + c += vl; + } +} + bool forward_ssm_conv_concat_f32(ggml::spacemit::context & ctx, ggml_tensor * dst) { const ggml_tensor * cat = dst->src[0]; // concat {d_conv - 1 + n_t, d_inner, n_s} const ggml_tensor * st = cat->src[0]; // conv states {d_conv - 1, d_inner, n_s} @@ -5275,6 +5467,31 @@ bool forward_ssm_conv_concat_f32(ggml::spacemit::context & ctx, ggml_tensor * ds const int64_t ir0 = dr * (int64_t) ctx.ith; const int64_t ir1 = std::min(ir0 + dr, nr); + if (n_t == 1 && ss == 3 * sizeof(float) && ws == 4 * sizeof(float)) { + for (int64_t i3 = 0; i3 < n_s; ++i3) { + for (int64_t c = ir0; c < ir1;) { + const size_t vl = __riscv_vsetvl_e32m2(ir1 - c); + const float * wp = (const float *) ((const char *) src1->data + c * ws); + const vfloat32m2x4_t w = __riscv_vlseg4e32_v_f32m2x4(wp, vl); + const float * sp = (const float *) ((const char *) st->data + c * ss + i3 * st->nb[2]); + const vfloat32m2x3_t sx = __riscv_vlseg3e32_v_f32m2x3(sp, vl); + const vfloat32m2_t x0 = __riscv_vget_v_f32m2x3_f32m2(sx, 0); + const vfloat32m2_t x1 = __riscv_vget_v_f32m2x3_f32m2(sx, 1); + const vfloat32m2_t x2 = __riscv_vget_v_f32m2x3_f32m2(sx, 2); + const float * qp = (const float *) ((const char *) qk->data + c * sizeof(float) + i3 * qk->nb[2]); + const vfloat32m2_t x3 = __riscv_vle32_v_f32m2(qp, vl); + vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(w, 0), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(w, 1), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(w, 2), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(w, 3), vl); + float * yp = (float *) ((char *) dst->data + c * sizeof(float) + i3 * dst->nb[2]); + __riscv_vse32_v_f32m2(yp, acc, vl); + c += vl; + } + } + return true; + } + for (int64_t i3 = 0; i3 < n_s; ++i3) { for (int64_t c = ir0; c < ir1;) { const size_t vl = __riscv_vsetvl_e32m4(ir1 - c); @@ -5336,6 +5553,52 @@ bool forward_concat_dim0_transposed_f32(ggml::spacemit::context & ctx, ggml_tens const int64_t c0 = dc * (int64_t) ctx.ith; const int64_t c1 = std::min(c0 + dc, ne1); + // The existing channel-vectorized copy scatters each token over many dst + // cache lines. Instead transpose small channel/token tiles: a vector loads + // tokens with src1's token stride and writes them contiguously into one dst + // channel. Adjacent channels reuse the same source cache lines before the + // next token tile. A 32x32 tile copies 4 KiB of values from each side. + // This also honors the partial materialization used by concat/SSM fusion. + if (ne10 >= 64 && ne1 >= 32 && nb10 >= (size_t) ne1 * sizeof(float) && + nb10 % sizeof(float) == 0 && nb01 >= (size_t) ne00 * sizeof(float) && + nb1 >= (size_t) ne0 * sizeof(float)) { + constexpr int64_t channel_tile = 32; + constexpr int64_t token_tile = 32; + const int64_t first_state = std::max(0, col0); + const int64_t first_token = std::max(0, col0 - ne00); + for (int64_t i3 = 0; i3 < ne3; ++i3) { + for (int64_t i2 = 0; i2 < ne2; ++i2) { + const char * s0 = (const char *) src0->data + i2 * nb02 + i3 * nb03; + const char * s1 = (const char *) src1->data + i2 * nb12 + i3 * nb13; + char * d = (char *) op->data + i2 * nb2 + i3 * nb3; + if (first_state < ne00) { + for (int64_t c = c0; c < c1; ++c) { + memcpy1d(d + c * nb1 + first_state * sizeof(float), + s0 + c * nb01 + first_state * sizeof(float), + (ne00 - first_state) * sizeof(float)); + } + } + for (int64_t cb = c0; cb < c1; cb += channel_tile) { + const int64_t ce = std::min(cb + channel_tile, c1); + for (int64_t tb = first_token; tb < ne10; tb += token_tile) { + const int64_t te = std::min(tb + token_tile, ne10); + for (int64_t c = cb; c < ce; ++c) { + for (int64_t t = tb; t < te;) { + const size_t vl = __riscv_vsetvl_e32m1(te - t); + const vfloat32m1_t values = __riscv_vlse32_v_f32m1( + (const float *) (s1 + c * nb11 + t * nb10), nb10, vl); + __riscv_vse32_v_f32m1( + (float *) (d + c * nb1 + (ne00 + t) * sizeof(float)), values, vl); + t += vl; + } + } + } + } + } + } + return true; + } + for (int64_t i3 = 0; i3 < ne3; i3++) { for (int64_t i2 = 0; i2 < ne2; i2++) { const char * s0 = (const char *) src0->data + i2 * nb02 + i3 * nb03; @@ -5383,6 +5646,30 @@ bool forward_ssm_conv_f32(ggml::spacemit::context & ctx, ggml_tensor * dst) { const int64_t ir0 = dr * (int64_t) ctx.ith; const int64_t ir1 = std::min(ir0 + dr, nr); + if (n_t == 1 && xs == 4 * sizeof(float) && ws == 4 * sizeof(float)) { + for (int64_t i3 = 0; i3 < n_s; ++i3) { + for (int64_t c = ir0; c < ir1;) { + const size_t vl = __riscv_vsetvl_e32m2(ir1 - c); + const float * wp = (const float *) ((const char *) src1->data + c * ws); + const vfloat32m2x4_t w = __riscv_vlseg4e32_v_f32m2x4(wp, vl); + const float * xp = (const float *) ((const char *) src0->data + c * xs + i3 * src0->nb[2]); + const vfloat32m2x4_t sx = __riscv_vlseg4e32_v_f32m2x4(xp, vl); + const vfloat32m2_t x0 = __riscv_vget_v_f32m2x4_f32m2(sx, 0); + const vfloat32m2_t x1 = __riscv_vget_v_f32m2x4_f32m2(sx, 1); + const vfloat32m2_t x2 = __riscv_vget_v_f32m2x4_f32m2(sx, 2); + const vfloat32m2_t x3 = __riscv_vget_v_f32m2x4_f32m2(sx, 3); + vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(w, 0), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(w, 1), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(w, 2), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(w, 3), vl); + float * yp = (float *) ((char *) dst->data + c * sizeof(float) + i3 * dst->nb[2]); + __riscv_vse32_v_f32m2(yp, acc, vl); + c += vl; + } + } + return true; + } + for (int64_t i3 = 0; i3 < n_s; ++i3) { for (int64_t c = ir0; c < ir1;) { const size_t vl = __riscv_vsetvl_e32m4(ir1 - c); diff --git a/ggml/src/ggml-spacemit/rvv_kernels.h b/ggml/src/ggml-spacemit/rvv_kernels.h index 2d8a757e94df..da5152635b54 100644 --- a/ggml/src/ggml-spacemit/rvv_kernels.h +++ b/ggml/src/ggml-spacemit/rvv_kernels.h @@ -108,17 +108,22 @@ bool forward_concat_dim0_transposed_f32(ggml::spacemit::context & ctx, ggml_tens bool forward_ssm_conv_f32(ggml::spacemit::context & ctx, ggml_tensor * dst); // ssm_conv reading its concat(conv_states, transpose(qkv)) inputs directly (fused conv) bool forward_ssm_conv_concat_f32(ggml::spacemit::context & ctx, ggml_tensor * dst); +void forward_ssm_conv_persistent(ggml::spacemit::context & ctx, ggml_tensor * ssm, ggml_tensor * copy, + ggml_tensor * gather); +void forward_ssm_conv_state_store(ggml::spacemit::context & ctx, ggml_tensor * ssm, ggml_tensor * copy); // RMS_NORM followed by MUL with a weight row, written to the MUL's dst void forward_rms_norm_mul_f32(ggml::spacemit::context & ctx, const ggml_tensor * rms, ggml_tensor * mul); template void forward_binary(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_scale_f32(ggml::spacemit::context & ctx, ggml_tensor * op); +void forward_arange_f32(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_cpy_strided_f32(ggml::spacemit::context & ctx, ggml_tensor * op); // F32 -> F32 with contiguous rows (nb[0] == sizeof(float)) but arbitrary outer strides on both sides; // used by the GDN rollback-snapshot copies into the row-strided cache_s views void forward_cpy_f32_row_strided(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_cpy_f32_to_f16(ggml::spacemit::context & ctx, ggml_tensor * op); +void forward_cpy_f32_to_i32(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_cpy_f16_to_f32(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_unary_tanh_f32(ggml::spacemit::context & ctx, ggml_tensor * op); void forward_unary_gelu_f32(ggml::spacemit::context & ctx, ggml_tensor * op); diff --git a/ggml/src/ggml-spacemit/spacemit-opnode.h b/ggml/src/ggml-spacemit/spacemit-opnode.h index b512349c4cf5..d59917ca5b9b 100644 --- a/ggml/src/ggml-spacemit/spacemit-opnode.h +++ b/ggml/src/ggml-spacemit/spacemit-opnode.h @@ -21,6 +21,7 @@ enum spacemit_op_code { SPACEMIT_OP_RMS_NORM, SPACEMIT_OP_RMS_NORM_MUL, SPACEMIT_OP_CONCAT_STATE, // concat writing only the trailing columns (fused with a later SSM_CONV) + SPACEMIT_OP_SSM_CONV_STATE_STORE, SPACEMIT_OP_SSM_CONV_CONCAT, // ssm_conv reading the concat inputs directly (the concat was partial) SPACEMIT_OP_ADD, SPACEMIT_OP_UNARY_SILU, @@ -32,6 +33,7 @@ enum spacemit_op_code { SPACEMIT_OP_PERMUTE, SPACEMIT_OP_TRANSPOSE, SPACEMIT_OP_NONE, + SPACEMIT_OP_SSM_CONV_PERSISTENT, }; #define SPACEMIT_OP_MAX_KERN_PARAMS 32 diff --git a/ggml/src/ggml-spacemit/spacemit-session.h b/ggml/src/ggml-spacemit/spacemit-session.h index 88662cf4d357..d2dfe279410d 100644 --- a/ggml/src/ggml-spacemit/spacemit-session.h +++ b/ggml/src/ggml-spacemit/spacemit-session.h @@ -5,6 +5,7 @@ #include "spacemit-context.h" #include +#include #include #include #include @@ -27,10 +28,12 @@ struct spacemit_session { size_t workspace_size = 0; std::vector contexts; - struct { + struct graph_cache_entry { uint64_t uid = 0; std::vector nodes; - } cached_graph; + } uncached_graph; + std::array cached_graphs; + size_t next_graph_cache = 0; spacemit_session() = default; ~spacemit_session(); From 1c13717178f41b5f690589ce900889953ce5fda0 Mon Sep 17 00:00:00 2001 From: co-seven Date: Mon, 30 Nov 2026 14:04:56 +0000 Subject: [PATCH 2/2] ggml-spacemit: plan SSM fusion with split export information Assisted-by: Codex --- ggml/src/ggml-backend-impl.h | 4 + ggml/src/ggml-backend.cpp | 23 ++++ ggml/src/ggml-spacemit/ggml-spacemit.cpp | 138 +++++++++-------------- ggml/src/ggml-spacemit/rvv_kernels.cpp | 24 ++-- 4 files changed, 94 insertions(+), 95 deletions(-) diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index 545880b068c7..57120627b194 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -125,6 +125,10 @@ extern "C" { // can be called multiple times for the same tensor: the longest lifetime applies void (*add_alloc_dep)(void * user_data, struct ggml_tensor * tensor, struct ggml_tensor * until); void * user_data; + // True for a tensor whose storage is read by another scheduler split. + // This includes reads through views and directly shared buffers. + bool (*is_split_export)(const void * exports, const struct ggml_tensor * tensor); + const void * exports; }; struct ggml_backend_i { diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 2e2f9c036560..c39df7910197 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #ifdef __APPLE__ @@ -1712,6 +1713,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra } // pass 5: split graph, find tensors that need to be copied + std::unordered_map producer_splits; + std::unordered_set split_exports; { int i_split = 0; struct ggml_backend_sched_split * split = &sched->splits[0]; @@ -1780,6 +1783,9 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra cur_backend_id = node_backend_id; } split_has_nodes = true; + if (node->view_src == nullptr && (node->flags & GGML_TENSOR_FLAG_COMPUTE)) { + producer_splits.emplace(node, i_split); + } // find inputs that are not on the same backend for (int j = 0; j < GGML_MAX_SRC; j++) { @@ -1789,6 +1795,18 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra } size_t src_id = hash_id(src); + // Keep the original storage identity before a copied input + // replaces this edge. Compatible buffers also cross splits. + if (node->flags & GGML_TENSOR_FLAG_COMPUTE) { + const ggml_tensor * root = src; + while (root->view_src) { + root = root->view_src; + } + const auto producer = producer_splits.find(root); + if (producer != producer_splits.end() && producer->second != i_split) { + split_exports.insert(root); + } + } const int src_backend_id = sched->hv_tensor_backend_ids[src_id]; GGML_ASSERT(src_backend_id != -1); // all inputs should be assigned by now @@ -1894,6 +1912,11 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra } }, /* .user_data = */ &alloc_deps, + /* .is_split_export = */ [](const void * exports, const ggml_tensor * tensor) { + const auto & roots = *static_cast *>(exports); + return roots.count(tensor) != 0; + }, + /* .exports = */ &split_exports, }; for (int i = 0; i < sched->n_splits; i++) { diff --git a/ggml/src/ggml-spacemit/ggml-spacemit.cpp b/ggml/src/ggml-spacemit/ggml-spacemit.cpp index de468fd42a6b..ee832bbb72a5 100644 --- a/ggml/src/ggml-spacemit/ggml-spacemit.cpp +++ b/ggml/src/ggml-spacemit/ggml-spacemit.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #define GGML_COMMON_IMPL_CPP @@ -187,10 +187,7 @@ static spacemit_op_code op_remap_to_spacemit(const ggml_tensor * t) { // Fused opnodes are dispatched by ggml_spacemit_compute_opnode through the // tensor traits of their primary node (compute_forward_fused). // -// try_fuse_node contains ALL fusion matching and emission: Pattern 2 consumes -// two nodes at different positions (the concat now, the ssm_conv when the loop -// reaches it — opnode list order is execution order, so the halves keep their -// original node positions); `emitted` carries the pairing across the gap. +// SSM fusion is planned once when building the opnode list. // RMS_NORM followed by MUL (rms, weight) that can run as one fused RVV kernel. static bool rms_norm_mul_fusable(const ggml_tensor * rms, const ggml_tensor * mul) { @@ -591,46 +588,49 @@ static ggml_tensor * ssm_conv_persistent_match(const ggml_cgraph * graph, int ci return copy; } -static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vector & nodes, - std::unordered_set & emitted) { - ggml_tensor * n = graph->nodes[i]; +// A null node in this plan marks an operation consumed by the fusion. Keep +// the convolution at its original position so allocator lifetimes still hold. +static std::unordered_map build_ssm_fusion_plan(const ggml_cgraph * graph) { + std::unordered_map plan; + for (int ci = 0; ci < graph->n_nodes; ++ci) { + ggml_tensor * cat = graph->nodes[ci]; + if (cat->op != GGML_OP_CONCAT || !op_is_compute(cat)) { + continue; + } + ggml_tensor * ssm = nullptr; + int si = -1; + int64_t col0 = 0; + if (!ssm_conv_concat_fusable(graph, ci, true, &ssm, &si, &col0)) { + continue; + } - // Second half of Pattern 2, arriving here: an ssm_conv paired with an earlier concat. - // Emitted at its own position — opnode list order is execution order, and the graph - // allocator planned the ssm_conv output buffer on the original node order (see Pattern 2). - if (emitted.count(n)) { - if (ggml_get_op_params_i32(n, SSM_PERSISTENT_PARAM_INPUTS_KEPT) == 1) { - for (int ci = 0; ci < i; ++ci) { - if (graph->nodes[ci] != n->src[0]) { - continue; - } - ggml_tensor * gather = nullptr; - if (ggml_tensor * copy = ssm_conv_persistent_match(graph, ci, i, n, true, &gather)) { - nodes.emplace_back(n, std::vector{}, SPACEMIT_OP_SSM_CONV_PERSISTENT, - std::vector{copy, gather}); - return true; - } - } + int pi = -1; + ggml_tensor * gather = nullptr; + if (ggml_tensor * copy = ssm_conv_persistent_match(graph, ci, si, ssm, true, &gather, &pi)) { + const int gi = std::find(graph->nodes, graph->nodes + ci, gather) - graph->nodes; + plan.try_emplace(gi); + plan.try_emplace(ci); + plan.try_emplace(pi); + plan.try_emplace(si, ssm, std::vector{}, SPACEMIT_OP_SSM_CONV_PERSISTENT, + std::vector{copy, gather}); + continue; } - nodes.emplace_back(n, std::vector{}, SPACEMIT_OP_SSM_CONV_CONCAT); - return true; - } - if (n->op == GGML_OP_GET_ROWS) { - for (int ci = i + 1; ci < graph->n_nodes; ++ci) { - if (graph->nodes[ci]->op != GGML_OP_CONCAT || - tensor_storage_root(graph->nodes[ci]->src[0]) != n) { - continue; - } - ggml_tensor * ssm = nullptr; - int si = -1; - int64_t col0 = 0; - ggml_tensor * gather = nullptr; - if (ssm_conv_concat_fusable(graph, ci, true, &ssm, &si, &col0) && - ssm_conv_persistent_match(graph, ci, si, ssm, true, &gather) && gather == n) { - return true; // no gather opnode: materialize only in the SSM runtime fallback - } + + if (ggml_tensor * copy = ssm_conv_state_store_match(graph, ci, si, ssm, &pi)) { + plan.try_emplace(ci); + plan.try_emplace(pi, copy, std::vector{}, SPACEMIT_OP_SSM_CONV_STATE_STORE, + std::vector{ssm}); + } else { + auto & node = plan.try_emplace(ci, cat, std::vector{}, SPACEMIT_OP_CONCAT_STATE).first->second; + node.kernel_params[0] = (int32_t) col0; } + plan.try_emplace(si, ssm, std::vector{}, SPACEMIT_OP_SSM_CONV_CONCAT); } + return plan; +} + +static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vector & nodes) { + ggml_tensor * n = graph->nodes[i]; // Find the next compute node, skipping empty (NONE) nodes. test-backend-ops // inserts NONE sentinels between ops for out-of-bounds detection, which must @@ -657,41 +657,6 @@ static bool try_fuse_node(const ggml_cgraph * graph, int & i, std::vectorop == GGML_OP_CONCAT) { - ggml_tensor * ssm = nullptr; - int ssm_idx = -1; - int64_t col0 = 0; - if (ssm_conv_concat_fusable(graph, i, true, &ssm, &ssm_idx, &col0)) { - int copy_index = -1; - if (ssm_conv_persistent_match(graph, i, ssm_idx, ssm, true, nullptr, ©_index)) { - i = copy_index; - emitted.insert(ssm); - return true; - } - if (ggml_tensor * copy = ssm_conv_state_store_match(graph, i, ssm_idx, ssm, ©_index)) { - nodes.emplace_back(copy, std::vector{}, SPACEMIT_OP_SSM_CONV_STATE_STORE, - std::vector{ssm}); - i = copy_index; - emitted.insert(ssm); - return true; - } - spacemit_opnode cat(n, {}, SPACEMIT_OP_CONCAT_STATE); - cat.kernel_params[0] = (int32_t) col0; - nodes.push_back(std::move(cat)); - // the ssm_conv half is emitted by try_fuse_node when the loop reaches its own - // node position (see the top of this function) — never here at the concat position - emitted.insert(ssm); - return true; - } - } - return false; } @@ -916,15 +881,20 @@ static ggml_status ggml_backend_spacemit_graph_compute(ggml_backend_t backend, g cached->uid = 0; cached->nodes.clear(); cached->nodes.reserve(graph->n_nodes); - std::unordered_set emitted; // nodes already emitted by try_fuse_node + auto ssm_plan = build_ssm_fusion_plan(graph); for (int i = 0; i < graph->n_nodes; ++i) { ggml_tensor * n = graph->nodes[i]; if (!op_is_compute(n)) { continue; } - // On a match, try_fuse_node pushes the fused opnodes and advances i past - // the nodes it consumed; otherwise the node is appended as a single op. - if (try_fuse_node(graph, i, cached->nodes, emitted)) { + const auto ssm = ssm_plan.find(i); + if (ssm != ssm_plan.end()) { + if (ssm->second.node) { + cached->nodes.push_back(std::move(ssm->second)); + } + continue; + } + if (try_fuse_node(graph, i, cached->nodes)) { continue; } cached->nodes.emplace_back(n); @@ -1039,7 +1009,7 @@ static void ggml_backend_spacemit_graph_optimize(ggml_backend_t backend, ggml_cg ggml_set_op_params_i32(graph->nodes[i], SSM_PERSISTENT_PARAM_INPUTS_KEPT, 0); } } - if (params == nullptr || params->add_alloc_dep == nullptr) { + if (params == nullptr || params->add_alloc_dep == nullptr || params->is_split_export == nullptr) { return; } for (int i = 0; i < graph->n_nodes; ++i) { @@ -1047,12 +1017,14 @@ static void ggml_backend_spacemit_graph_optimize(ggml_backend_t backend, ggml_cg ggml_tensor * ssm = nullptr; int ssm_idx = -1; int64_t col0 = 0; - if (c->op == GGML_OP_CONCAT && ssm_conv_concat_fusable(graph, i, false, &ssm, &ssm_idx, &col0)) { + if (c->op == GGML_OP_CONCAT && !params->is_split_export(params->exports, c) && + ssm_conv_concat_fusable(graph, i, false, &ssm, &ssm_idx, &col0)) { params->add_alloc_dep(params->user_data, c->src[0], ssm); params->add_alloc_dep(params->user_data, c->src[1], ssm); ggml_set_op_params_i32(ssm, SSM_CONV_PARAM_INPUTS_KEPT, 1); ggml_tensor * gather = nullptr; - if (ssm_conv_persistent_match(graph, i, ssm_idx, ssm, false, &gather)) { + if (ssm_conv_persistent_match(graph, i, ssm_idx, ssm, false, &gather) && + !params->is_split_export(params->exports, gather)) { params->add_alloc_dep(params->user_data, gather->src[0], ssm); params->add_alloc_dep(params->user_data, gather->src[1], ssm); ggml_set_op_params_i32(ssm, SSM_PERSISTENT_PARAM_INPUTS_KEPT, 1); diff --git a/ggml/src/ggml-spacemit/rvv_kernels.cpp b/ggml/src/ggml-spacemit/rvv_kernels.cpp index 6e65cc9ad675..3bff2ef7ca39 100644 --- a/ggml/src/ggml-spacemit/rvv_kernels.cpp +++ b/ggml/src/ggml-spacemit/rvv_kernels.cpp @@ -5339,6 +5339,15 @@ void forward_rms_norm_mul_f32(ggml::spacemit::context & ctx, const ggml_tensor * } } +static inline vfloat32m2_t ssm_conv_four_taps(vfloat32m2_t x0, vfloat32m2_t x1, vfloat32m2_t x2, + vfloat32m2_t x3, vfloat32m2x4_t weights, size_t vl) { + vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(weights, 0), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(weights, 1), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(weights, 2), vl); + acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(weights, 3), vl); + return acc; +} + // ssm_conv fused with its concat(conv_states, transpose(qkv)) input: reads the conv state (d_conv - 1 // columns per channel) and the untransposed qkv rows directly, so every token is one contiguous load across // channels instead of a strided gather. Same arithmetic order as forward_ssm_conv_f32 (bitwise identical). @@ -5390,10 +5399,7 @@ void forward_ssm_conv_persistent(ggml::spacemit::context & ctx, ggml_tensor * ss const vfloat32m2_t x2 = __riscv_vget_v_f32m2x3_f32m2(state, 2); const vfloat32m2_t x3 = __riscv_vle32_v_f32m2((const float *) q->data + c, vl); const vfloat32m2x4_t weights = __riscv_vlseg4e32_v_f32m2x4((const float *) w->data + 4 * c, vl); - vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(weights, 0), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(weights, 1), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(weights, 2), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(weights, 3), vl); + const auto acc = ssm_conv_four_taps(x0, x1, x2, x3, weights, vl); __riscv_vse32_v_f32m2((float *) ssm->data + c, acc, vl); // All three old values have reached registers before updating this channel. state = __riscv_vset_v_f32m2_f32m2x3(state, 0, x1); @@ -5480,10 +5486,7 @@ bool forward_ssm_conv_concat_f32(ggml::spacemit::context & ctx, ggml_tensor * ds const vfloat32m2_t x2 = __riscv_vget_v_f32m2x3_f32m2(sx, 2); const float * qp = (const float *) ((const char *) qk->data + c * sizeof(float) + i3 * qk->nb[2]); const vfloat32m2_t x3 = __riscv_vle32_v_f32m2(qp, vl); - vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(w, 0), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(w, 1), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(w, 2), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(w, 3), vl); + const auto acc = ssm_conv_four_taps(x0, x1, x2, x3, w, vl); float * yp = (float *) ((char *) dst->data + c * sizeof(float) + i3 * dst->nb[2]); __riscv_vse32_v_f32m2(yp, acc, vl); c += vl; @@ -5658,10 +5661,7 @@ bool forward_ssm_conv_f32(ggml::spacemit::context & ctx, ggml_tensor * dst) { const vfloat32m2_t x1 = __riscv_vget_v_f32m2x4_f32m2(sx, 1); const vfloat32m2_t x2 = __riscv_vget_v_f32m2x4_f32m2(sx, 2); const vfloat32m2_t x3 = __riscv_vget_v_f32m2x4_f32m2(sx, 3); - vfloat32m2_t acc = __riscv_vfmul_vv_f32m2(x0, __riscv_vget_v_f32m2x4_f32m2(w, 0), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x1, __riscv_vget_v_f32m2x4_f32m2(w, 1), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x2, __riscv_vget_v_f32m2x4_f32m2(w, 2), vl); - acc = __riscv_vfmacc_vv_f32m2(acc, x3, __riscv_vget_v_f32m2x4_f32m2(w, 3), vl); + const auto acc = ssm_conv_four_taps(x0, x1, x2, x3, w, vl); float * yp = (float *) ((char *) dst->data + c * sizeof(float) + i3 * dst->nb[2]); __riscv_vse32_v_f32m2(yp, acc, vl); c += vl;