diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 45fc50dcefc..15bfb2013de 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -2132,7 +2132,7 @@ jobs: PYTHON_EXECUTABLE=python bash backends/vulkan/test/ops/benchmark_v2/build.sh for op in binary/add gemm/linear/qw/q8csw convolution/qw/q8csw gemm/linear/qw/q4gsw \ quantization/choose_qparams_per_row quantize/q8ta clone/q8ta binary/q8ta \ - warp; do + warp attention/sdpa; do ./cmake-out/backends/vulkan/test/ops/benchmark_v2/etvk_ops_bench --validation_only \ --config=backends/vulkan/test/ops/benchmark_v2/operators/${op}/cases/correctness.json done diff --git a/.github/workflows/vulkan.yml b/.github/workflows/vulkan.yml index ec81451f6cd..ce1d8472293 100644 --- a/.github/workflows/vulkan.yml +++ b/.github/workflows/vulkan.yml @@ -124,7 +124,7 @@ jobs: PYTHON_EXECUTABLE=python bash backends/vulkan/test/ops/benchmark_v2/build.sh for op in binary/add gemm/linear/qw/q8csw convolution/qw/q8csw gemm/linear/qw/q4gsw \ quantization/choose_qparams_per_row quantize/q8ta clone/q8ta binary/q8ta \ - warp; do + warp attention/sdpa; do ./cmake-out/backends/vulkan/test/ops/benchmark_v2/etvk_ops_bench --validation_only \ --config=backends/vulkan/test/ops/benchmark_v2/operators/${op}/cases/correctness.json done diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl index 23206b9bb54..591e7e5b892 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl @@ -42,11 +42,6 @@ $if MODE == "llm": layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; -// Shared memory for cooperative max finding and exp sum reduction. -// For fused SDPA, reductions happen in fp32 for numerical stability. -shared SOFTMAX_ACC_T shared_max[NUM_WORKERS_PER_WG]; -shared SOFTMAX_ACC_T shared_exp_sum[NUM_WORKERS_PER_WG]; - SOFTMAX_IN_VEC4_T load_attn_weights_c4( const int c4, const int s, @@ -76,6 +71,13 @@ void store_attn_weights_softmax_c4( #endif } +#ifndef HAS_INPUT_POS +// ATen's safe softmax returns zero for rows masked entirely with -inf. +#define SOFTMAX_ZERO_FULLY_MASKED_ROWS +#endif + +#include "sdpa_attn_weights_softmax_row.glslh" + /* * 3-pass numerically stable softmax over the context_len dimension of * attention weights. @@ -119,7 +121,6 @@ void main() { #else const int context_len = k_sizes.y; #endif - const int context_texel_len = div_up_4(context_len); // LLM: attn_weights S dim is padded to S_aligned; fused: not padded. #ifdef HAS_INPUT_POS @@ -134,142 +135,5 @@ void main() { return; } - const int context_len_aligned_down = context_len - mod_4(context_len); - const int C4_limit = div_4(context_len_aligned_down); - - // ========================================================================= - // Pass 1: Find the maximum value across the row for numerical stability. - // Without this, exp(x) can overflow float32 when x > ~88.7. - // ========================================================================= - - SOFTMAX_ACC_T local_max = SOFTMAX_ACC_T(-1.0 / 0.0); // -infinity - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - for (int comp = 0; comp < 4; comp++) { - local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); - } - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); - } - } - } - } - - shared_max[worker_id] = local_max; - - memoryBarrierShared(); - barrier(); - - // Tree reduction to find the global max - for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { - if (worker_id < i) { - shared_max[worker_id] = max( - shared_max[worker_id], shared_max[worker_id + i]); - } - memoryBarrierShared(); - barrier(); - } - - const SOFTMAX_ACC_T global_max = shared_max[0]; - -#ifndef HAS_INPUT_POS - // ATen's safe softmax returns zero for rows masked entirely with -inf. - if (global_max == SOFTMAX_ACC_T(-1.0 / 0.0)) { - for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_WG) { - store_attn_weights_softmax_c4( - VEC4_T(0), c4, s, q_h, context_texel_len, attn_S, Q_H); - } - return; - } -#endif - - // ========================================================================= - // Pass 2: Compute sum(exp(x - max)) using the global max for stability - // ========================================================================= - - SOFTMAX_ACC_T local_exp_sum = SOFTMAX_ACC_T(0); - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - for (int comp = 0; comp < 4; comp++) { - local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); - } - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); - } - } - } - } - - shared_exp_sum[worker_id] = local_exp_sum; - - memoryBarrierShared(); - barrier(); - - // Tree reduction to compute the overall exp sum - for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { - if (worker_id < i) { - shared_exp_sum[worker_id] = shared_exp_sum[worker_id] + - shared_exp_sum[worker_id + i]; - } - memoryBarrierShared(); - barrier(); - } - - local_exp_sum = shared_exp_sum[0]; - - // ========================================================================= - // Pass 3: Normalize each element: out = exp(x - max) / sum(exp(x - max)) - // ========================================================================= - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - VEC4_T out_texel; - [[unroll]] for (int comp = 0; comp < 4; comp++) { - out_texel[comp] = T( - exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); - } - store_attn_weights_softmax_c4( - out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - VEC4_T out_texel = VEC4_T(0); - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - out_texel[comp] = T( - exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); - } - } - store_attn_weights_softmax_c4( - out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); - } - } + softmax_attn_weights_row(worker_id, s, q_h, context_len, attn_S, Q_H); } diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh new file mode 100644 index 00000000000..735e9b2c2e1 --- /dev/null +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh @@ -0,0 +1,193 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* + * Cooperative softmax over one row of attention weights, shared by the + * standalone softmax shader and the fused QK + softmax variant of the coop + * attention weights shader. + * + * Required macros: + * NUM_WORKERS_PER_WG - number of invocations in the work group + * SOFTMAX_IN_VEC4_T - texel type returned by load_attn_weights_c4 + * SOFTMAX_ACC_T - scalar type the max and exp sum are reduced in + * VEC4_T, T - texel and scalar type of the softmax output + * + * Required functions, defined before including this file: + * SOFTMAX_IN_VEC4_T load_attn_weights_c4(c4, s, q_h, C4, S, Q_H) + * void store_attn_weights_softmax_c4(VEC4_T, c4, s, q_h, C4, S, Q_H) + * + * Optional macros: + * SOFTMAX_ZERO_FULLY_MASKED_ROWS - write zeros for a row whose elements are + * all -inf, as ATen's safe softmax does, + * instead of NaN + */ + +#ifndef SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH +#define SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH + +#extension GL_EXT_control_flow_attributes : require + +// Shared memory for cooperative max finding and exp sum reduction. +// For fused SDPA, reductions happen in fp32 for numerical stability. +shared SOFTMAX_ACC_T shared_max[NUM_WORKERS_PER_WG]; +shared SOFTMAX_ACC_T shared_exp_sum[NUM_WORKERS_PER_WG]; + +/* + * 3-pass numerically stable softmax over the first context_len elements of + * row (s, q_h). attn_S is the S extent of the attention weight tensors. Every + * invocation of the work group must call this, since it contains barriers. + */ +void softmax_attn_weights_row( + const int worker_id, + const int s, + const int q_h, + const int context_len, + const int attn_S, + const int Q_H) { + const int context_texel_len = div_up_4(context_len); + + const int context_len_aligned_down = context_len - mod_4(context_len); + const int C4_limit = div_4(context_len_aligned_down); + + // ========================================================================= + // Pass 1: Find the maximum value across the row for numerical stability. + // Without this, exp(x) can overflow float32 when x > ~88.7. + // ========================================================================= + + SOFTMAX_ACC_T local_max = SOFTMAX_ACC_T(-1.0 / 0.0); // -infinity + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + for (int comp = 0; comp < 4; comp++) { + local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); + } + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); + } + } + } + } + + shared_max[worker_id] = local_max; + + memoryBarrierShared(); + barrier(); + + // Tree reduction to find the global max + for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { + if (worker_id < i) { + shared_max[worker_id] = max( + shared_max[worker_id], shared_max[worker_id + i]); + } + memoryBarrierShared(); + barrier(); + } + + const SOFTMAX_ACC_T global_max = shared_max[0]; + +#ifdef SOFTMAX_ZERO_FULLY_MASKED_ROWS + if (global_max == SOFTMAX_ACC_T(-1.0 / 0.0)) { + for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_WG) { + store_attn_weights_softmax_c4( + VEC4_T(0), c4, s, q_h, context_texel_len, attn_S, Q_H); + } + return; + } +#endif + + // ========================================================================= + // Pass 2: Compute sum(exp(x - max)) using the global max for stability + // ========================================================================= + + SOFTMAX_ACC_T local_exp_sum = SOFTMAX_ACC_T(0); + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + for (int comp = 0; comp < 4; comp++) { + local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); + } + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); + } + } + } + } + + shared_exp_sum[worker_id] = local_exp_sum; + + memoryBarrierShared(); + barrier(); + + // Tree reduction to compute the overall exp sum + for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { + if (worker_id < i) { + shared_exp_sum[worker_id] = shared_exp_sum[worker_id] + + shared_exp_sum[worker_id + i]; + } + memoryBarrierShared(); + barrier(); + } + + local_exp_sum = shared_exp_sum[0]; + + // ========================================================================= + // Pass 3: Normalize each element: out = exp(x - max) / sum(exp(x - max)) + // ========================================================================= + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + VEC4_T out_texel; + [[unroll]] for (int comp = 0; comp < 4; comp++) { + out_texel[comp] = T( + exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); + } + store_attn_weights_softmax_c4( + out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + VEC4_T out_texel = VEC4_T(0); + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + out_texel[comp] = T( + exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); + } + } + store_attn_weights_softmax_c4( + out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); + } + } +} + +#endif // SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl index fe9e262a79a..79313281e64 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl @@ -31,6 +31,13 @@ $if K_CACHE_STORAGE == "buffer": #define NUM_WORKERS_PER_OUT 64 +$if FUSE_SOFTMAX: + #define FUSE_SOFTMAX + // Cap on the attn_weights row held in shared memory, in texels. The host only + // selects this variant when the context fits within this bound (see + // use_fused_qk_softmax() in SDPA.cpp); a longer context writes nothing. + #define MAX_CONTEXT_TEXEL_LEN ${MAX_CONTEXT_TEXEL_LEN} + ${define_required_extensions(IO_STORAGE, DTYPE)} layout(std430) buffer; @@ -54,62 +61,75 @@ ${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} #include "gemm/tile_utils/linear_fp_output_tile_fp_compute.glslh" #include "sdpa_fp_attn_weight_tile_store.glslh" -shared FPOutTile partial_sums[NUM_WORKERS_PER_OUT]; +#ifdef FUSE_SOFTMAX + +// The scaled and masked attn_weights row, one array per texel component, so +// that the workers, which each own one texel, access consecutive words. +shared T row_attn_w_x[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_y[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_z[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_w[MAX_CONTEXT_TEXEL_LEN]; + +#define NUM_WORKERS_PER_WG NUM_WORKERS_PER_OUT +#define SOFTMAX_IN_VEC4_T VEC4_T +#define SOFTMAX_ACC_T T + +// The softmax reads the row back from shared memory... +VEC4_T load_attn_weights_c4( + const int c4, + const int s, + const int q_h, + const int C4, + const int S, + const int Q_H) { + return VEC4_T( + row_attn_w_x[c4], row_attn_w_y[c4], row_attn_w_z[c4], row_attn_w_w[c4]); +} -/* - * See the tiled variant of this shader for the implemented behavior. This - * shader is implements an optimization for cases where sequence length is 1; in - * these cases, the matrix multiplication being performed is akin to gemv, which - * benefits from using a co-operative algorithm for reduction. For this shader - * the entire work group co-operates to compute one reduction output. - */ +// ...and writes the normalized weights to t_attn_weights. +void store_attn_weights_softmax_c4( + const VEC4_T out_texel, + const int c4, + const int s, + const int q_h, + const int C4, + const int S, + const int Q_H) { + store_attn_weight_c4(out_texel, c4, s, q_h, C4, S, Q_H); +} -void main() { - const int worker_id = int(gl_LocalInvocationID.y); +#include "sdpa_attn_weights_softmax_row.glslh" - const int tile_idx_x = int(gl_GlobalInvocationID.x); - // idx along output num_q_heads dim - const int q_h = int(gl_GlobalInvocationID.z); +#else - // idx along the output context_len dim - const int c = tile_idx_x * TILE_N; - const int c4 = div_4(c); +shared FPOutTile partial_sums[NUM_WORKERS_PER_OUT]; - // idx along the output seq_len dim. Note that for this shader seq_len will be - // 1. - const int s = 0; +#endif - // head dimension +/* + * Accumulates Q @ K^T for the attn_weights tile at (c, s, q_h) over the head + * dim texels d4_start, d4_start + d4_step, ... A tile entirely inside the + * causal mask is set to negative infinity instead, and true is returned, in + * which case no scale or mask needs to be applied to it. + */ +bool compute_attn_weight_tile( + out FPOutTile out_tile, + const int d4_start, + const int d4_step, + const int c, + const int s, + const int q_h, + const int kv_h, + const int context_len) { + // head dim, sequence length, number of Q heads, max context length and + // number of K heads const int D = q_sizes.x; - // texel size of head_dim, over which the dot product is accumulated const int D4 = div_up_4(D); - // number of Q heads - const int Q_H = q_sizes.y; - // sequence length const int S = q_sizes.z; - const int S_aligned = align_up_4(S); - - // number of K/V heads - const int KV_H = k_sizes.y; - // Max context length + const int Q_H = q_sizes.y; const int C = k_sizes.z; - const int C4 = div_up_4(C); - - int kv_h = q_h; - if (KV_H < Q_H) { - kv_h = q_h / (Q_H / KV_H); - } - - // current context length - const int context_len = input_pos + S; - const int context_texel_len = div_up_4(context_len); - - // bounds check - if (c >= context_len || s >= S || q_h >= Q_H) { - return; - } + const int KV_H = k_sizes.y; - FPOutTile out_tile; initialize(out_tile); FPInputTile q_tile; @@ -125,7 +145,7 @@ void main() { } // Otherwise, need to actually compute output tile else { - for (int d4 = worker_id; d4 < D4; d4 += NUM_WORKERS_PER_OUT) { + for (int d4 = d4_start; d4 < D4; d4 += d4_step) { load_q_projected_tile_with_checks( q_tile, d4, @@ -145,8 +165,8 @@ void main() { C, KV_H); - // Each worker covers about one d4, so checking for the partial last - // vec4 in the loop is cheap. + // The coop path's workers each cover about one d4, so checking for the + // partial last vec4 in the loop is cheap. if (mul_4(d4) + 4 > D) { mask_q_projected_tile_d_tail(q_tile, d4, D); mask_k_cache_tile_d_tail(w_tile, d4, D); @@ -155,6 +175,113 @@ void main() { fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); } } + return tile_in_mask_region; +} + +/* + * See the tiled variant of this shader for the implemented behavior. This + * shader is implements an optimization for cases where sequence length is 1; in + * these cases, the matrix multiplication being performed is akin to gemv, which + * benefits from using a co-operative algorithm for reduction. For this shader + * the entire work group co-operates to compute one reduction output. + * + * The FUSE_SOFTMAX variant instead dispatches one work group per (s, q_h) row. + * Each worker computes whole texels of the row, which is kept in shared memory + * so that the work group can apply the softmax and write normalized weights + * directly. That saves the separate softmax dispatch and the round trip of + * attn_weights through global memory, at the cost of parallelism along the + * context dim, so the host only selects it for short contexts. + */ + +void main() { +#ifdef FUSE_SOFTMAX + const int worker_id = int(gl_LocalInvocationID.x); + + // idx along the output seq_len dim + const int s = int(gl_GlobalInvocationID.y); +#else + const int worker_id = int(gl_LocalInvocationID.y); + + const int tile_idx_x = int(gl_GlobalInvocationID.x); + + // idx along the output context_len dim + const int c = tile_idx_x * TILE_N; + const int c4 = div_4(c); + + // idx along the output seq_len dim. Note that for this shader seq_len will be + // 1. + const int s = 0; +#endif + // idx along output num_q_heads dim + const int q_h = int(gl_GlobalInvocationID.z); + + // number of Q heads + const int Q_H = q_sizes.y; + // sequence length + const int S = q_sizes.z; + const int S_aligned = align_up_4(S); + + // number of K/V heads + const int KV_H = k_sizes.y; + + int kv_h = q_h; + if (KV_H < Q_H) { + kv_h = q_h / (Q_H / KV_H); + } + + // current context length + const int context_len = input_pos + S; + const int context_texel_len = div_up_4(context_len); + +#ifdef FUSE_SOFTMAX + // bounds check. A context longer than the shared row is never selected by + // the host; if it is dispatched anyway, write nothing rather than overrun the + // row. s and q_h are uniform over the work group, so the whole work group + // returns together and the barriers below stay uniform. + if (s >= S || q_h >= Q_H || context_texel_len > MAX_CONTEXT_TEXEL_LEN) { + return; + } + + // Compute the row into shared memory; worker w owns c4 = w, w + 64, ... + for (int c4 = worker_id; c4 < context_texel_len; + c4 += NUM_WORKERS_PER_OUT) { + const int c = mul_4(c4); + + FPOutTile out_tile; + const bool tile_in_mask_region = compute_attn_weight_tile( + out_tile, 0, 1, c, s, q_h, kv_h, context_len); + if (!tile_in_mask_region) { + VEC4_T inv_scale_vec = VEC4_T(inv_scale); + apply_scale_and_mask(out_tile, inv_scale_vec, input_pos, c, s); + } + + // TILE_M and TILE_N4 are 1, so the tile holds a single texel. + row_attn_w_x[c4] = out_tile.data[0][0].x; + row_attn_w_y[c4] = out_tile.data[0][0].y; + row_attn_w_z[c4] = out_tile.data[0][0].z; + row_attn_w_w[c4] = out_tile.data[0][0].w; + } + + memoryBarrierShared(); + barrier(); + + softmax_attn_weights_row(worker_id, s, q_h, context_len, S_aligned, Q_H); +#else + // bounds check + if (c >= context_len || s >= S || q_h >= Q_H) { + return; + } + + FPOutTile out_tile; + const bool tile_in_mask_region = compute_attn_weight_tile( + out_tile, + worker_id, + NUM_WORKERS_PER_OUT, + c, + s, + q_h, + kv_h, + context_len); partial_sums[worker_id] = out_tile; @@ -194,4 +321,5 @@ void main() { S_aligned, Q_H); } +#endif } diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml index d5cadc36060..482cc307488 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml @@ -11,6 +11,10 @@ sdpa_compute_attn_weights_coop: K_CACHE_STORAGE: texture3d TILE_K4: 1 TILE_N4: 1 + FUSE_SOFTMAX: false + # Shared attn_weights row of the FUSE_SOFTMAX variant, in texels. Must equal + # kFusedSoftmaxMaxContextTexels in SDPA.cpp. + MAX_CONTEXT_TEXEL_LEN: 64 generate_variant_forall: combination: parameter_names: [IO_STORAGE, K_CACHE_STORAGE] @@ -23,3 +27,5 @@ sdpa_compute_attn_weights_coop: - VALUE: half shader_variants: - NAME: sdpa_compute_attn_weights_coop + - NAME: sdpa_compute_attn_weights_coop_softmax + FUSE_SOFTMAX: true diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index ea0b2cea7b5..5cd25769ae0 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -77,6 +77,39 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { return graph->size_at(-3, q_projected) == 1; } +// Context length past which the separate attn-weights and softmax pair is +// faster than the fused dispatch. The fused shader reduces the whole row +// inside one work group, so its parallelism is capped at num_q_heads work +// groups; the separate pair spreads the same work over one work group per +// context texel. Below the cutoff the saved dispatch and the saved round trip +// of attn_weights through global memory dominate; above it the lost +// parallelism does. Measured on Adreno 840 only (Qwen3-0.6B, crossover near +// 220 tokens); kShaderOverrideForceSeparateQkSoftmax A/Bs the two paths on one +// shape. +// +// Each fused worker also loops serially over the whole head dim, while the +// separate pair splits it across the work group, so the fused path loses as +// head_dim grows: on Adreno 840 it was slower for D128 and D256 at every +// context length. It is used only up to kFusedSoftmaxMaxHeadDim until a +// multi-device sweep shows otherwise. +// +// The fused shader also sizes its shared attn_weights row to this cutoff: its +// MAX_CONTEXT_TEXEL_LEN parameter in sdpa_compute_attn_weights_coop.yaml must +// equal kFusedSoftmaxMaxContextTexels, and the shader writes nothing for a +// longer context. +constexpr int64_t kFusedSoftmaxMaxContextTexels = 64; +constexpr int64_t kFusedSoftmaxMaxContextLen = + kFusedSoftmaxMaxContextTexels * 4; +constexpr int64_t kFusedSoftmaxMaxHeadDim = 64; + +// The fused shader's shared memory: four row arrays (one per texel component) +// plus the softmax helper's two 64-entry reductions, all fp32 in the worst +// case. Keep it within the 16 KiB maxComputeSharedMemorySize that Vulkan +// guarantees, so no device rejects the pipeline. +static_assert( + (4 * kFusedSoftmaxMaxContextTexels + 2 * 64) * sizeof(float) <= 16384, + "fused QK+softmax shared memory exceeds the Vulkan minimum limit"); + // // Resize functions // @@ -192,13 +225,16 @@ bool use_gqa_av_coop( // Resolve whether the AV decode path uses the GQA-reuse coop shader, honoring // the test-only shader_override knob (see SDPA.h): auto selects via // use_gqa_av_coop; kShaderOverrideForceNonGqa forces off; any other value -// forces the GQA family on. +// except kShaderOverrideForceSeparateQkSoftmax, which only concerns the QK and +// softmax nodes, forces the GQA family on. bool resolve_use_gqa( ComputeGraph* graph, const ValueRef shader_override, const int64_t num_q_heads, const int64_t num_kv_heads) { - if (shader_override == kDummyValueRef) { + if (shader_override == kDummyValueRef || + graph->extract_scalar(shader_override) == + kShaderOverrideForceSeparateQkSoftmax) { return use_gqa_av_coop(graph, num_q_heads, num_kv_heads); } const bool force_gqa = graph->extract_scalar(shader_override) != @@ -496,7 +532,9 @@ void add_sdpa_kv_cache_update_node( // kDummyValueRef to indicate no bias. scale_val is always passed as // a spec const; the LLM path computes it per head_dim and FUSED may // inherit from the caller-supplied scale. -void add_sdpa_compute_attn_weights_node( +// Shared by add_sdpa_compute_attn_weights_node and the LLM attention with a +// fused decode node, which passes its own global work group picker. +void add_sdpa_compute_attn_weights_node_impl( ComputeGraph& graph, const ValueRef q, const ValueRef k, @@ -504,7 +542,9 @@ void add_sdpa_compute_attn_weights_node( const ValueRef attn_mask, const float scale_val, const ValueRef attn_weights, - const SDPAMode mode) { + const SDPAMode mode, + const DynamicDispatchNode::PickGwgFn& pick_gwg, + const ValueRef shader_override) { vkapi::ParamsBindList param_ubos = { graph.sizes_ubo(q), graph.sizes_ubo(k), @@ -523,7 +563,7 @@ void add_sdpa_compute_attn_weights_node( graph.execute_nodes().emplace_back(new DynamicDispatchNode( graph, pick_sdpa_qk_shader, - pick_sdpa_qk_gwg, + pick_gwg, pick_sdpa_qk_lwg, // Inputs and Outputs {{attn_weights, vkapi::kWrite}, {read_inputs, vkapi::kRead}}, @@ -533,20 +573,47 @@ void add_sdpa_compute_attn_weights_node( {}, // Specialization Constants {scale_val}, - // Resize Args: [q, k, input_pos_symint_or_dummy, mode] - {q, k, input_pos_symint, mode_ref}, + // Resize Args: [q, k, input_pos_symint_or_dummy, mode, + // shader_override_or_dummy] + {q, k, input_pos_symint, mode_ref, shader_override}, // Resizing Logic resize_sdpa_attn_weights_node)); } -void add_sdpa_attn_weights_softmax_node( +void add_sdpa_compute_attn_weights_node( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const ValueRef attn_mask, + const float scale_val, + const ValueRef attn_weights, + const SDPAMode mode) { + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + attn_mask, + scale_val, + attn_weights, + mode, + pick_sdpa_qk_gwg, + kDummyValueRef); +} + +// Shared by add_sdpa_attn_weights_softmax_node and the LLM attention with a +// fused decode node, which passes its own global work group picker. +void add_sdpa_attn_weights_softmax_node_impl( ComputeGraph& graph, const ValueRef attn_weights, const ValueRef q, const ValueRef k, const ValueRef input_pos_symint, const ValueRef attn_weights_softmax, - const SDPAMode mode) { + const SDPAMode mode, + const DynamicDispatchNode::PickGwgFn& pick_gwg, + const ValueRef shader_override) { std::string shader_name; if (mode == SDPAMode::LLM) { shader_name = "sdpa_attn_weights_softmax"; @@ -575,7 +642,7 @@ void add_sdpa_attn_weights_softmax_node( graph.execute_nodes().emplace_back(new DynamicDispatchNode( graph, VK_KERNEL_FROM_STR(shader_name), - pick_sdpa_softmax_gwg, + pick_gwg, pick_required_lwg, // Inputs and Outputs {{attn_weights_softmax, vkapi::kWrite}, {attn_weights, vkapi::kRead}}, @@ -585,12 +652,222 @@ void add_sdpa_attn_weights_softmax_node( {}, // Specialization Constants {}, - // Resize Args: [q, k, input_pos_symint_or_dummy, mode] - {q, k, input_pos_symint, mode_ref}, + // Resize Args: [q, k, input_pos_symint_or_dummy, mode, + // shader_override_or_dummy] + {q, k, input_pos_symint, mode_ref, shader_override}, // Resizing Logic resize_sdpa_attn_weights_softmax_node)); } +void add_sdpa_attn_weights_softmax_node( + ComputeGraph& graph, + const ValueRef attn_weights, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const ValueRef attn_weights_softmax, + const SDPAMode mode) { + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + mode, + pick_sdpa_softmax_gwg, + kDummyValueRef); +} + +// +// Fused decode QK+softmax +// +// An LLM attention with head_dim <= kFusedSoftmaxMaxHeadDim also gets a +// decode-only node that computes Q @ K^T and the softmax in one dispatch. All +// three nodes are built, because the sequence length is only known once sizes +// are current: a dynamic-shape export reports the max bound at graph build +// time, never 1. +// Their global work group pickers are re-run from +// DynamicDispatchNode::trigger_resize, so the choice below is re-made every +// token, and the nodes not serving the current step get a zero grid, which +// DispatchNode::encode skips. A zero grid still carries the node's local work +// group, since the lwg picker requires one. All three nodes take the resize +// args [q, k, input_pos_symint, mode, shader_override_or_dummy]. +// + +// Whether the fused node, rather than the separate attn-weights and softmax +// pair, serves the current step. +bool use_fused_qk_softmax( + ComputeGraph* graph, + const std::vector& resize_args) { + const ValueRef q = resize_args.at(0); + const ValueRef k = resize_args.at(1); + const ValueRef input_pos_symint = resize_args.at(2); + const ValueRef shader_override = resize_args.at(4); + if (!is_single_token(graph, q) || + graph->size_at(-1, q) > kFusedSoftmaxMaxHeadDim) { + return false; + } + if (shader_override != kDummyValueRef && + graph->extract_scalar(shader_override) == + kShaderOverrideForceSeparateQkSoftmax) { + return false; + } + const int64_t context_len = + compute_sdpa_dims(*graph, q, k, input_pos_symint, SDPAMode::LLM) + .context_len; + return context_len <= kFusedSoftmaxMaxContextLen; +} + +vkapi::ShaderInfo pick_sdpa_qk_softmax_shader( + ComputeGraph* graph, + const std::vector& args, + const std::vector& resize_args) { + (void)resize_args; + const ValueRef q = args.at(1).refs.at(0); + const ValueRef k = args.at(1).refs.at(1); + + std::string shader_name = "sdpa_compute_attn_weights_coop_softmax"; + add_storage_type_suffix(shader_name, graph->storage_type_of(q)); + add_storage_type_suffix(shader_name, graph->storage_type_of(k)); + add_dtype_suffix(shader_name, graph->dtype_of(q)); + return VK_KERNEL_FROM_STR(shader_name); +} + +GlobalWorkGrid pick_sdpa_qk_softmax_gwg( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + (void)shader; + (void)args; + const LocalWorkGroup lwg(64u, 1u, 1u); + if (!use_fused_qk_softmax(graph, resize_args)) { + return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid, lwg); + } + const ValueRef q = resize_args.at(0); + const uint32_t num_q_heads = graph->size_at(-2, q); + const uint32_t seq_len = graph->size_at(-3, q); + return GlobalWorkGrid({1u, seq_len, num_q_heads}, kTiledWorkGrid, lwg); +} + +// A grid that DispatchNode::encode skips, keeping the picker's intent and +// required local work group. +GlobalWorkGrid zero_grid_of(const GlobalWorkGrid& gwg) { + return GlobalWorkGrid({0u, 0u, 0u}, gwg.intent(), gwg.required_lwg_size()); +} + +// The separate pair stands down whenever the fused node serves the step. +GlobalWorkGrid pick_sdpa_qk_gwg_beside_fused_decode( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + GlobalWorkGrid gwg = pick_sdpa_qk_gwg(graph, shader, args, resize_args); + if (use_fused_qk_softmax(graph, resize_args)) { + return zero_grid_of(gwg); + } + return gwg; +} + +GlobalWorkGrid pick_sdpa_softmax_gwg_beside_fused_decode( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + GlobalWorkGrid gwg = pick_sdpa_softmax_gwg(graph, shader, args, resize_args); + if (use_fused_qk_softmax(graph, resize_args)) { + return zero_grid_of(gwg); + } + return gwg; +} + +// Adds the attn-weights and softmax nodes of an LLM attention, and the fused +// decode node when head_dim allows it. The fused shader applies no attn_mask, +// so a masked attention must not come through here. +void add_sdpa_llm_attn_weights_softmax_nodes( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const float scale_val, + const ValueRef attn_weights, + const ValueRef attn_weights_softmax, + const ValueRef shader_override) { + if (graph.size_at(-1, q) > kFusedSoftmaxMaxHeadDim) { + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + /*attn_mask=*/kDummyValueRef, + scale_val, + attn_weights, + SDPAMode::LLM, + pick_sdpa_qk_gwg, + shader_override); + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + SDPAMode::LLM, + pick_sdpa_softmax_gwg, + shader_override); + return; + } + + const ValueRef mode_ref = static_cast(SDPAMode::LLM); + + // Writes normalized weights straight to attn_weights_softmax, removing the + // softmax dispatch and the round trip through attn_weights. + graph.execute_nodes().emplace_back(new DynamicDispatchNode( + graph, + pick_sdpa_qk_softmax_shader, + pick_sdpa_qk_softmax_gwg, + pick_required_lwg, + // Inputs and Outputs + {{attn_weights_softmax, vkapi::kWrite}, {{q, k}, vkapi::kRead}}, + // Shader param buffers + {graph.sizes_ubo(q), + graph.sizes_ubo(k), + graph.get_or_create_int_param_buffer(input_pos_symint)}, + // Push Constants + {}, + // Specialization Constants + {scale_val}, + // Resize Args + {q, k, input_pos_symint, mode_ref, shader_override}, + // Resizing Logic: the output has the attn_weights shape, and args[1] + // holds {q, k}, not an attn_weights tensor to copy the shape from. + resize_sdpa_attn_weights_node)); + + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + /*attn_mask=*/kDummyValueRef, + scale_val, + attn_weights, + SDPAMode::LLM, + pick_sdpa_qk_gwg_beside_fused_decode, + shader_override); + + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + SDPAMode::LLM, + pick_sdpa_softmax_gwg_beside_fused_decode, + shader_override); +} + void add_sdpa_compute_out_node( ComputeGraph& graph, const ValueRef attn_weights_softmax, @@ -779,24 +1056,15 @@ void sdpa_impl_with_shader_override( ? 1.0f / std::sqrt(static_cast(head_dim_size)) : graph.extract_scalar(scale); - add_sdpa_compute_attn_weights_node( + add_sdpa_llm_attn_weights_softmax_nodes( graph, q_projected, k_cache, input_pos_symint, - /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, - SDPAMode::LLM); - - add_sdpa_attn_weights_softmax_node( - graph, - attn_weights, - q_projected, - k_cache, - input_pos_symint, attn_weights_softmax, - SDPAMode::LLM); + shader_override); add_sdpa_compute_out_node( graph, diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.h b/backends/vulkan/runtime/graph/ops/impl/SDPA.h index f5324472d8a..79a5d7ba252 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.h +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.h @@ -54,6 +54,7 @@ constexpr int64_t kShaderOverrideForceNonGqa = 0; constexpr int64_t kShaderOverrideForceGqa = 1; constexpr int64_t kShaderOverrideForceTile2 = 2; constexpr int64_t kShaderOverrideForceBase = 3; +constexpr int64_t kShaderOverrideForceSeparateQkSoftmax = 4; // shader_override: test-only knob selecting the single-token decode AV shader. // It is a ValueRef holding one of the kShaderOverride* int64 scalars above, or @@ -69,6 +70,11 @@ constexpr int64_t kShaderOverrideForceBase = 3; // variant (tile2 on Adreno). // kShaderOverrideForceTile2 — force the tiled variant regardless of vendor. // kShaderOverrideForceBase — force the base variant regardless of vendor. +// kShaderOverrideForceSeparateQkSoftmax — keep the decode AV shader on auto, +// but serve a short decode context with the +// separate attn-weights and softmax nodes instead +// of the fused QK+softmax node, to A/B the fusion +// on one shape. Only sdpa_impl reads it. // Lets the benchmark/test exercise every AV shader on the same shape, and gives // the Adreno-only tile2 variant deterministic coverage on any device. Forcing // the GQA family requires a GQA-eligible shape (Hq divisible by Hkv, group size diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 0a1cd408ca1..f2df9ded53f 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -324,7 +324,9 @@ void test_vulkan_sdpa( // Get reference output at::Tensor out = at::empty_like(q); if (mode == SDPAMode::ATTN_WEIGHT_ONLY) { - out = at::empty({batch_size, num_heads, init_seq_len, init_seq_len}); + out = at::empty( + {batch_size, num_heads, init_seq_len, init_seq_len}, + at::device(at::kCPU).dtype(dtype)); } // Build Vulkan SDPA graph @@ -519,7 +521,9 @@ void test_vulkan_sdpa( at::indexing::Slice(0, context_len)}); } - const bool output_correct = at::allclose(reference_out, vk_out); + const double rtol = dtype == at::kHalf ? 1e-2 : 1e-5; + const double atol = dtype == at::kHalf ? 1e-2 : 1e-8; + const bool output_correct = at::allclose(reference_out, vk_out, rtol, atol); if (!output_correct) { // Print only differing tensor elements side by side for easier comparison auto ref_flat = reference_out.flatten(); @@ -1124,6 +1128,46 @@ TEST(VulkanSDPATest, test_sdpa_op_unaligned_head_dim) { test_vulkan_sdpa(0, {3, 1, 1, 2}, head_dim, num_heads, num_kv_heads, 1); } +// Decode within 256 tokens of context is served by the fused QK+softmax node, +// and beyond it by the separate attn-weights and softmax pair. A 250-token +// prefill is followed by decode steps that cross that cutoff, so one graph +// switches paths on resize. The steps start at position 0 because the +// update_cache path leaves earlier cache rows unwritten. +const std::vector kDecodeAcrossFusedCutoff = + {250, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff) { + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 64, 8, 2, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_fp16) { + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 64, 8, 2, 1, at::kHalf); +} + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_unaligned_dim) { + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 6, 4, 2, 1); +} + +// Above a head_dim of 64 the fused node is not built, so the separate pair +// serves every decode step, including a short context. +const std::vector kShortDecode = {10, 1, 1, 1, 1}; + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128) { + test_vulkan_sdpa(0, kShortDecode, 128, 8, 2, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128_fp16) { + test_vulkan_sdpa(0, kShortDecode, 128, 8, 2, 1, at::kHalf); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256) { + test_vulkan_sdpa(0, kShortDecode, 256, 8, 1, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256_fp16) { + test_vulkan_sdpa(0, kShortDecode, 256, 8, 1, 1, at::kHalf); +} + // q, k and v arrive with NaN in their head_dim padding, as when the ops that // produce them leave padding unwritten. Only the logical head_dim may be read. void test_vulkan_sdpa_ignores_head_dim_padding(const int seq_len) { diff --git a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp index 8df993ff582..843c0ddef78 100644 --- a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp +++ b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp @@ -24,7 +24,9 @@ Json build_sdpa_route( const char* name = Override == kShaderOverrideForceGqa ? "gqa" : Override == kShaderOverrideForceTile2 ? "gqa_tile2" : Override == kShaderOverrideForceBase ? "gqa_base" - : "non_gqa"; + : Override == kShaderOverrideForceSeparateQkSoftmax + ? "separate_qk_softmax" + : "non_gqa"; return {{"name", name}, {"options", options}}; } @@ -45,6 +47,10 @@ REGISTER_OPERATOR_ROUTES { llama.custom_sdpa.default, gqa_base, (build_sdpa_route)); + REGISTER_OPERATOR_ROUTE( + llama.custom_sdpa.default, + separate_qk_softmax, + (build_sdpa_route)); } } // namespace diff --git a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json index 3b22b6e78aa..001488c7a95 100644 --- a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json +++ b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json @@ -449,5 +449,245 @@ {"tensor": {"name": "output", "sizes": [1, 1, 32, 64], "dtype": "float16", "storage": "texture3d", "layout": "width", "data": {"fill": 0}}} ] ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P254 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 254}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P255 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 255}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P256 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 256}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P254 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 254}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P255 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 255}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P256 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 256}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D128 H16 Hkv8 S1 C64 P30 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 16, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 8, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 8, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 16, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D128 H16 Hkv8 S1 C64 P30 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 16, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 8, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 8, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 16, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D256 H8 Hkv1 S1 C64 P30 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 1, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 1, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D256 H8 Hkv1 S1 C64 P30 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 1, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 1, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] } ]