batch loads to allow overlap and coalescing

This commit is contained in:
Ruben Ortlam 2026-11-25 11:52:37 +01:00
parent e4b77e6120
commit 458d0e0247
7 changed files with 142 additions and 22 deletions

View file

@ -812,6 +812,7 @@ struct vk_device_struct {
bool coopmat2_bf16_support {};
bool coopmat2_gdn_support {};
bool coopmat2_decode_vector;
uint32_t coopmat2_reserved_shmem {};
bool dot2_f16 {};
bool ocp_fp4 {};

View file

@ -1440,6 +1440,9 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk,
}
}
// cm2 only: selects the flash_attn_cm2 SPIR-V built with FA_BIAS_STAGE
static constexpr uint32_t FA_FLAG_BIAS_STAGE = 256;
vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc,
bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type,
uint32_t bias_bins) {
@ -2430,18 +2433,23 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
const bool f32acc = fa.first.f32acc;
const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16;
const bool bias_stage = (fa.first.flags & FA_FLAG_BIAS_STAGE) != 0;
const void * spv_data;
size_t spv_size;
const char * name;
if (bf16_kv) {
#if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
if (!device->coopmat2_bf16_support) continue;
spv_data = flash_attn_f32_f16_bf16_cm2_data;
spv_size = flash_attn_f32_f16_bf16_cm2_len;
name = aligned ? "flash_attn_f32_bf16_aligned_cm2" : "flash_attn_f32_bf16_cm2";
spv_data = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_data : flash_attn_f32_f16_bf16_cm2_data;
spv_size = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_len : flash_attn_f32_f16_bf16_cm2_len;
name = bias_stage ? (aligned ? "flash_attn_f32_bf16_aligned_cm2_bias" : "flash_attn_f32_bf16_cm2_bias") :
(aligned ? "flash_attn_f32_bf16_aligned_cm2" : "flash_attn_f32_bf16_cm2");
#else
continue;
#endif
} else if (bias_stage) {
if (f32acc) { spv_data = flash_attn_f32_f16_cm2_bias_data; spv_size = flash_attn_f32_f16_cm2_bias_len; name = aligned ? "flash_attn_f32_f16_aligned_f32acc_cm2_bias" : "flash_attn_f32_f16_f32acc_cm2_bias"; }
else { spv_data = flash_attn_f32_f16_f16acc_cm2_bias_data; spv_size = flash_attn_f32_f16_f16acc_cm2_bias_len; name = aligned ? "flash_attn_f32_f16_aligned_f16acc_cm2_bias" : "flash_attn_f32_f16_f16acc_cm2_bias"; }
} else if (aligned) {
if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_aligned_f32acc_cm2"; }
else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_aligned_f16acc_cm2"; }
@ -5292,6 +5300,7 @@ vk_device ggml_vk_get_device(size_t idx) {
device->coopmat2 = true;
device->coopmat2_bf16_support = found_bf16_128 && found_bf16_256;
device->coopmat2_decode_vector = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector;
device->coopmat2_reserved_shmem = coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory;
}
}
#endif
@ -9004,6 +9013,15 @@ bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_
return supported;
}
static bool ggml_vk_flash_attn_cm2_bias_stage_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, bool f32acc) {
// Needs to be kept up to date on shader changes
const uint32_t acctype = f32acc ? 4 : 2;
const uint32_t bias_sh = params.block_rows * params.block_cols * acctype;
const uint32_t iq_shmem = 16 * sizeof(ggml_fp16_t);
return uint64_t(bias_sh) + iq_shmem + device->coopmat2_reserved_shmem <= device->properties.limits.maxComputeSharedMemorySize;
}
void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst) {
VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3];
std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3];
@ -9213,6 +9231,11 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc,
mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff,
bias_bins);
// GQA rows share one index row, the per-element bias is cheaper there
if (bias_bins && gqa_ratio == 1 && tuning_params.path == FA_COOPMAT2 &&
ggml_vk_flash_attn_cm2_bias_stage_shmem_support(ctx->device, tuning_params, f32acc)) {
fa_pipeline_state.flags |= FA_FLAG_BIAS_STAGE;
}
vk_pipeline pipeline = nullptr;

View file

@ -32,6 +32,7 @@ const uint32_t rows_per_thread = Br / row_split;
const uint32_t cols_per_iter = WorkGroupSize / D_split / row_split;
const uint32_t cols_per_thread = Bc / cols_per_iter;
const uint32_t num_subgroups = SubGroupSize == 0 ? 0 : WorkGroupSize / SubGroupSize;
const uint32_t mask_iters = (Bc * Br + WorkGroupSize - 1) / WorkGroupSize;
layout (binding = 0) readonly buffer Q {float data_q[];};
@ -201,12 +202,39 @@ void main() {
// skip this block
continue;
}
// Only load if the block is not all zeros, the bias still needs staging
// Skip all-zero blocks unless a bias has to be staged
if (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS) {
const bool mask_zero = USE_BIAS && mask_opt_bits == MASK_OPT_ALL_ZERO;
bool nem1_bounds_check = !(p.gqa_ratio > 1) && (p.nem1 % Br) != 0;
float max_mask = NEG_FLT_MAX_OVER_2;
// Bias: all mask, index and table loads before the barrier; the max keeps them there
FLOAT_TYPE mb[mask_iters];
if (USE_BIAS) {
bool mact[mask_iters], bact[mask_iters];
FLOAT_TYPE mv[mask_iters];
uint32_t bin_base[mask_iters];
int32_t bin[mask_iters];
[[unroll]] for (uint32_t it = 0; it < mask_iters; ++it) {
const uint32_t c = (it * WorkGroupSize + tid) % Bc;
const uint32_t r = (it * WorkGroupSize + tid) / Bc;
uint32_t kcol, bq, bh;
const bool kv_active = fa_kv_index(j * Bc + c, kcol);
mact[it] = it * WorkGroupSize + tid < Bc * Br && kv_active && (!nem1_bounds_check || i * Br + r < p.nem1);
bact[it] = fa_bias_row(r, bq, bh) && mact[it];
mv[it] = FLOAT_TYPE(data_m[mact[it] && !mask_zero ? m_offset + (i * Br + r) * m_stride + kcol : 0]);
bin_base[it] = (bq * p.neq2 + bh) * BiasBins;
bin[it] = data_bias_idx[bact[it] ? bq * p.KV + kcol : 0];
}
[[unroll]] for (uint32_t it = 0; it < mask_iters; ++it) {
const float t = data_bias_table[bact[it] ? bin_base[it] + uint32_t(bin[it]) : 0];
const float m = mask_zero ? 0.0f : float(mv[it]);
mb[it] = FLOAT_TYPE(bact[it] ? m + t : m);
max_mask = mact[it] ? max(max_mask, float(mb[it])) : max_mask;
}
}
barrier();
[[unroll]] for (uint32_t idx = 0; idx < Bc * Br; idx += gl_WorkGroupSize.x) {
uint32_t c = (idx + tid) % Bc;
@ -215,14 +243,8 @@ void main() {
uint32_t kcol;
bool kv_active = fa_kv_index(j * Bc + c, kcol);
if (kv_active && (!nem1_bounds_check || i * Br + r < p.nem1)) {
FLOAT_TYPE m = mask_zero ? FLOAT_TYPE(0) : FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]);
FLOAT_TYPE m = USE_BIAS ? mb[idx / WorkGroupSize] : FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]);
max_mask = max(max_mask, float(m));
if (USE_BIAS) {
uint32_t bq, bh;
if (fa_bias_row(r, bq, bh)) {
m = FLOAT_TYPE(float(m) + fa_bias(bq, bh, kcol));
}
}
masksh[c * masksh_stride + r] = m;
} else {
#if defined(FLOAT16)

View file

@ -230,7 +230,7 @@ void main() {
// skip this block
continue;
}
// Only load if the block is not all zeros, the bias still needs staging
// Skip all-zero blocks unless a bias has to be staged
if (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS) {
bool nem1_bounds_check = !(p.gqa_ratio > 1) && (p.nem1 % Br) != 0;
@ -241,7 +241,22 @@ void main() {
if (idx + tid < Bc * Br / 4 || idx + gl_WorkGroupSize.x <= Bc * Br / 4) {
uint32_t kcol;
bool kv_active = fa_kv_index(j * Bc + c, kcol);
if (kv_active) {
if (USE_BIAS && kv_active && p.gqa_ratio > 1 && mask_opt_bits != MASK_OPT_ALL_ZERO) {
// GQA: the rows share one mask value and one bias index
uint32_t bq, bh0;
fa_bias_row(0, bq, bh0);
const float mv = float(data_m[m_offset + kcol]);
const uint32_t bin = uint32_t(data_bias_idx[bq * p.KV + kcol]);
vec4 mb = vec4(mv);
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
uint32_t q, h;
const bool v = fa_bias_row(r * 4 + k, q, h);
const float b = data_bias_table[(bq * p.neq2 + (v ? h : bh0)) * BiasBins + bin];
mb[k] += v ? b : 0.0;
}
max_mask = max(max_mask, mv);
mask_cache[idx / WorkGroupSize] = f16vec4(mb);
} else if (kv_active) {
f16vec4 m;
if (USE_BIAS && mask_opt_bits == MASK_OPT_ALL_ZERO) {
m = f16vec4(0.0);
@ -278,13 +293,23 @@ void main() {
} else {
m = f16vec4(0.0);
}
if (USE_BIAS) {
uint32_t bq0, bh0;
if (USE_BIAS && fa_bias_row(r * 4, bq0, bh0)) {
vec4 mb = vec4(m);
uint32_t bq[4], bh[4];
bool bv[4];
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
uint32_t bq, bh;
if (fa_bias_row(r * 4 + k, bq, bh)) {
mb[k] += fa_bias(bq, bh, kcol);
}
bv[k] = fa_bias_row(r * 4 + k, bq[k], bh[k]);
bq[k] = bv[k] ? bq[k] : bq0;
bh[k] = bv[k] ? bh[k] : bh0;
}
uint32_t bin[4];
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
bin[k] = uint32_t(data_bias_idx[bq[k] * p.KV + kcol]);
}
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
const float b = data_bias_table[(bq[k] * p.neq2 + bh[k]) * BiasBins + bin[k]];
mb[k] += bv[k] ? b : 0.0;
}
m = f16vec4(mb);
}

View file

@ -221,6 +221,31 @@ ACC_TYPE faAddBias(const uint32_t row, const uint32_t col, const ACC_TYPE elem,
return elem + ACC_TYPE(fa_bias(bq, bh, kv_col));
}
#ifdef FA_BIAS_STAGE
const uint32_t BIAS_ROW_STEP = WorkGroupSize / Bc;
const uint32_t BIAS_ROWS = Br / BIAS_ROW_STEP;
shared ACC_TYPE bias_sh[Br * Bc];
// Subgroups read contiguous columns of one row, so the index and table loads coalesce.
void faStageBias(const uint32_t jblk) {
const uint32_t col = gl_LocalInvocationIndex % Bc;
const uint32_t r0 = gl_LocalInvocationIndex / Bc;
const uint32_t kv_col = jblk * Bc + col;
int32_t bins[BIAS_ROWS];
uint32_t boff[BIAS_ROWS];
bool ok[BIAS_ROWS];
[[unroll]] for (uint32_t k = 0; k < BIAS_ROWS; ++k) {
uint32_t bq, bh;
ok[k] = (!KV_bounds_check || kv_col < KV) && fa_bias_row(r0 + k * BIAS_ROW_STEP, bq, bh);
boff[k] = (bq * p.neq2 + bh) * BiasBins;
bins[k] = ok[k] ? data_bias_idx[bq * p.KV + kv_col] : 0;
}
[[unroll]] for (uint32_t k = 0; k < BIAS_ROWS; ++k) {
bias_sh[(r0 + k * BIAS_ROW_STEP) * Bc + col] = ok[k] ? ACC_TYPE(data_bias_table[boff[k] + uint32_t(bins[k])]) : ACC_TYPE(0);
}
}
#endif
ACC_TYPE maxReduce(const in ACC_TYPE x, const in ACC_TYPE y) {
return max(x, y);
}
@ -423,6 +448,14 @@ void main() {
}
}
#ifdef FA_BIAS_STAGE
if (MASK_ENABLE) {
barrier();
faStageBias(j);
barrier();
}
#endif
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> S = coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator>(0);
coopmat<FLOAT_TYPE, gl_ScopeWorkgroup, HSK_pad, Bc, gl_MatrixUseB> K_T;
@ -451,9 +484,15 @@ void main() {
coopMatPerElementNV(S, S, faAddSparseMask, j);
} else if (MASK_ENABLE) {
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> mva = coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator>(mv);
#ifdef FA_BIAS_STAGE
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> bias;
coopMatLoad(bias, bias_sh, 0, Bc, gl_CooperativeMatrixLayoutRowMajor);
mva += bias;
#else
if (USE_BIAS) {
coopMatPerElementNV(mva, mva, faAddBias, j);
}
#endif
S += slopeMat*mva;
}

View file

@ -736,6 +736,8 @@ void process_shaders() {
#if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
string_to_spv("flash_attn_f32_f16", "flash_attn_cm2.comp",
merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}), fp16, false, true, f16acc);
string_to_spv("flash_attn_f32_f16", "flash_attn_cm2.comp",
merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"FA_BIAS_STAGE", "1"}}), fp16, false, true, f16acc, "_bias");
#endif
#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
@ -787,6 +789,9 @@ void process_shaders() {
string_to_spv("flash_attn_f32_f16_bf16", "flash_attn_cm2.comp",
merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}),
true, false, true, false);
string_to_spv("flash_attn_f32_f16_bf16", "flash_attn_cm2.comp",
merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"FA_BIAS_STAGE", "1"}}),
true, false, true, false, "_bias");
#endif
std::map<std::string, std::string> base_dict = {{"FLOAT_TYPE", "float"}, {"FLOAT_TYPEV2", "vec2"}};

View file

@ -9639,6 +9639,15 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
}
}
visible.assign(nb*n_stream, kv);
if (causal) {
for (int64_t s = 0; s < n_stream; ++s) {
for (int64_t j = 0; j < nb; ++j) {
visible[s*nb + j] = kv/2 + (j + 1)*(kv/2)/nb - 37*s;
}
}
}
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
if (strcmp(t->name, "r") == 0) {
ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t));
@ -9647,12 +9656,8 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
} else if (strcmp(t->name, "m") == 0) {
std::vector<float> f(ggml_nelements(t));
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
visible.assign(nb*n_stream, kv);
for (int64_t s = 0; s < n_stream; ++s) {
for (int64_t j = 0; j < nb; ++j) {
if (causal) {
visible[s*nb + j] = kv/2 + (j + 1)*(kv/2)/nb - 37*s;
}
for (int64_t i = 0; i < kv; ++i) {
const bool pad = kv_rows && rows[s*kv + i] < 0;
if (causal) {