diff --git a/ggml/src/ggml-spacemit/ime.cpp b/ggml/src/ggml-spacemit/ime.cpp index 493c989d4ccf..9050bdd5bce9 100644 --- a/ggml/src/ggml-spacemit/ime.cpp +++ b/ggml/src/ggml-spacemit/ime.cpp @@ -1277,6 +1277,12 @@ template class tensor_ } }; +#if defined(RISCV64_SPACEMIT_IME2) +static bool flash_attn_ext_f16_tiled_use_ime2(int64_t dk, int64_t dv) { + return global_spine_env_info.use_ime2 && dk % 8 == 0 && dv % 32 == 0; +} +#endif + class tensor_traits_common : public ggml::spacemit::tensor_traits_base { bool work_size(int n_threads, const ggml_tensor * op, size_t & size) const override { switch (op->op) { @@ -1302,11 +1308,12 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { // Tiled flash attention scratch (tile sizes defined in common.h) // Per-thread: Q_q + KQ + mask + VKQ32 + V32 + K_f32 + padding - size_t prefill = sizeof(float) * - (GGML_FA_TILE_Q * DK + 2 * GGML_FA_TILE_Q * GGML_FA_TILE_KV + GGML_FA_TILE_Q * DV + - GGML_FA_TILE_KV * DV + GGML_FA_TILE_KV * DK + - ggml::spacemit::cache_line_size_f32) * - n_tasks; + size_t prefill = spacemit_kernels::rvv::flash_attn_ext_f16_tiled_workspace_size(op, n_tasks); +#if defined(RISCV64_SPACEMIT_IME2) + if (flash_attn_ext_f16_tiled_use_ime2(DK, DV)) { + prefill = spacemit_kernels::ime2::flash_attn_ext_f16_tiled_workspace_size(op, n_tasks); + } +#endif // Decode path: n_kv_chunks = n_tasks (one chunk per thread) // Per-thread: VKQ accmulator (DV), partial M, partial S + intra-thread scratch for V, Q and VKQ @@ -1702,8 +1709,10 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { const bool supported_prec = (dst->op_params[3] == GGML_PREC_F32 || dst->op_params[3] == GGML_PREC_UNDEFINED); const bool supported_types = (q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16); - const bool supported_shape = (DK > 0 && DK <= 256 && DV > 0 && DV <= 256); - const bool supported_vlen = (__riscv_vlenb() == 128); + const bool supported_shape = (DK > 0 && DK <= 512 && DV > 0 && DV <= 512); + const size_t vlenb = __riscv_vlenb(); + const bool use_tiled = neq1 >= ggml_fa_tile_config::Q; + const bool supported_vlen = vlenb == 128 || (vlenb == 32 && use_tiled); if (!(supported_prec && supported_types && supported_shape && supported_vlen)) { return false; @@ -1716,9 +1725,6 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { const int ith = ctx.ith; const int nth = ctx.nth; - static constexpr int64_t Q_TILE_SZ = ggml_fa_tile_config::Q; - const bool use_tiled = neq1 >= Q_TILE_SZ; - // 4x chunks per thread // int nth_scaled = nth * 4; // int64_t chunk_size = (nr + nth_scaled - 1) / nth_scaled; @@ -1742,27 +1748,20 @@ class tensor_traits_common : public ggml::spacemit::tensor_traits_base { return true; } - int64_t nchunk = nth; - - // The number of elements in each chunk - const int64_t dr = (nr + nchunk - 1) / nchunk; - - // The first chunk comes from our thread_id, the rest will get auto-assigned. - int current_chunk = ith; + const int64_t dr = (nr + nth - 1) / nth; + const int64_t ir0 = dr * ith; + const int64_t ir1 = std::min(ir0 + dr, nr); - while (current_chunk < nchunk) { - const int64_t ir0 = dr * current_chunk; - const int64_t ir1 = MIN(ir0 + dr, nr); - - if (use_tiled) { - spacemit_kernels::rvv::forward_flash_attn_ext_f16_tiled_vlen1024_vf16( - ctx, dst, ir0, ir1); - } else { - spacemit_kernels::rvv::forward_flash_attn_ext_f16_one_chunk_vlen1024_vf16( - ctx, dst, ir0, ir1); + if (use_tiled) { +#if defined(RISCV64_SPACEMIT_IME2) + if (vlenb == 128 && flash_attn_ext_f16_tiled_use_ime2(DK, DV)) { + spacemit_kernels::ime2::forward_flash_attn_ext_f16_tiled_ime2(ctx, dst, ir0, ir1); + return true; } - - current_chunk += nth; +#endif + spacemit_kernels::rvv::forward_flash_attn_ext_f16_tiled_rvv(ctx, dst, ir0, ir1); + } else { + spacemit_kernels::rvv::forward_flash_attn_ext_f16_one_chunk_vlen1024_vf16(ctx, dst, ir0, ir1); } return true; @@ -1860,10 +1859,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; diff --git a/ggml/src/ggml-spacemit/ime2_kernels.cpp b/ggml/src/ggml-spacemit/ime2_kernels.cpp index 2539cfa45848..fb623203579b 100644 --- a/ggml/src/ggml-spacemit/ime2_kernels.cpp +++ b/ggml/src/ggml-spacemit/ime2_kernels.cpp @@ -1,3 +1,4 @@ +#include "common.h" #include "ggml-impl.h" #include "ggml.h" #include "ime_kernels.h" @@ -4739,7 +4740,8 @@ size_t gemm_i8i5_k32_rows(a_pack ap, } // A/B use [K/8][M16|N32][K8]; the output is row-major FP32. -void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, +template +static void gemm_kernel_f16f16f32_m16_vfwmadot_impl(size_t gemm_k, const _Float16 * b_f16_k8, _Float16 * a_f16_k8, float * c_ptr, @@ -4764,11 +4766,19 @@ void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, size_t kc_left = gemm_k / 8; // Accumulator register pairs are not row-major; add existing C only after unpacking. // The local tile also avoids writing beyond a partial-M output. - const bool via_tile = accumulate || count_m != 16; + const bool via_tile = !FA_DIRECT_ACCUMULATE && (accumulate || count_m != 16); const bool store_vs8r = count_m == 16 && count_n == 32 && ldc == 32 && !accumulate; float * out = via_tile ? tile : c_ptr; const size_t out_row_bytes = (via_tile ? size_t{ 32 } : ldc) * sizeof(float); +#define GGML_IME2_PV_ACCUMULATE_ROW(VREG) \ + "vle32.v v0, (%[out])\n\t" \ + "vfadd.vv " #VREG ", v0, " #VREG "\n\t" \ + "vse32.v " #VREG ", (%[out])\n\t" \ + "addi t1, t1, -1\n\t" \ + "beqz t1, .L_f16_store_done_%=\n\t" \ + "add %[out], %[out], %[out_stride]\n\t" + asm volatile( "vsetvli t0, zero, e32, m4, tu, mu\n\t" "vxor.vv v12, v12, v12\n\t" @@ -5089,6 +5099,26 @@ void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, "vpack.vv v26, v9, v11, 3\n\t" "vpack.vv v28, v12, v14, 3\n\t" "vpack.vv v30, v13, v15, 3\n\t" + ".if %[fa_direct_accumulate]\n\t" + "vsetvli t0, %[count_n], e32, m1, tu, mu\n\t" + "mv t1, %[count_m]\n\t" + GGML_IME2_PV_ACCUMULATE_ROW(v16) + GGML_IME2_PV_ACCUMULATE_ROW(v17) + GGML_IME2_PV_ACCUMULATE_ROW(v18) + GGML_IME2_PV_ACCUMULATE_ROW(v19) + GGML_IME2_PV_ACCUMULATE_ROW(v20) + GGML_IME2_PV_ACCUMULATE_ROW(v21) + GGML_IME2_PV_ACCUMULATE_ROW(v22) + GGML_IME2_PV_ACCUMULATE_ROW(v23) + GGML_IME2_PV_ACCUMULATE_ROW(v24) + GGML_IME2_PV_ACCUMULATE_ROW(v25) + GGML_IME2_PV_ACCUMULATE_ROW(v26) + GGML_IME2_PV_ACCUMULATE_ROW(v27) + GGML_IME2_PV_ACCUMULATE_ROW(v28) + GGML_IME2_PV_ACCUMULATE_ROW(v29) + GGML_IME2_PV_ACCUMULATE_ROW(v30) + GGML_IME2_PV_ACCUMULATE_ROW(v31) + ".else\n\t" "bnez %[store_vs8r], .L_f16_store_whole_registers_%=\n\t" "vsetvli t0, %[count_n], e32, m1, tu, mu\n\t" "vse32.v v16, (%[out])\n\t" @@ -5127,13 +5157,16 @@ void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, "vs8r.v v16, (%[out])\n\t" "addi %[out], %[out], 1024\n\t" "vs8r.v v24, (%[out])\n\t" + ".endif\n\t" ".L_f16_store_done_%=:\n\t" : [a0] "+&r"(a0), [a1] "+&r"(a1), [b0] "+&r"(b0), [b1] "+&r"(b1), [b2] "+&r"(b2), [b3] "+&r"(b3), [kc] "+&r"(kc_left), [out] "+&r"(out) - : [count_n] "r"(count_n), [out_stride] "r"(out_row_bytes), [store_vs8r] "r"(store_vs8r) + : [count_n] "r"(count_n), [out_stride] "r"(out_row_bytes), [store_vs8r] "r"(store_vs8r), + [count_m] "r"(count_m), [fa_direct_accumulate] "i"(FA_DIRECT_ACCUMULATE) : "cc", "memory", "t0", "t1", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); +#undef GGML_IME2_PV_ACCUMULATE_ROW if (via_tile) { for (size_t m = 0; m < count_m; ++m) { @@ -5144,5 +5177,429 @@ void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, } } +void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, + const _Float16 * b_f16_k8, + _Float16 * a_f16_k8, + float * c_ptr, + size_t count_m, + size_t count_n, + size_t ldc, + bool accumulate) { + gemm_kernel_f16f16f32_m16_vfwmadot_impl(gemm_k, b_f16_k8, a_f16_k8, c_ptr, + count_m, count_n, ldc, accumulate); +} + +void fa_pv_f16f16f32_m16n32_k64_accumulate(const _Float16 * b_f16_k8, + _Float16 * a_f16_k8, + float * c_ptr, + size_t count_m, + size_t ldc) { + // Add C only after unpacking, with one F32 addition per completed dot product. + // The row count prevents loads/stores beyond a partial query panel. + gemm_kernel_f16f16f32_m16_vfwmadot_impl(64, b_f16_k8, a_f16_k8, c_ptr, + count_m, 32, ldc, true); +} + +// Pack row-major F16 rows into IME2 [K/8][panel rows][8] panels. +// Callers zero the destination for padding rows before packing. +static void fa_pack_f16_k8(_Float16 * dst, const char * src, size_t row_bytes, + int rows, int depth, int panel_rows) { + if (depth >= 128) { + // Treat K8 as two 64-bit words. Strided segmented loads gather one + // complete panel at a time; the store is contiguous in the native layout. + for (int r = 0; r < rows; r += panel_rows) { + const int count = std::min(panel_rows, rows - r); + for (int k = 0; k < depth; k += 8) { + const auto x = __riscv_vlsseg2e64_v_u64m2x2( + reinterpret_cast(src + r * row_bytes + k * sizeof(_Float16)), row_bytes, count); + __riscv_vsseg2e64_v_u64m2x2( + reinterpret_cast(dst + r * depth + (k / 8) * panel_rows * 8), x, count); + } + } + return; + } + // For short rows, load contiguous words and scatter K8 pairs. This + // avoids many VL=8 F16 loads/stores without gathering a narrow panel. + const auto even = __riscv_vsll_vx_u64m1(__riscv_vid_v_u64m1(8), 1, 8); + const auto odd = __riscv_vadd_vx_u64m1(even, 1, 8); + for (int r = 0; r < rows; ++r) { + const auto * row = reinterpret_cast(src + r * row_bytes); + auto * out = dst + (r / panel_rows) * panel_rows * depth + (r % panel_rows) * 8; + for (int k = 0; k < depth; k += 64) { + const int count = std::min(64, depth - k) / 8; + const auto words = __riscv_vle64_v_u64m1(row + k / 4, count * 2); + vuint64m1x2_t packed; + packed = __riscv_vset_v_u64m1_u64m1x2(packed, 0, __riscv_vrgather_vv_u64m1(words, even, count)); + packed = __riscv_vset_v_u64m1_u64m1x2(packed, 1, __riscv_vrgather_vv_u64m1(words, odd, count)); + __riscv_vssseg2e64_v_u64m1x2(reinterpret_cast(out + k * panel_rows), + panel_rows * 8 * sizeof(_Float16), packed, count); + } + } +} + +static void fa_pack_v_f16(_Float16 * dst, const char * src_data, size_t stride, int rows, int dv) { + // PV always consumes all 64 positions; explicitly zero padding, including masked non-finite tails. + if (rows < ggml_fa_tile_config::KV) { + rvv::detail::rvv_fill_f16(dst, 0.0f, ggml_fa_tile_config::KV * dv); + } + // Eight contiguous V rows become one contiguous K8 B panel. + int tk = 0; + for (; tk + 7 < rows; tk += 8) { + const char * src = src_data + tk * stride; + for (int d = 0; d < dv; d += 32) { + vfloat16m1x8_t x; + x = __riscv_vset_v_f16m1_f16m1x8(x, 0, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 0 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 1, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 1 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 2, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 2 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 3, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 3 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 4, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 4 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 5, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 5 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 6, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 6 * stride) + d, 32)); + x = __riscv_vset_v_f16m1_f16m1x8(x, 7, __riscv_vle16_v_f16m1( + reinterpret_cast(src + 7 * stride) + d, 32)); + __riscv_vsseg8e16_v_f16m1x8(dst + (d / 32) * 32 * ggml_fa_tile_config::KV + tk * 32, x, 32); + } + } + for (; tk < rows; ++tk) { + const auto * src = reinterpret_cast( + src_data + tk * stride); + for (int d = 0; d < dv; d += 32) { + const auto x = __riscv_vle16_v_f16m1(src + d, 32); + __riscv_vsse16_v_f16m1(dst + (d / 32) * 32 * ggml_fa_tile_config::KV + (tk / 8) * 32 * 8 + tk % 8, + 8 * sizeof(_Float16), x, 32); + } + } +} + +static bool flash_attn_ext_f16_prepack_supported(const ggml_tensor * dst) { + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + // Start with one batch and matching KV heads. Outer strides may be arbitrary. + // Workspace sizing runs on the X100 host thread; VLEN is checked by + // the A100 worker dispatcher before this path executes. + return q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && + q->ne[0] == 256 && k->ne[0] == 256 && v->ne[0] == 256 && + q->ne[1] >= ggml_fa_tile_config::Q && k->ne[1] > 0 && k->ne[1] == v->ne[1] && + k->ne[2] > 0 && k->ne[2] == v->ne[2] && q->ne[2] % k->ne[2] == 0 && + q->ne[3] == 1 && k->ne[3] == 1 && v->ne[3] == 1 && + q->nb[0] == sizeof(float) && k->nb[0] == sizeof(_Float16) && v->nb[0] == sizeof(_Float16); +} + +size_t flash_attn_ext_f16_tiled_workspace_size(const ggml_tensor * dst, int nth) { + size_t size = rvv::flash_attn_ext_f16_tiled_workspace_size(dst, nth); + if (flash_attn_ext_f16_prepack_supported(dst)) { + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + constexpr size_t kt = ggml_fa_tile_config::KV; + const size_t tiles = (k->ne[1] + kt - 1) / kt; + size += sizeof(_Float16) * tiles * kt * k->ne[2] * (k->ne[0] + v->ne[0]); + } + return size; +} + +static void forward_flash_attn_ext_f16_prepack(ggml::spacemit::context & ctx, const ggml_tensor * dst) { + GGML_ASSERT(flash_attn_ext_f16_prepack_supported(dst)); + GGML_ASSERT(ctx.workspace_size >= flash_attn_ext_f16_tiled_workspace_size(dst, ctx.nth)); + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + constexpr int kt = ggml_fa_tile_config::KV; + const int64_t tiles = (k->ne[1] + kt - 1) / kt; + const int64_t tasks = tiles * k->ne[2]; + auto * packed_k = (_Float16 *) ((char *) ctx.workspace + rvv::flash_attn_ext_f16_tiled_workspace_size(dst, ctx.nth)); + auto * packed_v = packed_k + tasks * kt * k->ne[0]; + // Workers own disjoint tiles. The caller synchronizes every worker before use. + for (int64_t task = ctx.ith; task < tasks; task += ctx.nth) { + const int64_t h = task / tiles; + const int64_t row = (task % tiles) * kt; + const int rows = std::min(kt, k->ne[1] - row); + const auto * ks = (const _Float16 *) ((const char *) k->data + h * k->nb[2] + row * k->nb[1]); + const char * vs = (const char *) v->data + h * v->nb[2] + row * v->nb[1]; + if (rows < kt) { + rvv::detail::rvv_fill_f16(packed_k + task * kt * k->ne[0], 0.0f, kt * k->ne[0]); + } + fa_pack_f16_k8(packed_k + task * kt * k->ne[0], (const char *) ks, k->nb[1], rows, k->ne[0], 32); + fa_pack_v_f16(packed_v + task * kt * v->ne[0], vs, v->nb[1], rows, v->ne[0]); + } +} + +void forward_flash_attn_ext_f16_tiled_ime2(ggml::spacemit::context & ctx, + ggml_tensor * dst, + int ir0, + int ir1) { + using namespace rvv::detail; + + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + + GGML_TENSOR_LOCALS(int64_t, neq, q, ne) + GGML_TENSOR_LOCALS(size_t, nbq, q, nb) + GGML_TENSOR_LOCALS(int64_t, nek, k, ne) + GGML_TENSOR_LOCALS(size_t, nbk, k, nb) + GGML_TENSOR_LOCALS(int64_t, nev, v, ne) + GGML_TENSOR_LOCALS(size_t, nbv, v, nb) + GGML_TENSOR_LOCALS(int64_t, ne, dst, ne) + GGML_TENSOR_LOCALS(size_t, nb, dst, nb) + + const int64_t DK = nek0; + const int64_t DV = nev0; + const int64_t N = neq1; + + GGML_ASSERT(DK > 0 && DK <= 512 && DV > 0 && DV <= 512); + + GGML_ASSERT(ne0 == DV); + GGML_ASSERT(ne2 == N); + + // input tensor rows must be contiguous + GGML_ASSERT(nbq0 == ggml_type_size(q->type)); + GGML_ASSERT(nbk0 == ggml_type_size(k->type)); + GGML_ASSERT(nbv0 == ggml_type_size(v->type)); + + GGML_ASSERT(neq0 == DK); + GGML_ASSERT(nek0 == DK); + GGML_ASSERT(nev0 == DV); + + GGML_ASSERT(neq1 == N); + + // dst cannot be transposed or permuted + GGML_ASSERT(nb0 == sizeof(float)); + GGML_ASSERT(nb0 <= nb1); + GGML_ASSERT(nb1 <= nb2); + GGML_ASSERT(nb2 <= nb3); + + GGML_ASSERT(q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16); + GGML_ASSERT(__riscv_vlenb() == 128 && DK % 8 == 0 && DV % 32 == 0); + + // broadcast factors + const int64_t rk2 = neq2 / nek2; + const int64_t rk3 = neq3 / nek3; + + const int64_t rv2 = neq2 / nev2; + const int64_t rv3 = neq3 / nev3; + + float * param_list = (float *) dst->op_params; + float scale = param_list[0]; + float max_bias = param_list[1]; + float logit_softcap = param_list[2]; + + if (logit_softcap != 0) { + scale /= logit_softcap; + } + + const uint32_t n_head = neq2; + const uint32_t n_head_log2 = 1u << (uint32_t) floor(log2(n_head)); + + const float m0 = powf(2.0f, -(max_bias) / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + int ith = ctx.ith; + + static constexpr int Q_TILE_SZ = ggml_fa_tile_config::Q; + static constexpr int KV_TILE_SZ = ggml_fa_tile_config::KV; + static_assert(Q_TILE_SZ == KV_TILE_SZ && KV_TILE_SZ == 64, "IME2 Q staging and K8 tiles require Q=KV=64"); + + // Q/K/V are F16; KQ, mask and the output accumulator are F32. + const size_t q_bytes = Q_TILE_SZ * DK * sizeof(_Float16); + const size_t v_bytes = KV_TILE_SZ * DV * sizeof(_Float16); + const size_t base_size = fa_tiled_thread_bytes(dst, Q_TILE_SZ, KV_TILE_SZ); + const bool use_shared_kv = flash_attn_ext_f16_prepack_supported(dst); + const int64_t kv_tiles = (nek1 + KV_TILE_SZ - 1) / KV_TILE_SZ; + const _Float16 * packed_k = nullptr; + const _Float16 * packed_v = nullptr; + if (use_shared_kv) { + // Workers with empty query ranges also participate in prepacking. + forward_flash_attn_ext_f16_prepack(ctx, dst); + ctx.sync(); + packed_k = (const _Float16 *) ((const char *) ctx.workspace + base_size * ctx.nth); + packed_v = packed_k + kv_tiles * nek2 * KV_TILE_SZ * DK; + } + char * base = (char *) ctx.workspace + ith * base_size; + + if (base_size <= ctx.shared.size && ctx.shared.data != nullptr) { + base = (char *) ctx.shared.data; + } + + float S_M_Buf[Q_TILE_SZ * 2]; // buffer to hold S, M, bias for one tile to reduce register pressure in main loop + float * S = S_M_Buf; + float * M = S_M_Buf + Q_TILE_SZ; + + int ir = ir0; + while (ir < ir1) { + // q indices for the start of this tile + const int iq3 = ir / (neq2 * neq1); + const int iq2 = (ir - iq3 * neq2 * neq1) / neq1; + const int iq1 = (ir - iq3 * neq2 * neq1 - iq2 * neq1); + + // Number of valid rows in this tile: + // - limited by tile size (Q_TILE_SZ) + // - limited by chunk boundary (ir1 - ir) + // - limited by head boundary (neq1 - iq1) to avoid crossing into next head + const int tile_rows = MIN(Q_TILE_SZ, MIN((int) (ir1 - ir), (int) (neq1 - iq1))); + GGML_ASSERT(tile_rows > 0); + + const uint32_t h = iq2; // head index + const float slope = + (max_bias > 0.0f) ? h < n_head_log2 ? powf(m0, h + 1) : powf(m1, 2 * (h - n_head_log2) + 1) : 1.0f; + + for (int i = 0; i < Q_TILE_SZ; ++i) { + S[i] = 0.; + M[i] = -INFINITY; + } + + _Float16 * Q_f16 = (_Float16 *) base; + float * KQ = (float *) (base + q_bytes); + float * mask32 = KQ + Q_TILE_SZ * KV_TILE_SZ; + float * VKQ32 = mask32 + Q_TILE_SZ * KV_TILE_SZ; + _Float16 * V_f16 = (_Float16 *) (VKQ32 + Q_TILE_SZ * DV); + _Float16 * K_f16 = (_Float16 *) ((char *) V_f16 + v_bytes); + + rvv_zero_f32(VKQ32, Q_TILE_SZ * DV); + + // k indices + const int ik3 = iq3 / rk3; + const int ik2 = iq2 / rk2; + + // v indices + const int iv3 = iq3 / rv3; + const int iv2 = iq2 / rv2; + + const float * pq = (const float *) ((char *) q->data + (iq1 * nbq1 + iq2 * nbq2 + iq3 * nbq3)); + // K scratch is dead until the KV loop; stage Q there to keep one compact Q allocation. + rvv_pack_f32_as_scaled_f16((uint8_t *) K_f16, DK * sizeof(_Float16), (uint8_t *) pq, nbq1, tile_rows, DK, + scale); + rvv_fill_f16(Q_f16, 0.0f, Q_TILE_SZ * DK); + fa_pack_f16_k8(Q_f16, (const char *) K_f16, DK * sizeof(_Float16), tile_rows, DK, 16); + + for (int64_t ic = 0; ic < nek1; ic += KV_TILE_SZ) { + const int kv_tile = (int) std::min((int64_t) KV_TILE_SZ, nek1 - ic); + int active_kv[Q_TILE_SZ]; + int max_active_kv = kv_tile; + + // skip the tile entirely if all the masks are -inf + if (mask) { + const ggml_fp16_t * mp_row = + (const ggml_fp16_t *) ((const char *) mask->data + iq1 * mask->nb[1] + + (iq2 % mask->ne[2]) * mask->nb[2] + (iq3 % mask->ne[3]) * mask->nb[3]); + rvv_pack_scaled_f16_as_f32(mask32, KV_TILE_SZ * sizeof(float), mp_row + ic, mask->nb[1], tile_rows, + kv_tile, slope); + + max_active_kv = 0; + for (int tq = 0; tq < tile_rows; tq++) { + int tk = kv_tile; + if (mask32[tq * KV_TILE_SZ + tk - 1] == -INFINITY) { + const size_t vl = __riscv_vsetvl_e32m2(tk); + const auto values = __riscv_vle32_v_f32m2(mask32 + tq * KV_TILE_SZ, vl); + const auto valid = __riscv_vmfne_vf_f32m2_b16(values, -INFINITY, vl); + const auto indices = __riscv_vadd_vx_u32m2(__riscv_vid_v_u32m2(vl), 1, vl); + const auto selected = __riscv_vmerge_vvm_u32m2(__riscv_vmv_v_x_u32m2(0, vl), indices, valid, vl); + const auto last = __riscv_vredmaxu_vs_u32m2_u32m1(selected, __riscv_vmv_v_x_u32m1(0, 1), vl); + tk = __riscv_vmv_x_s_u32m1_u32(last); + } + active_kv[tq] = tk; + max_active_kv = std::max(max_active_kv, tk); + } + + if (max_active_kv == 0) { + continue; + } + } else { + std::fill_n(active_kv, tile_rows, kv_tile); + } + + // The GEMM reads padded K8 panels. + if (!use_shared_kv && max_active_kv < KV_TILE_SZ) { + rvv_fill_f16(K_f16, 0.0f, DK * KV_TILE_SZ); + } + if (use_shared_kv) { + const int64_t tile = ik2 * kv_tiles + ic / KV_TILE_SZ; + rvv::memcpy1d(K_f16, packed_k + tile * KV_TILE_SZ * DK, KV_TILE_SZ * DK * sizeof(_Float16)); + // Preserve padding semantics when a causal tile ends in masked NaN/Inf rows. + for (int r = max_active_kv; r < KV_TILE_SZ; ++r) { + for (int d = 0; d < DK; d += 8) { + rvv_fill_f16(K_f16 + (r / 32) * 32 * DK + d * 32 + (r % 32) * 8, 0.0f, 8); + } + } + } else { + fa_pack_f16_k8(K_f16, (const char *) k->data + ic * nbk1 + ik2 * nbk2 + ik3 * nbk3, + nbk1, max_active_kv, DK, 32); + } + for (int tq = 0; tq < tile_rows; tq += 16) { + for (int tk = 0; tk < max_active_kv; tk += 32) { + gemm_kernel_f16f16f32_m16_vfwmadot(DK, K_f16 + tk * DK, Q_f16 + tq * DK, + KQ + tq * KV_TILE_SZ + tk, std::min(16, tile_rows - tq), + std::min(32, max_active_kv - tk), KV_TILE_SZ, false); + } + } + + bool skip[Q_TILE_SZ] = {}; + + fa_update_softmax(KQ, mask32, mask != nullptr, logit_softcap, active_kv, skip, + tile_rows, KV_TILE_SZ, DV, M, S, VKQ32); + + // Softmax remains F32. Only the IME2 PV operands are rounded to F16. + // mask32 is dead here and can hold the packed probability tile. + auto * P_ime2 = reinterpret_cast<_Float16 *>(mask32); + memset(P_ime2, 0, Q_TILE_SZ * KV_TILE_SZ * sizeof(_Float16)); + // Gather K8 word pairs and store eight groups with a segmented stride. + const auto even = __riscv_vsll_vx_u64m1(__riscv_vid_v_u64m1(8), 1, 8); + const auto odd = __riscv_vadd_vx_u64m1(even, 1, 8); + for (int tq = 0; tq < tile_rows; ++tq) { + if (skip[tq]) continue; + auto * row = P_ime2 + (tq / 16) * 16 * KV_TILE_SZ + (tq % 16) * 8; + { + // Tail-undisturbed load zero-pads past row_active without reading stale logits. + const auto zero = __riscv_vfmv_v_f_f32m2(0.0f, KV_TILE_SZ); + const auto p32 = __riscv_vle32_v_f32m2_tu(zero, KQ + tq * KV_TILE_SZ, active_kv[tq]); + const auto p16 = __riscv_vfncvt_f_f_w_f16m1(p32, KV_TILE_SZ); + const auto words = __riscv_vreinterpret_v_u16m1_u64m1(__riscv_vreinterpret_v_f16m1_u16m1(p16)); + vuint64m1x2_t packed; + packed = __riscv_vset_v_u64m1_u64m1x2(packed, 0, __riscv_vrgather_vv_u64m1(words, even, 8)); + packed = __riscv_vset_v_u64m1_u64m1x2(packed, 1, __riscv_vrgather_vv_u64m1(words, odd, 8)); + __riscv_vssseg2e64_v_u64m1x2(reinterpret_cast(row), 16 * 8 * sizeof(_Float16), packed, 8); + } + } + if (use_shared_kv) { + const int64_t tile = iv2 * kv_tiles + ic / KV_TILE_SZ; + rvv::memcpy1d(V_f16, packed_v + tile * KV_TILE_SZ * DV, KV_TILE_SZ * DV * sizeof(_Float16)); + if (max_active_kv < KV_TILE_SZ) { + const auto zero = __riscv_vfmv_v_f_f16m1((_Float16) 0, 32); + for (int d = 0; d < DV; d += 32) { + for (int tk = max_active_kv; tk < KV_TILE_SZ; ++tk) { + __riscv_vsse16_v_f16m1(V_f16 + d * KV_TILE_SZ + (tk / 8) * 256 + tk % 8, + 8 * sizeof(_Float16), zero, 32); + } + } + } + } else { + fa_pack_v_f16(V_f16, (const char *) v->data + ic * nbv1 + iv2 * nbv2 + iv3 * nbv3, + nbv1, max_active_kv, DV); + } + for (int tq = 0; tq < tile_rows; tq += 16) { + for (int d = 0; d < DV; d += 32) { + fa_pv_f16f16f32_m16n32_k64_accumulate( + V_f16 + d * KV_TILE_SZ, P_ime2 + tq * KV_TILE_SZ, + VKQ32 + tq * DV + d, std::min(16, tile_rows - tq), DV); + } + } + } + + const float * sink = sinks ? (const float *) sinks->data + h : nullptr; + float * dst_ptr = (float *) ((char *) dst->data + (iq3 * ne2 * ne1 + iq2 + iq1 * ne1) * nb1); + fa_store_tile(dst_ptr, nb1 * ne1, VKQ32, DV, tile_rows, M, S, sink); + + ir += tile_rows; + } +} + } // namespace ime2 } // namespace spacemit_kernels diff --git a/ggml/src/ggml-spacemit/ime_kernels.h b/ggml/src/ggml-spacemit/ime_kernels.h index 50c1816e3003..d6d01b0cd42b 100644 --- a/ggml/src/ggml-spacemit/ime_kernels.h +++ b/ggml/src/ggml-spacemit/ime_kernels.h @@ -1,5 +1,7 @@ #pragma once +#include "spacemit-context.h" + #include #include #include @@ -88,6 +90,13 @@ void quantize_a_i8_r4(size_t blk_len, const float * a_ptr, size_t count_k, uint8 } // namespace ime1 namespace ime2 { +size_t flash_attn_ext_f16_tiled_workspace_size(const ggml_tensor * dst, int nth); + +void forward_flash_attn_ext_f16_tiled_ime2(ggml::spacemit::context & ctx, + ggml_tensor * dst, + int ir0, + int ir1); + size_t gemm_i8i2k_k256(a_pack ap, size_t blk_len, const uint8_t * quant_a_ptr, @@ -205,5 +214,12 @@ void gemm_kernel_f16f16f32_m16_vfwmadot(size_t gemm_k, size_t count_n, size_t ldc, bool accumulate = false); + +// Flash-attention PV: K64/N32 packed operands, direct F32 accumulation into valid M rows. +void fa_pv_f16f16f32_m16n32_k64_accumulate(const _Float16 * b_f16_k8, + _Float16 * a_f16_k8, + float * c_ptr, + size_t count_m, + size_t ldc); } // namespace ime2 } // namespace spacemit_kernels diff --git a/ggml/src/ggml-spacemit/rvv_kernels.cpp b/ggml/src/ggml-spacemit/rvv_kernels.cpp index a9b5032d9baa..3f0325254dae 100644 --- a/ggml/src/ggml-spacemit/rvv_kernels.cpp +++ b/ggml/src/ggml-spacemit/rvv_kernels.cpp @@ -1,7 +1,6 @@ #include "rvv_kernels.h" #include "common.h" -#include "spacemit-env.h" #include "ggml.h" #include "ggml-impl.h" #include "string.h" @@ -34,12 +33,14 @@ namespace spacemit_kernels::rvv { namespace { +using namespace detail; + auto align_up(size_t value, size_t alignment) { return (value + alignment - 1) / alignment * alignment; } // head dims above vlmax(e16m2) = 128 are processed in 128-wide segments -static constexpr int64_t FA_VLEN1024_MAX_D = 256; +static constexpr int64_t FA_VLEN1024_MAX_D = 512; // split-KV decode handles up to this many query tokens (speculative-decoding verification) static constexpr int64_t FA_SPLIT_KV_MAX_Q = 4; @@ -57,14 +58,6 @@ static inline float reduce_sum_f32m4_vlen1024(vfloat32m4_t v, size_t vl) { return __riscv_vfmv_f_s_f32m1_f32(s_v); } -static inline void rvv_fill_f16(_Float16 * dst, float value, int64_t n) { - for (int64_t d0 = 0; d0 < n;) { - const size_t vl = __riscv_vsetvl_e16m2(n - d0); - __riscv_vse16_v_f16m2(dst + d0, __riscv_vfmv_v_f_f16m2((_Float16) value, vl), vl); - d0 += vl; - } -} - static inline void rvv_scale_f16(_Float16 * dst, float scale, int64_t n) { for (int64_t d0 = 0; d0 < n;) { const size_t vl = __riscv_vsetvl_e16m2(n - d0); @@ -133,45 +126,6 @@ static inline void flash_attn_ext_finalize_row_f16(float * dst, } } -static inline float reduce_sum_f32m2_vlen1024(vfloat32m2_t v, size_t vl) { - vfloat32m1_t s_v = __riscv_vfmv_v_f_f32m1(0.0f, 1); - s_v = __riscv_vfredusum_vs_f32m2_f32m1(v, s_v, vl); - return __riscv_vfmv_f_s_f32m1_f32(s_v); -} - -// Adapted from ggml_v_expf_m2 in vec.h. This is accurate enough for softmax. -static inline vfloat32m2_t rvv_expf_approx_f32m2(vfloat32m2_t x, size_t vl) { - const vfloat32m2_t r = __riscv_vfmv_v_f_f32m2(0x1.8p23f, vl); - const vfloat32m2_t z = __riscv_vfmacc_vf_f32m2(r, 0x1.715476p+0f, x, vl); - const vfloat32m2_t n = __riscv_vfsub_vv_f32m2(z, r, vl); - const vfloat32m2_t b = - __riscv_vfnmsac_vf_f32m2(__riscv_vfnmsac_vf_f32m2(x, 0x1.62e4p-1f, n, vl), 0x1.7f7d1cp-20f, n, vl); - const vuint32m2_t e = __riscv_vsll_vx_u32m2(__riscv_vreinterpret_v_f32m2_u32m2(z), 23, vl); - const vfloat32m2_t k = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vadd_vx_u32m2(e, 0x3f800000, vl)); - const vbool16_t c = __riscv_vmfgt_vf_f32m2_b16(__riscv_vfabs_v_f32m2(n, vl), 126.0f, vl); - const vfloat32m2_t u = __riscv_vfmul_vv_f32m2(b, b, vl); - const vfloat32m2_t j = __riscv_vfmacc_vv_f32m2( - __riscv_vfmul_vf_f32m2(b, 0x1.ffffecp-1f, vl), - __riscv_vfmacc_vv_f32m2( - __riscv_vfmacc_vf_f32m2(__riscv_vfmv_v_f_f32m2(0x1.fffdb6p-2f, vl), 0x1.555e66p-3f, b, vl), - __riscv_vfmacc_vf_f32m2(__riscv_vfmv_v_f_f32m2(0x1.573e2ep-5f, vl), 0x1.0e4020p-7f, b, vl), u, vl), - u, vl); - - if (!__riscv_vcpop_m_b16(c, vl)) { - return __riscv_vfmacc_vv_f32m2(k, j, k, vl); - } - - const vbool16_t dm = __riscv_vmfle_vf_f32m2_b16(n, 0.0f, vl); - const vuint32m2_t d = __riscv_vmerge_vxm_u32m2(__riscv_vmv_v_x_u32m2(0, vl), 0x82000000, dm, vl); - const vfloat32m2_t s1 = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vadd_vx_u32m2(d, 0x7f000000, vl)); - const vfloat32m2_t s2 = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vsub_vv_u32m2(e, d, vl)); - const vfloat32m2_t r1 = - __riscv_vmerge_vvm_f32m2(__riscv_vfmacc_vv_f32m2(k, k, j, vl), - __riscv_vfmul_vv_f32m2(__riscv_vfmacc_vv_f32m2(s2, s2, j, vl), s1, vl), c, vl); - return __riscv_vmerge_vvm_f32m2(r1, __riscv_vfmul_vv_f32m2(s1, s1, vl), - __riscv_vmfgt_vf_f32m2_b16(__riscv_vfabs_v_f32m2(n, vl), 192.0f, vl), vl); -} - // log1p(t) for t in [0, 1] (Cephes logf polynomial). 1 + t is rounded, so the rounding error // (t - ((1 + t) - 1), exact in float) is added back as a first-order correction; for tiny t the // result is t. Used by softplus, whose t = exp(-|x|) keeps it within ~4 ulp for normal results. @@ -201,49 +155,6 @@ static inline vfloat32m2_t rvv_log1pf_01_f32m2(vfloat32m2_t t, size_t vl) { return __riscv_vfmacc_vf_f32m2(__riscv_vfadd_vv_f32m2(f, y, vl), 0.693359375f, e, vl); } -static inline vfloat32m2_t rvv_tanh_approx_f32m2(vfloat32m2_t x, size_t vl) { - const vfloat32m2_t abs_x = __riscv_vfabs_v_f32m2(x, vl); - const vfloat32m2_t neg_2_abs = __riscv_vfmul_vf_f32m2(abs_x, -2.0f, vl); - const vfloat32m2_t exp_term = rvv_expf_approx_f32m2(neg_2_abs, vl); - const vfloat32m2_t numerator = __riscv_vfsub_vf_f32m2(exp_term, 1.0f, vl); - const vfloat32m2_t denominator = __riscv_vfadd_vf_f32m2(exp_term, 1.0f, vl); - const vfloat32m2_t tanh_abs = __riscv_vfneg_v_f32m2(__riscv_vfdiv_vv_f32m2(numerator, denominator, vl), vl); - const vbool16_t neg_mask = __riscv_vmflt_vf_f32m2_b16(x, 0.0f, vl); - const vfloat32m2_t tanh_neg = __riscv_vfneg_v_f32m2(tanh_abs, vl); - return __riscv_vmerge_vvm_f32m2(tanh_abs, tanh_neg, neg_mask, vl); -} - -static void rvv_softcap_tanh_inplace_f32(float * dst, int64_t dst_stride, int64_t tile_rows, int64_t n, float softcap) { - for (int tq = 0; tq < tile_rows; ++tq, dst += dst_stride) { - float * dst_row = dst; - int64_t remaining = n; - while (remaining > 0) { - const size_t vl = __riscv_vsetvl_e32m2(remaining); - vfloat32m2_t v = __riscv_vle32_v_f32m2(dst_row, vl); - v = rvv_tanh_approx_f32m2(v, vl); - v = __riscv_vfmul_vf_f32m2(v, softcap, vl); - __riscv_vse32_v_f32m2(dst_row, v, vl); - dst_row += vl; - remaining -= vl; - } - } -} - -static inline float rvv_softmax_exp_inplace_f32(float * dst, int64_t n, float max_value) { - float row_sum = 0.0f; - while (n > 0) { - const size_t vl = __riscv_vsetvl_e32m2(n); - vfloat32m2_t v = __riscv_vle32_v_f32m2(dst, vl); - v = __riscv_vfsub_vf_f32m2(v, max_value, vl); - v = rvv_expf_approx_f32m2(v, vl); - __riscv_vse32_v_f32m2(dst, v, vl); - row_sum += reduce_sum_f32m2_vlen1024(v, vl); - dst += vl; - n -= vl; - } - return row_sum; -} - static inline float rvv_add_max_inplace_f32(float * dst, const float * src, int64_t n) { float max_val = -INFINITY; while (n > 0) { @@ -290,135 +201,6 @@ static inline float rvv_softcap_add_max_inplace_f32(float * dst, const float * s return max_val; } -static inline void rvv_zero_f32(float * dst, int64_t n) { - while (n > 0) { - const size_t vl = __riscv_vsetvl_e32m4(n); - const vfloat32m4_t z = __riscv_vfmv_v_f_f32m4(0.0f, vl); - __riscv_vse32_v_f32m4(dst, z, vl); - dst += vl; - n -= vl; - } -} - -static inline void rvv_scale_f32(float * dst, float scale, int64_t n) { - while (n > 0) { - const size_t vl = __riscv_vsetvl_e32m4(n); - vfloat32m4_t v = __riscv_vle32_v_f32m4(dst, vl); - v = __riscv_vfmul_vf_f32m4(v, scale, vl); - __riscv_vse32_v_f32m4(dst, v, vl); - dst += vl; - n -= vl; - } -} - -static inline void rvv_add_inplace_f32(float * dst, - int64_t dst_stride, - const float * src, - int64_t src_stride, - int64_t tile_rows, - int64_t n) { - for (int tq = 0; tq < tile_rows; ++tq, dst += dst_stride, src += src_stride) { - int64_t remaining = n; - float * dst_row = dst; - const float * src_row = src; - while (remaining > 0) { - const size_t vl = __riscv_vsetvl_e32m4(remaining); - vfloat32m4_t vdst = __riscv_vle32_v_f32m4(dst_row, vl); - vfloat32m4_t vsrc = __riscv_vle32_v_f32m4(src_row, vl); - vdst = __riscv_vfadd_vv_f32m4(vdst, vsrc, vl); - __riscv_vse32_v_f32m4(dst_row, vdst, vl); - dst_row += vl; - src_row += vl; - remaining -= vl; - } - } -} - -static inline float rvv_max_f32(const float * src, int64_t n) { - float max_val = -INFINITY; - while (n > 0) { - const size_t vl = __riscv_vsetvl_e32m4(n); - const vfloat32m4_t v = __riscv_vle32_v_f32m4(src, vl); - vfloat32m1_t seed = __riscv_vfmv_v_f_f32m1(max_val, 1); - seed = __riscv_vfredmax_vs_f32m4_f32m1(v, seed, vl); - max_val = __riscv_vfmv_f_s_f32m1_f32(seed); - src += vl; - n -= vl; - } - return max_val; -} - -static void rvv_pack_f32_as_scaled_f16(void * dst, - int64_t dst_row_stride, - const void * src, - int64_t src_row_stride, - int64_t tile_rows, - int64_t n, - float scale) { - for (int tq = 0; tq < tile_rows; ++tq) { - const float * row_ptr = (const float *) ((const char *) src + tq * src_row_stride); - _Float16 * dst_row_ptr = (_Float16 *) ((char *) dst + tq * dst_row_stride); - int64_t remaining = n; - while (remaining > 0) { - const size_t vl = __riscv_vsetvl_e32m4(remaining); - vfloat32m4_t v32 = __riscv_vle32_v_f32m4(row_ptr, vl); - v32 = __riscv_vfmul_vf_f32m4(v32, scale, vl); - const vfloat16m2_t v16 = __riscv_vfncvt_f_f_w_f16m2(v32, vl); - __riscv_vse16_v_f16m2(dst_row_ptr, v16, vl); - dst_row_ptr += vl; - row_ptr += vl; - remaining -= vl; - } - } -} - -static void rvv_pack_scaled_f16_as_f32(void * dst, - int64_t dst_row_stride, - const void * src, - int64_t src_row_stride, - int64_t tile_rows, - int64_t n, - float scale) { - for (int tq = 0; tq < tile_rows; ++tq) { - const _Float16 * row_ptr = (const _Float16 *) ((const char *) src + tq * src_row_stride); - float * dst_row_ptr = (float *) ((char *) dst + tq * dst_row_stride); - int64_t remaining = n; - while (remaining > 0) { - const size_t vl = __riscv_vsetvl_e16m2(remaining); - const vfloat16m2_t v16 = __riscv_vle16_v_f16m2(row_ptr, vl); - vfloat32m4_t v32 = __riscv_vfwcvt_f_f_v_f32m4(v16, vl); - v32 = __riscv_vfmul_vf_f32m4(v32, scale, vl); - __riscv_vse32_v_f32m4(dst_row_ptr, v32, vl); - dst_row_ptr += vl; - row_ptr += vl; - remaining -= vl; - } - } -} - -static void rvv_pack_scaled_f32_as_f32(void * dst, - int64_t dst_row_stride, - const void * src, - int64_t src_row_stride, - int64_t tile_rows, - int64_t n, - float * scale) { - for (int tq = 0; tq < tile_rows; ++tq) { - const float * row_ptr = (const float *) ((const char *) src + tq * src_row_stride); - float * dst_row_ptr = (float *) ((char *) dst + tq * dst_row_stride); - int64_t remaining = n; - while (remaining > 0) { - const size_t vl = __riscv_vsetvl_e32m4(remaining); - vfloat32m4_t v32 = __riscv_vle32_v_f32m4(row_ptr, vl); - v32 = __riscv_vfmul_vf_f32m4(v32, scale[tq], vl); - __riscv_vse32_v_f32m4(dst_row_ptr, v32, vl); - dst_row_ptr += vl; - row_ptr += vl; - remaining -= vl; - } - } -} - static inline void rvv_transposed_s32_mn_to_nm(int8_t * dst, int64_t n_dst_stride, int8_t * src, @@ -588,15 +370,16 @@ static inline void rvv_qk_dot_tile_f16_x1(float * dst, const _Float16 * k_pack, int64_t dk, int64_t kv_tile) { - const size_t vl = __riscv_vsetvl_e16m1(kv_tile); - vfloat32m2_t acc = __riscv_vfmv_v_f_f32m2(0.0f, vl); - - for (int64_t d = 0; d < dk; ++d) { - const vfloat16m1_t k_vec = __riscv_vle16_v_f16m1(k_pack + d * ggml_fa_tile_config::KV, vl); - acc = __riscv_vfwmacc_vf_f32m2(acc, q_row[d], k_vec, vl); + for (int64_t tk = 0; tk < kv_tile;) { + const size_t vl = __riscv_vsetvl_e16m1(kv_tile - tk); + vfloat32m2_t acc = __riscv_vfmv_v_f_f32m2(0.0f, vl); + for (int64_t d = 0; d < dk; ++d) { + const vfloat16m1_t k_vec = __riscv_vle16_v_f16m1(k_pack + d * ggml_fa_tile_config::KV + tk, vl); + acc = __riscv_vfwmacc_vf_f32m2(acc, q_row[d], k_vec, vl); + } + __riscv_vse32_v_f32m2(dst + tk, acc, vl); + tk += vl; } - - __riscv_vse32_v_f32m2(dst, acc, vl); } static inline void rvv_qk_dot_tile_f16_x4(float * dst0, @@ -610,24 +393,25 @@ static inline void rvv_qk_dot_tile_f16_x4(float * dst0, const _Float16 * k_pack, int64_t dk, int64_t kv_tile) { - const size_t vl = __riscv_vsetvl_e16m1(kv_tile); - vfloat32m2_t acc0 = __riscv_vfmv_v_f_f32m2(0.0f, vl); - vfloat32m2_t acc1 = __riscv_vfmv_v_f_f32m2(0.0f, vl); - vfloat32m2_t acc2 = __riscv_vfmv_v_f_f32m2(0.0f, vl); - vfloat32m2_t acc3 = __riscv_vfmv_v_f_f32m2(0.0f, vl); - - for (int64_t d = 0; d < dk; ++d) { - const vfloat16m1_t k_vec = __riscv_vle16_v_f16m1(k_pack + d * ggml_fa_tile_config::KV, vl); - acc0 = __riscv_vfwmacc_vf_f32m2(acc0, q0[d], k_vec, vl); - acc1 = __riscv_vfwmacc_vf_f32m2(acc1, q1[d], k_vec, vl); - acc2 = __riscv_vfwmacc_vf_f32m2(acc2, q2[d], k_vec, vl); - acc3 = __riscv_vfwmacc_vf_f32m2(acc3, q3[d], k_vec, vl); + for (int64_t tk = 0; tk < kv_tile;) { + const size_t vl = __riscv_vsetvl_e16m1(kv_tile - tk); + vfloat32m2_t acc0 = __riscv_vfmv_v_f_f32m2(0.0f, vl); + vfloat32m2_t acc1 = __riscv_vfmv_v_f_f32m2(0.0f, vl); + vfloat32m2_t acc2 = __riscv_vfmv_v_f_f32m2(0.0f, vl); + vfloat32m2_t acc3 = __riscv_vfmv_v_f_f32m2(0.0f, vl); + for (int64_t d = 0; d < dk; ++d) { + const vfloat16m1_t k_vec = __riscv_vle16_v_f16m1(k_pack + d * ggml_fa_tile_config::KV + tk, vl); + acc0 = __riscv_vfwmacc_vf_f32m2(acc0, q0[d], k_vec, vl); + acc1 = __riscv_vfwmacc_vf_f32m2(acc1, q1[d], k_vec, vl); + acc2 = __riscv_vfwmacc_vf_f32m2(acc2, q2[d], k_vec, vl); + acc3 = __riscv_vfwmacc_vf_f32m2(acc3, q3[d], k_vec, vl); + } + __riscv_vse32_v_f32m2(dst0 + tk, acc0, vl); + __riscv_vse32_v_f32m2(dst1 + tk, acc1, vl); + __riscv_vse32_v_f32m2(dst2 + tk, acc2, vl); + __riscv_vse32_v_f32m2(dst3 + tk, acc3, vl); + tk += vl; } - - __riscv_vse32_v_f32m2(dst0, acc0, vl); - __riscv_vse32_v_f32m2(dst1, acc1, vl); - __riscv_vse32_v_f32m2(dst2, acc2, vl); - __riscv_vse32_v_f32m2(dst3, acc3, vl); } static inline void rvv_pv_accumulate_f16_x1(float * dst, @@ -693,47 +477,6 @@ static inline void rvv_pv_accumulate_f16_x4(float * dst0, } } -static inline void rvv_qk_dot_tile(float * dst, - const float * q_row, - const float * k_pack, - int64_t dk, - int64_t kv_stride, - int64_t kv_tile, - float scale) { - const size_t vl = __riscv_vsetvl_e32m4(kv_tile); - vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); - - for (int64_t d = 0; d < dk; ++d) { - const vfloat32m4_t k_vec = __riscv_vle32_v_f32m4(k_pack + d * kv_stride, vl); - acc = __riscv_vfmacc_vf_f32m4(acc, q_row[d] * scale, k_vec, vl); - } - - __riscv_vse32_v_f32m4(dst, acc, vl); -} - -static inline void rvv_pv_accumulate(float * dst, - const float * prob, - const float * v_pack, - int64_t kv_tile, - int64_t dv) { - int64_t d_left = dv; - int64_t d_off = 0; - - while (d_left > 0) { - const size_t vl = __riscv_vsetvl_e32m4(d_left); - vfloat32m4_t acc = __riscv_vle32_v_f32m4(dst + d_off, vl); - - for (int64_t tk = 0; tk < kv_tile; ++tk) { - const vfloat32m4_t v_vec = __riscv_vle32_v_f32m4(v_pack + tk * dv + d_off, vl); - acc = __riscv_vfmacc_vf_f32m4(acc, prob[tk], v_vec, vl); - } - - __riscv_vse32_v_f32m4(dst + d_off, acc, vl); - d_left -= vl; - d_off += vl; - } -} - static void permute_transpose_impl(const ggml_tensor * src0, ggml_tensor * dst, int64_t batch, @@ -787,7 +530,8 @@ static void flash_attn_ext_f16_one_chunk_inner_vlen1024_vf16_mrow(float ** // its own mask row at mp + m * mask_row_stride bytes; a KV position is packed if any token can see it. // With partial != nullptr row i writes {M, S, unnormalized VKQ[DV]} to partial[i] (for a later split-KV // reduction) instead of the normalized output to dst[i]. - static_assert(QLEN == 2 || QLEN == 4 || QLEN == 8 || QLEN == 16, "unsupported QLEN"); + static_assert(QLEN == 2 || QLEN == 4 || QLEN == 8 || QLEN == 16 || QLEN == 24 || QLEN == 32, + "unsupported QLEN"); GGML_ASSERT(n_mask_rows >= 1 && QLEN % n_mask_rows == 0 && n_mask_rows <= 16); const int64_t rows_per_mask = QLEN / n_mask_rows; auto mask_at = [&](int64_t m, int64_t ic) -> float { @@ -843,9 +587,32 @@ static void flash_attn_ext_f16_one_chunk_inner_vlen1024_vf16_mrow(float ** int64_t ic_step = 0; for (int64_t ic = 0; ic < nek1; ++ic) { + const char * direct_v = nullptr; + bool packed_tile = false; + if constexpr (QLEN == 4) { + if (partial && n_mask_rows == 1 && DK == 256 && DV == 256 && ic_step == 0 && + ic + ic_tile_step <= nek1) { + bool all_visible = true; + for (int64_t tk = 0; tk < ic_tile_step; ++tk) { + mv_tile_pack[tk] = mask_at(0, ic + tk); + all_visible &= mv_tile_pack[tk] != -INFINITY; + } + if (all_visible) { + // Eight-row segmented stores avoid channel-strided scatters into TCM. + rvv_transposed_s16_mn_to_nm((int8_t *) k_tile_pack, k_tile_byte_stride, + (int8_t *) k_data_row + ic * nbk1, nbk1, ic_tile_step, DK); + // This single PV group consumes each visible V row once. + direct_v = v_data_row + ic * nbv1; + ic += ic_tile_step - 1; + ic_step = ic_tile_step; + packed_tile = true; + } + } + } + float mvs[16]; bool visible = false; - for (int64_t m = 0; m < n_mask_rows; ++m) { + for (int64_t m = 0; !packed_tile && m < n_mask_rows; ++m) { mvs[m] = mask_at(m, ic); visible |= mvs[m] != -INFINITY; } @@ -926,6 +693,10 @@ static void flash_attn_ext_f16_one_chunk_inner_vlen1024_vf16_mrow(float ** const float tile_max = rvv_softcap_add_max_inplace_f32( row_ptr, mv_tile_pack + (i / rows_per_mask) * ic_tile_step, ic_step, logit_softcap); + if (tile_max == -INFINITY) { + rvv_zero_f32(row_ptr, ic_step); + continue; + } const float Mold = M[i]; if (tile_max > Mold) { @@ -938,7 +709,38 @@ static void flash_attn_ext_f16_one_chunk_inner_vlen1024_vf16_mrow(float ** S[i] += rvv_softmax_exp_inplace_f32(row_ptr, ic_step, M[i]); } - for (int64_t d0 = 0; d0 < DV; d0 += seg) { + bool pv_m4 = false; + if constexpr (QLEN == 4) { + if (partial && n_mask_rows == 1 && DK == 256 && DV == 256) { + const size_t vl = __riscv_vsetvl_e16m4(DV); + vfloat16m4_t pv_acc0 = __riscv_vle16_v_f16m4(kq16_buffer + 0 * DV, vl); + vfloat16m4_t pv_acc1 = __riscv_vle16_v_f16m4(kq16_buffer + 1 * DV, vl); + vfloat16m4_t pv_acc2 = __riscv_vle16_v_f16m4(kq16_buffer + 2 * DV, vl); + vfloat16m4_t pv_acc3 = __riscv_vle16_v_f16m4(kq16_buffer + 3 * DV, vl); + const float * p0 = kq_tile_buffer + 0 * ic_tile_step; + const float * p1 = kq_tile_buffer + 1 * ic_tile_step; + const float * p2 = kq_tile_buffer + 2 * ic_tile_step; + const float * p3 = kq_tile_buffer + 3 * ic_tile_step; + + for (int64_t tk = 0; tk < ic_step; ++tk) { + const _Float16 * vrow = direct_v ? (const _Float16 *) (direct_v + tk * nbv1) : + v_tile_pack + tk * DV; + const vfloat16m4_t v16 = __riscv_vle16_v_f16m4(vrow, vl); + pv_acc0 = __riscv_vfmacc_vf_f16m4(pv_acc0, (_Float16) p0[tk], v16, vl); + pv_acc1 = __riscv_vfmacc_vf_f16m4(pv_acc1, (_Float16) p1[tk], v16, vl); + pv_acc2 = __riscv_vfmacc_vf_f16m4(pv_acc2, (_Float16) p2[tk], v16, vl); + pv_acc3 = __riscv_vfmacc_vf_f16m4(pv_acc3, (_Float16) p3[tk], v16, vl); + } + + __riscv_vse16_v_f16m4(kq16_buffer + 0 * DV, pv_acc0, vl); + __riscv_vse16_v_f16m4(kq16_buffer + 1 * DV, pv_acc1, vl); + __riscv_vse16_v_f16m4(kq16_buffer + 2 * DV, pv_acc2, vl); + __riscv_vse16_v_f16m4(kq16_buffer + 3 * DV, pv_acc3, vl); + pv_m4 = true; + } + } + + for (int64_t d0 = 0; !pv_m4 && d0 < DV; d0 += seg) { const size_t vl = __riscv_vsetvl_e16m2(DV - d0); for (size_t g = 0; g < QLEN; g += 4) { if constexpr (QLEN >= 4) { @@ -1302,7 +1104,7 @@ void forward_flash_attn_ext_f16_one_chunk_vlen1024_vf16(ggml::spacemit::context (iq3 % mask->ne[3]) * mask->nb[3]) : NULL; - const bool mp_equal_2 = iq1_1 == iq1 && (iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) && + const bool mp_equal_2 = mask && iq1_1 == iq1 && (iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_1 % mask->ne[3]); const bool mp_equal_4 = mp_equal_2 && iq1_2 == iq1 && (iq2 % mask->ne[2]) == (iq2_2 % mask->ne[2]) && @@ -1461,15 +1263,19 @@ void forward_flash_attn_ext_f16_split_kv_partial_vlen1024_vf16(ggml::spacemit::c const int64_t chunk = (n_kv + n_chunks - 1) / n_chunks; - std::array pq; - std::array pr; - std::array unused = {}; + std::array pq; + std::array pr; + std::array unused = {}; - // all query tokens of a unit in one pass (one K/V pack) when rk2 * nq is a supported row count + // All query tokens share one K/V pack when their combined row count is supported. const int64_t rows = rk2 * nq; - const bool fused = rows == 2 || rows == 4 || rows == 8 || rows == 16; - const int64_t n_pass = fused ? 1 : nq; - const int64_t prows = fused ? rows : rk2; + const size_t wide_qkv_bytes = rows * (DK + DV) * sizeof(_Float16); + const size_t wide_tile_bytes = 8 * (rows * sizeof(float) + (DK + DV) * sizeof(_Float16) + nq * sizeof(float)); + const bool wide_fits = tcm_buffer_size >= wide_qkv_bytes + wide_tile_bytes + 64; + const bool fused = rows == 2 || rows == 4 || rows == 8 || rows == 16 || + (wide_fits && (DK > 256 || DV > 256) && (rows == 24 || rows == 32)); + const int64_t queries_per_pass = fused ? nq : + (rk2 == 8 && (nq == 3 || nq == 4) ? 2 : 1); for (int64_t u = ctx.ith; u < n_kvh * n_chunks; u += ctx.nth) { const int64_t kvh = u / n_chunks; @@ -1480,17 +1286,17 @@ void forward_flash_attn_ext_f16_split_kv_partial_vlen1024_vf16(ggml::spacemit::c const char * kd = (const char *) k->data + kvh * k->nb[2] + c0 * k->nb[1]; const char * vd = (const char *) v->data + kvh * v->nb[2] + c0 * v->nb[1]; - for (int64_t p = 0; p < n_pass; ++p) { + for (int64_t t0 = 0; t0 < nq; t0 += queries_per_pass) { + const int64_t n_mask_rows = std::min(queries_per_pass, nq - t0); + const int64_t prows = rk2 * n_mask_rows; for (int64_t r = 0; r < prows; ++r) { - const int64_t t = fused ? r / rk2 : p; - const int64_t i = fused ? r % rk2 : r; + const int64_t t = t0 + r / rk2; + const int64_t i = r % rk2; pq[r] = (float *) ((char *) q->data + t * q->nb[1] + (h0 + i) * q->nb[2]); pr[r] = partials + ((t * nh + h0 + i) * n_chunks + c) * (2 + DV); } - const int64_t t0 = fused ? 0 : p; const ggml_fp16_t * mp = mask ? (const ggml_fp16_t *) ((const char *) mask->data + t0 * mask->nb[1]) + c0 : nullptr; - const int64_t n_mask_rows = fused ? nq : 1; const size_t mstride = mask ? mask->nb[1] : 0; #define FA_SPLIT_MROW(QL) \ @@ -1502,6 +1308,8 @@ void forward_flash_attn_ext_f16_split_kv_partial_vlen1024_vf16(ggml::spacemit::c case 2: FA_SPLIT_MROW(2); break; case 4: FA_SPLIT_MROW(4); break; case 8: FA_SPLIT_MROW(8); break; + case 24: FA_SPLIT_MROW(24); break; + case 32: FA_SPLIT_MROW(32); break; default: FA_SPLIT_MROW(16); break; } #undef FA_SPLIT_MROW @@ -1575,10 +1383,14 @@ void forward_flash_attn_ext_f16_split_kv_reduce_vlen1024_vf16(ggml::spacemit::co } } -void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ctx, - ggml_tensor * dst, - int ir0, - int ir1) { +size_t flash_attn_ext_f16_tiled_workspace_size(const ggml_tensor * dst, int nth) { + return fa_tiled_thread_bytes(dst, ggml_fa_tile_config::Q, ggml_fa_tile_config::KV) * nth; +} + +void forward_flash_attn_ext_f16_tiled_rvv(ggml::spacemit::context & ctx, + ggml_tensor * dst, + int ir0, + int ir1) { const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; @@ -1620,8 +1432,7 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ct GGML_ASSERT(nb1 <= nb2); GGML_ASSERT(nb2 <= nb3); - GGML_ASSERT(k->type == v->type); - const ggml_type kv_type = k->type; + GGML_ASSERT(q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16); // broadcast factors const int64_t rk2 = neq2 / nek2; @@ -1650,23 +1461,14 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ct static constexpr int Q_TILE_SZ = ggml_fa_tile_config::Q; static constexpr int KV_TILE_SZ = ggml_fa_tile_config::KV; - // Per-thread scratch layout: - // Q_f32: Q_TILE_SZ * DK - // KQ: Q_TILE_SZ * KV_TILE_SZ - // mask32: Q_TILE_SZ * KV_TILE_SZ - // VKQ32: Q_TILE_SZ * DV - // V32: KV_TILE_SZ * DV - // K_f32: DK * KV_TILE_SZ (transposed K tile) - float * base = (float *) ctx.workspace + - ith * (Q_TILE_SZ * DK + 2 * Q_TILE_SZ * KV_TILE_SZ + Q_TILE_SZ * DV + KV_TILE_SZ * DV + - KV_TILE_SZ * DK + ggml::spacemit::cache_line_size_f32); - const size_t base_size = - (Q_TILE_SZ * DK + 2 * Q_TILE_SZ * KV_TILE_SZ + Q_TILE_SZ * DV + KV_TILE_SZ * DV + KV_TILE_SZ * DK) * - sizeof(float) + - ggml::spacemit::cache_line_size_f32 * sizeof(float); + // Q/K/V are F16; KQ, mask and the output accumulator are F32. + const size_t q_bytes = Q_TILE_SZ * DK * sizeof(_Float16); + const size_t v_bytes = KV_TILE_SZ * DV * sizeof(_Float16); + const size_t base_size = fa_tiled_thread_bytes(dst, Q_TILE_SZ, KV_TILE_SZ); + char * base = (char *) ctx.workspace + ith * base_size; if (base_size <= ctx.shared.size && ctx.shared.data != nullptr) { - base = (float *) ctx.shared.data; + base = (char *) ctx.shared.data; } float S_M_Buf[Q_TILE_SZ * 2]; // buffer to hold S, M, bias for one tile to reduce register pressure in main loop @@ -1696,15 +1498,12 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ct M[i] = -INFINITY; } - float * Q_f32 = base; - float * KQ = (float *) ((char *) base + Q_TILE_SZ * DK * sizeof(float)); + _Float16 * Q_f16 = (_Float16 *) base; + float * KQ = (float *) (base + q_bytes); float * mask32 = KQ + Q_TILE_SZ * KV_TILE_SZ; float * VKQ32 = mask32 + Q_TILE_SZ * KV_TILE_SZ; - float * V32 = VKQ32 + Q_TILE_SZ * DV; - float * K_f32 = V32 + KV_TILE_SZ * DV; - _Float16 * Q_f16 = (_Float16 *) Q_f32; - _Float16 * V_f16 = (_Float16 *) V32; - _Float16 * K_f16 = (_Float16 *) K_f32; + _Float16 * V_f16 = (_Float16 *) (VKQ32 + Q_TILE_SZ * DV); + _Float16 * K_f16 = (_Float16 *) ((char *) V_f16 + v_bytes); rvv_zero_f32(VKQ32, Q_TILE_SZ * DV); @@ -1717,21 +1516,14 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ct const int iv2 = iq2 / rv2; const float * pq = (const float *) ((char *) q->data + (iq1 * nbq1 + iq2 * nbq2 + iq3 * nbq3)); - if (kv_type == GGML_TYPE_F16) { - rvv_pack_f32_as_scaled_f16((uint8_t *) Q_f16, DK * sizeof(_Float16), (uint8_t *) pq, nbq1, tile_rows, DK, - scale); - } else { - memcpy2d(Q_f32, DK * sizeof(float), pq, nbq1, tile_rows, DK * sizeof(float)); - } + rvv_pack_f32_as_scaled_f16((uint8_t *) Q_f16, DK * sizeof(_Float16), (uint8_t *) pq, nbq1, tile_rows, DK, + scale); for (int64_t ic = 0; ic < nek1; ic += KV_TILE_SZ) { const int kv_tile = (int) std::min((int64_t) KV_TILE_SZ, nek1 - ic); int active_kv[Q_TILE_SZ]; int max_active_kv = kv_tile; - rvv_zero_f32(K_f32, DK * KV_TILE_SZ); - rvv_zero_f32(V32, KV_TILE_SZ * DV); - // skip the tile entirely if all the masks are -inf if (mask) { const ggml_fp16_t * mp_row = @@ -1757,156 +1549,69 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ct std::fill_n(active_kv, tile_rows, kv_tile); } - if (kv_type == GGML_TYPE_F16) { - rvv_transposed_s16_mn_to_nm((int8_t *) K_f16, KV_TILE_SZ * sizeof(_Float16), - (int8_t *) k->data + ic * nbk1 + ik2 * nbk2 + ik3 * nbk3, nbk1, - max_active_kv, - DK); - - int tq = 0; - for (; tq + 3 < tile_rows; tq += 4) { - const int group_active = std::max(std::max(active_kv[tq + 0], active_kv[tq + 1]), - std::max(active_kv[tq + 2], active_kv[tq + 3])); - if (group_active > 0) { - rvv_qk_dot_tile_f16_x4(KQ + (tq + 0) * KV_TILE_SZ, KQ + (tq + 1) * KV_TILE_SZ, - KQ + (tq + 2) * KV_TILE_SZ, KQ + (tq + 3) * KV_TILE_SZ, - Q_f16 + (tq + 0) * DK, Q_f16 + (tq + 1) * DK, Q_f16 + (tq + 2) * DK, - Q_f16 + (tq + 3) * DK, K_f16, DK, group_active); - } - } - for (; tq < tile_rows; ++tq) { - if (active_kv[tq] > 0) { - rvv_qk_dot_tile_f16_x1(KQ + tq * KV_TILE_SZ, Q_f16 + tq * DK, K_f16, DK, active_kv[tq]); - } - } - } else { - for (int tk = 0; tk < max_active_kv; tk++) { - const char * k_data = (const char *) k->data + (ic + tk) * nbk1 + ik2 * nbk2 + ik3 * nbk3; - float * k_col = K_f32 + tk; - const float * k_src = (const float *) k_data; - for (int64_t dk = 0; dk < DK; ++dk) { - k_col[dk * KV_TILE_SZ] = k_src[dk]; - } + rvv_transposed_s16_mn_to_nm((int8_t *) K_f16, KV_TILE_SZ * sizeof(_Float16), + (int8_t *) k->data + ic * nbk1 + ik2 * nbk2 + ik3 * nbk3, nbk1, + max_active_kv, + DK); + + int tq = 0; + for (; tq + 3 < tile_rows; tq += 4) { + const int group_active = std::max(std::max(active_kv[tq + 0], active_kv[tq + 1]), + std::max(active_kv[tq + 2], active_kv[tq + 3])); + if (group_active > 0) { + rvv_qk_dot_tile_f16_x4(KQ + (tq + 0) * KV_TILE_SZ, KQ + (tq + 1) * KV_TILE_SZ, + KQ + (tq + 2) * KV_TILE_SZ, KQ + (tq + 3) * KV_TILE_SZ, + Q_f16 + (tq + 0) * DK, Q_f16 + (tq + 1) * DK, Q_f16 + (tq + 2) * DK, + Q_f16 + (tq + 3) * DK, K_f16, DK, group_active); } - - for (int tq = 0; tq < tile_rows; ++tq) { - if (active_kv[tq] > 0) { - rvv_qk_dot_tile(KQ + tq * KV_TILE_SZ, Q_f32 + tq * DK, K_f32, DK, KV_TILE_SZ, active_kv[tq], - scale); - } + } + for (; tq < tile_rows; ++tq) { + if (active_kv[tq] > 0) { + rvv_qk_dot_tile_f16_x1(KQ + tq * KV_TILE_SZ, Q_f16 + tq * DK, K_f16, DK, active_kv[tq]); } } bool skip[Q_TILE_SZ] = {}; - for (int tq = 0; tq < tile_rows; tq++) { - float * kq_row = KQ + tq * KV_TILE_SZ; - const int row_active = active_kv[tq]; - - if (row_active == 0) { - skip[tq] = true; - continue; - } - - if (logit_softcap != 0.0f) { - rvv_softcap_tanh_inplace_f32(kq_row, KV_TILE_SZ, 1, row_active, logit_softcap); - } - if (mask) { - rvv_add_inplace_f32(kq_row, KV_TILE_SZ, mask32 + tq * KV_TILE_SZ, KV_TILE_SZ, 1, row_active); - } - - const float tile_max = rvv_max_f32(kq_row, row_active); - - if (tile_max == -INFINITY) { - skip[tq] = true; - continue; - } - - const float Mold = M[tq]; - const float Mnew = fmaxf(Mold, tile_max); - - if (Mnew > Mold) { - const float ms = expf(Mold - Mnew); - rvv_scale_f32(VKQ32 + tq * DV, ms, DV); - S[tq] *= ms; - } - M[tq] = Mnew; - - S[tq] += rvv_softmax_exp_inplace_f32(kq_row, row_active, Mnew); - } + fa_update_softmax(KQ, mask32, mask != nullptr, logit_softcap, active_kv, skip, + tile_rows, KV_TILE_SZ, DV, M, S, VKQ32); - // Pack V as contiguous [KV_TILE_SZ][DV]. - if (kv_type == GGML_TYPE_F16) { - const char * v_data = (const char *) v->data + ic * nbv1 + iv2 * nbv2 + iv3 * nbv3; - memcpy2d(V_f16, DV * sizeof(_Float16), v_data, nbv1, max_active_kv, DV * sizeof(_Float16)); - - int tq = 0; - for (; tq + 3 < tile_rows; tq += 4) { - if (skip[tq + 0] || skip[tq + 1] || skip[tq + 2] || skip[tq + 3]) { - for (int i = 0; i < 4; ++i) { - if (!skip[tq + i]) { - rvv_pv_accumulate_f16_x1(VKQ32 + (tq + i) * DV, KQ + (tq + i) * KV_TILE_SZ, V_f16, - active_kv[tq + i], DV); - } - } - continue; - } + const char * v_data = (const char *) v->data + ic * nbv1 + iv2 * nbv2 + iv3 * nbv3; + memcpy2d(V_f16, DV * sizeof(_Float16), v_data, nbv1, max_active_kv, DV * sizeof(_Float16)); - const int group_active = std::max(std::max(active_kv[tq + 0], active_kv[tq + 1]), - std::max(active_kv[tq + 2], active_kv[tq + 3])); + tq = 0; + for (; tq + 3 < tile_rows; tq += 4) { + if (skip[tq + 0] || skip[tq + 1] || skip[tq + 2] || skip[tq + 3]) { for (int i = 0; i < 4; ++i) { - std::fill(KQ + (tq + i) * KV_TILE_SZ + active_kv[tq + i], - KQ + (tq + i) * KV_TILE_SZ + group_active, 0.0f); - } - rvv_pv_accumulate_f16_x4(VKQ32 + (tq + 0) * DV, VKQ32 + (tq + 1) * DV, VKQ32 + (tq + 2) * DV, - VKQ32 + (tq + 3) * DV, KQ + (tq + 0) * KV_TILE_SZ, - KQ + (tq + 1) * KV_TILE_SZ, KQ + (tq + 2) * KV_TILE_SZ, - KQ + (tq + 3) * KV_TILE_SZ, V_f16, group_active, DV); - } - for (; tq < tile_rows; ++tq) { - if (!skip[tq]) { - rvv_pv_accumulate_f16_x1(VKQ32 + tq * DV, KQ + tq * KV_TILE_SZ, V_f16, active_kv[tq], DV); + if (!skip[tq + i]) { + rvv_pv_accumulate_f16_x1(VKQ32 + (tq + i) * DV, KQ + (tq + i) * KV_TILE_SZ, V_f16, + active_kv[tq + i], DV); + } } + continue; } - } else { - const char * v_data = (const char *) v->data + ic * nbv1 + iv2 * nbv2 + iv3 * nbv3; - memcpy2d(V32, DV * sizeof(float), v_data, nbv1, max_active_kv, DV * sizeof(float)); - for (int tq = 0; tq < tile_rows; ++tq) { - if (!skip[tq]) { - rvv_pv_accumulate(VKQ32 + tq * DV, KQ + tq * KV_TILE_SZ, V32, active_kv[tq], DV); - } + const int group_active = std::max(std::max(active_kv[tq + 0], active_kv[tq + 1]), + std::max(active_kv[tq + 2], active_kv[tq + 3])); + for (int i = 0; i < 4; ++i) { + std::fill(KQ + (tq + i) * KV_TILE_SZ + active_kv[tq + i], + KQ + (tq + i) * KV_TILE_SZ + group_active, 0.0f); } + rvv_pv_accumulate_f16_x4(VKQ32 + (tq + 0) * DV, VKQ32 + (tq + 1) * DV, VKQ32 + (tq + 2) * DV, + VKQ32 + (tq + 3) * DV, KQ + (tq + 0) * KV_TILE_SZ, + KQ + (tq + 1) * KV_TILE_SZ, KQ + (tq + 2) * KV_TILE_SZ, + KQ + (tq + 3) * KV_TILE_SZ, V_f16, group_active, DV); } - } - - // sinks (apply only to valid rows in the tile) - if (sinks) { - const float s = ((float *) ((char *) sinks->data))[h]; - - for (int tq = 0; tq < tile_rows; tq++) { - float ms = 1.0f; - float vs = 1.0f; - - if (s > M[tq]) { - ms = expf(M[tq] - s); - rvv_scale_f32(VKQ32 + tq * DV, ms, DV); - } else { - vs = expf(s - M[tq]); + for (; tq < tile_rows; ++tq) { + if (!skip[tq]) { + rvv_pv_accumulate_f16_x1(VKQ32 + tq * DV, KQ + tq * KV_TILE_SZ, V_f16, active_kv[tq], DV); } - - float S_temp = S[tq] * ms + vs; - S[tq] = S_temp == 0.0f ? 0.0f : 1.0f / S_temp; - } - } else { - for (int tq = 0; tq < tile_rows; tq++) { - const float S_inv = S[tq] == 0.0f ? 0.0f : 1.0f / S[tq]; - S[tq] = S_inv; } } - float * dst_ptr = (float *) ((char *) dst->data + (iq3 * ne2 * ne1 + iq2 + (iq1) *ne1) * nb1); - rvv_pack_scaled_f32_as_f32(dst_ptr, nb1 * ne1, VKQ32, DV * sizeof(float), tile_rows, DV, S); + const float * sink = sinks ? (const float *) sinks->data + h : nullptr; + float * dst_ptr = (float *) ((char *) dst->data + (iq3 * ne2 * ne1 + iq2 + iq1 * ne1) * nb1); + fa_store_tile(dst_ptr, nb1 * ne1, VKQ32, DV, tile_rows, M, S, sink); ir += tile_rows; } diff --git a/ggml/src/ggml-spacemit/rvv_kernels.h b/ggml/src/ggml-spacemit/rvv_kernels.h index 2d8a757e94df..797ceb0d994d 100644 --- a/ggml/src/ggml-spacemit/rvv_kernels.h +++ b/ggml/src/ggml-spacemit/rvv_kernels.h @@ -3,11 +3,14 @@ #include "spacemit-context.h" #include +#include #include #include #include #include +#include + namespace spacemit_kernels { template constexpr auto div_round_up(T up, U down) { @@ -58,6 +61,305 @@ constexpr size_t q8_m4al_row_blk_size = q8_m4al_blk_size / 4; static_assert(q8_m4al_hdr_size == 64 && q8_m4al_blk_size == 192, "i8i8 group layout"); namespace rvv { + +namespace detail { + +inline size_t fa_tiled_thread_bytes(const ggml_tensor * dst, size_t qt, size_t kt) { + const size_t dk = dst->src[1]->ne[0], dv = dst->src[2]->ne[0]; + const size_t scalar = dst->src[1]->type == GGML_TYPE_F16 ? sizeof(_Float16) : sizeof(float); + return (qt * dk + kt * (dk + dv)) * scalar + + (2 * qt * kt + qt * dv + ggml::spacemit::cache_line_size_f32) * sizeof(float); +} + +inline void rvv_fill_f16(_Float16 * dst, float value, int64_t n) { + for (int64_t d0 = 0; d0 < n;) { + const size_t vl = __riscv_vsetvl_e16m2(n - d0); + __riscv_vse16_v_f16m2(dst + d0, __riscv_vfmv_v_f_f16m2((_Float16) value, vl), vl); + d0 += vl; + } +} + +inline float reduce_sum_f32m2_vlen1024(vfloat32m2_t v, size_t vl) { + vfloat32m1_t s_v = __riscv_vfmv_v_f_f32m1(0.0f, 1); + s_v = __riscv_vfredusum_vs_f32m2_f32m1(v, s_v, vl); + return __riscv_vfmv_f_s_f32m1_f32(s_v); +} + +// Adapted from ggml_v_expf_m2 in vec.h. This is accurate enough for softmax. +inline vfloat32m2_t rvv_expf_approx_f32m2(vfloat32m2_t x, size_t vl) { + const vfloat32m2_t r = __riscv_vfmv_v_f_f32m2(0x1.8p23f, vl); + const vfloat32m2_t z = __riscv_vfmacc_vf_f32m2(r, 0x1.715476p+0f, x, vl); + const vfloat32m2_t n = __riscv_vfsub_vv_f32m2(z, r, vl); + const vfloat32m2_t b = + __riscv_vfnmsac_vf_f32m2(__riscv_vfnmsac_vf_f32m2(x, 0x1.62e4p-1f, n, vl), 0x1.7f7d1cp-20f, n, vl); + const vuint32m2_t e = __riscv_vsll_vx_u32m2(__riscv_vreinterpret_v_f32m2_u32m2(z), 23, vl); + const vfloat32m2_t k = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vadd_vx_u32m2(e, 0x3f800000, vl)); + const vbool16_t c = __riscv_vmfgt_vf_f32m2_b16(__riscv_vfabs_v_f32m2(n, vl), 126.0f, vl); + const vfloat32m2_t u = __riscv_vfmul_vv_f32m2(b, b, vl); + const vfloat32m2_t j = __riscv_vfmacc_vv_f32m2( + __riscv_vfmul_vf_f32m2(b, 0x1.ffffecp-1f, vl), + __riscv_vfmacc_vv_f32m2( + __riscv_vfmacc_vf_f32m2(__riscv_vfmv_v_f_f32m2(0x1.fffdb6p-2f, vl), 0x1.555e66p-3f, b, vl), + __riscv_vfmacc_vf_f32m2(__riscv_vfmv_v_f_f32m2(0x1.573e2ep-5f, vl), 0x1.0e4020p-7f, b, vl), u, vl), + u, vl); + + if (!__riscv_vcpop_m_b16(c, vl)) { + return __riscv_vfmacc_vv_f32m2(k, j, k, vl); + } + + const vbool16_t dm = __riscv_vmfle_vf_f32m2_b16(n, 0.0f, vl); + const vuint32m2_t d = __riscv_vmerge_vxm_u32m2(__riscv_vmv_v_x_u32m2(0, vl), 0x82000000, dm, vl); + const vfloat32m2_t s1 = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vadd_vx_u32m2(d, 0x7f000000, vl)); + const vfloat32m2_t s2 = __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vsub_vv_u32m2(e, d, vl)); + const vfloat32m2_t r1 = + __riscv_vmerge_vvm_f32m2(__riscv_vfmacc_vv_f32m2(k, k, j, vl), + __riscv_vfmul_vv_f32m2(__riscv_vfmacc_vv_f32m2(s2, s2, j, vl), s1, vl), c, vl); + return __riscv_vmerge_vvm_f32m2(r1, __riscv_vfmul_vv_f32m2(s1, s1, vl), + __riscv_vmfgt_vf_f32m2_b16(__riscv_vfabs_v_f32m2(n, vl), 192.0f, vl), vl); +} + +inline vfloat32m2_t rvv_tanh_approx_f32m2(vfloat32m2_t x, size_t vl) { + const vfloat32m2_t abs_x = __riscv_vfabs_v_f32m2(x, vl); + const vfloat32m2_t neg_2_abs = __riscv_vfmul_vf_f32m2(abs_x, -2.0f, vl); + const vfloat32m2_t exp_term = rvv_expf_approx_f32m2(neg_2_abs, vl); + const vfloat32m2_t numerator = __riscv_vfsub_vf_f32m2(exp_term, 1.0f, vl); + const vfloat32m2_t denominator = __riscv_vfadd_vf_f32m2(exp_term, 1.0f, vl); + const vfloat32m2_t tanh_abs = __riscv_vfneg_v_f32m2(__riscv_vfdiv_vv_f32m2(numerator, denominator, vl), vl); + const vbool16_t neg_mask = __riscv_vmflt_vf_f32m2_b16(x, 0.0f, vl); + const vfloat32m2_t tanh_neg = __riscv_vfneg_v_f32m2(tanh_abs, vl); + return __riscv_vmerge_vvm_f32m2(tanh_abs, tanh_neg, neg_mask, vl); +} + +inline void rvv_softcap_tanh_inplace_f32(float * dst, int64_t dst_stride, int64_t tile_rows, int64_t n, float softcap) { + for (int tq = 0; tq < tile_rows; ++tq, dst += dst_stride) { + float * dst_row = dst; + int64_t remaining = n; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m2(remaining); + vfloat32m2_t v = __riscv_vle32_v_f32m2(dst_row, vl); + v = rvv_tanh_approx_f32m2(v, vl); + v = __riscv_vfmul_vf_f32m2(v, softcap, vl); + __riscv_vse32_v_f32m2(dst_row, v, vl); + dst_row += vl; + remaining -= vl; + } + } +} + +inline float rvv_softmax_exp_inplace_f32(float * dst, int64_t n, float max_value) { + float row_sum = 0.0f; + while (n > 0) { + const size_t vl = __riscv_vsetvl_e32m2(n); + vfloat32m2_t v = __riscv_vle32_v_f32m2(dst, vl); + v = __riscv_vfsub_vf_f32m2(v, max_value, vl); + v = rvv_expf_approx_f32m2(v, vl); + __riscv_vse32_v_f32m2(dst, v, vl); + row_sum += reduce_sum_f32m2_vlen1024(v, vl); + dst += vl; + n -= vl; + } + return row_sum; +} + +inline void rvv_zero_f32(float * dst, int64_t n) { + while (n > 0) { + const size_t vl = __riscv_vsetvl_e32m4(n); + const vfloat32m4_t z = __riscv_vfmv_v_f_f32m4(0.0f, vl); + __riscv_vse32_v_f32m4(dst, z, vl); + dst += vl; + n -= vl; + } +} + +inline void rvv_scale_f32(float * dst, float scale, int64_t n) { + while (n > 0) { + const size_t vl = __riscv_vsetvl_e32m4(n); + vfloat32m4_t v = __riscv_vle32_v_f32m4(dst, vl); + v = __riscv_vfmul_vf_f32m4(v, scale, vl); + __riscv_vse32_v_f32m4(dst, v, vl); + dst += vl; + n -= vl; + } +} + +inline void rvv_add_inplace_f32(float * dst, + int64_t dst_stride, + const float * src, + int64_t src_stride, + int64_t tile_rows, + int64_t n) { + for (int tq = 0; tq < tile_rows; ++tq, dst += dst_stride, src += src_stride) { + int64_t remaining = n; + float * dst_row = dst; + const float * src_row = src; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t vdst = __riscv_vle32_v_f32m4(dst_row, vl); + vfloat32m4_t vsrc = __riscv_vle32_v_f32m4(src_row, vl); + vdst = __riscv_vfadd_vv_f32m4(vdst, vsrc, vl); + __riscv_vse32_v_f32m4(dst_row, vdst, vl); + dst_row += vl; + src_row += vl; + remaining -= vl; + } + } +} + +inline float rvv_max_f32(const float * src, int64_t n) { + float max_val = -INFINITY; + while (n > 0) { + const size_t vl = __riscv_vsetvl_e32m4(n); + const vfloat32m4_t v = __riscv_vle32_v_f32m4(src, vl); + vfloat32m1_t seed = __riscv_vfmv_v_f_f32m1(max_val, 1); + seed = __riscv_vfredmax_vs_f32m4_f32m1(v, seed, vl); + max_val = __riscv_vfmv_f_s_f32m1_f32(seed); + src += vl; + n -= vl; + } + return max_val; +} + +inline void rvv_pack_f32_as_scaled_f16(void * dst, + int64_t dst_row_stride, + const void * src, + int64_t src_row_stride, + int64_t tile_rows, + int64_t n, + float scale) { + for (int tq = 0; tq < tile_rows; ++tq) { + const float * row_ptr = (const float *) ((const char *) src + tq * src_row_stride); + _Float16 * dst_row_ptr = (_Float16 *) ((char *) dst + tq * dst_row_stride); + int64_t remaining = n; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t v32 = __riscv_vle32_v_f32m4(row_ptr, vl); + v32 = __riscv_vfmul_vf_f32m4(v32, scale, vl); + const vfloat16m2_t v16 = __riscv_vfncvt_f_f_w_f16m2(v32, vl); + __riscv_vse16_v_f16m2(dst_row_ptr, v16, vl); + dst_row_ptr += vl; + row_ptr += vl; + remaining -= vl; + } + } +} + +inline void rvv_pack_scaled_f16_as_f32(void * dst, + int64_t dst_row_stride, + const void * src, + int64_t src_row_stride, + int64_t tile_rows, + int64_t n, + float scale) { + for (int tq = 0; tq < tile_rows; ++tq) { + const _Float16 * row_ptr = (const _Float16 *) ((const char *) src + tq * src_row_stride); + float * dst_row_ptr = (float *) ((char *) dst + tq * dst_row_stride); + int64_t remaining = n; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e16m2(remaining); + const vfloat16m2_t v16 = __riscv_vle16_v_f16m2(row_ptr, vl); + vfloat32m4_t v32 = __riscv_vfwcvt_f_f_v_f32m4(v16, vl); + v32 = __riscv_vfmul_vf_f32m4(v32, scale, vl); + __riscv_vse32_v_f32m4(dst_row_ptr, v32, vl); + dst_row_ptr += vl; + row_ptr += vl; + remaining -= vl; + } + } +} + +inline void rvv_pack_scaled_f32_as_f32(void * dst, + int64_t dst_row_stride, + const void * src, + int64_t src_row_stride, + int64_t tile_rows, + int64_t n, + float * scale) { + for (int tq = 0; tq < tile_rows; ++tq) { + const float * row_ptr = (const float *) ((const char *) src + tq * src_row_stride); + float * dst_row_ptr = (float *) ((char *) dst + tq * dst_row_stride); + int64_t remaining = n; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t v32 = __riscv_vle32_v_f32m4(row_ptr, vl); + v32 = __riscv_vfmul_vf_f32m4(v32, scale[tq], vl); + __riscv_vse32_v_f32m4(dst_row_ptr, v32, vl); + dst_row_ptr += vl; + row_ptr += vl; + remaining -= vl; + } + } +} + +inline void fa_update_softmax(float * kq, const float * mask32, bool has_mask, float logit_softcap, + const int * active_kv, bool * skip, int tile_rows, int kv_stride, int64_t dv, + float * M, float * S, float * VKQ32) { + for (int tq = 0; tq < tile_rows; tq++) { + float * kq_row = kq + tq * kv_stride; + const int row_active = active_kv[tq]; + + if (row_active == 0) { + skip[tq] = true; + continue; + } + + if (logit_softcap != 0.0f) { + rvv_softcap_tanh_inplace_f32(kq_row, kv_stride, 1, row_active, logit_softcap); + } + if (has_mask) { + rvv_add_inplace_f32(kq_row, kv_stride, mask32 + tq * kv_stride, kv_stride, 1, row_active); + } + + const float tile_max = rvv_max_f32(kq_row, row_active); + + if (tile_max == -INFINITY) { + skip[tq] = true; + continue; + } + + const float Mold = M[tq]; + const float Mnew = fmaxf(Mold, tile_max); + + if (Mnew > Mold) { + const float ms = expf(Mold - Mnew); + rvv_scale_f32(VKQ32 + tq * dv, ms, dv); + S[tq] *= ms; + } + M[tq] = Mnew; + + S[tq] += rvv_softmax_exp_inplace_f32(kq_row, row_active, Mnew); + } +} + +inline void fa_store_tile(float * dst, int64_t dst_stride, float * VKQ32, int64_t dv, int tile_rows, + const float * M, float * S, const float * sink) { + if (sink) { + const float s = *sink; + + for (int tq = 0; tq < tile_rows; tq++) { + float ms = 1.0f; + float vs = 1.0f; + + if (s > M[tq]) { + ms = expf(M[tq] - s); + rvv_scale_f32(VKQ32 + tq * dv, ms, dv); + } else { + vs = expf(s - M[tq]); + } + + float S_temp = S[tq] * ms + vs; + S[tq] = S_temp == 0.0f ? 0.0f : 1.0f / S_temp; + } + } else { + for (int tq = 0; tq < tile_rows; tq++) { + const float S_inv = S[tq] == 0.0f ? 0.0f : 1.0f / S[tq]; + S[tq] = S_inv; + } + } + + rvv_pack_scaled_f32_as_f32(dst, dst_stride, VKQ32, dv * sizeof(float), tile_rows, dv, S); +} + +} // namespace detail void quantize_a_i8_r4_al(size_t blk_len, const float * a_ptr, size_t count_k, uint8_t * quant_a_ptr); void quantize_a_i8_r4_hp_al(size_t blk_len, const float * a_ptr, size_t count_k, uint8_t * quant_a_ptr); void quantize_a_i8_r8_hp(size_t blk_len, const float * a_ptr, size_t count_k, uint8_t * quant_a_ptr); @@ -84,10 +386,12 @@ void forward_flash_attn_ext_f16_split_kv_reduce_vlen1024_vf16(ggml::spacemit::co int n_chunks, const float * partials); -void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(ggml::spacemit::context & ctx, - ggml_tensor * dst, - int ir0, - int ir1); +size_t flash_attn_ext_f16_tiled_workspace_size(const ggml_tensor * dst, int nth); + +void forward_flash_attn_ext_f16_tiled_rvv(ggml::spacemit::context & ctx, + ggml_tensor * dst, + int ir0, + int ir1); void forward_rms_norm_f32(ggml::spacemit::context & ctx, ggml_tensor * op);