Commit c17655bce for llama.cpp

commit c17655bcec2c6449a66f945aa88243a1e8cee0d3
Author: Ruben Ortlam <rortlam@redhat.com>
Date:   Wed Dec 2 16:19:51 2026 +0100

    vulkan: add support for kv rows to Flash Attention (#33172)

    * vulkan: Support flash attention rows

    * reduce prefill regression

    * fix rdna4 prefill

    * store row indices in shmem

    * use separate shader instance for cm2 kv rows to avoid Nvidia slowdown

    * add support for Xe FA shaders

    * fixes after review

    * zero softmax weights for inactive columns, reject op for unsupported strides

    * fix shmem calculation, check_results call

    * add bias to check_results call

    * ggml: require contiguous rows and 16-byte alignment for flash_attn_ext q tensor

diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h
index 301df8d95..4941d47a6 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h
@@ -34,8 +34,8 @@ bool ggml_vk_intel_windows_driver_in_range(uint32_t driver_version, uint32_t low

 // shaders
 void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
-vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool allow_flip = true);
-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, uint32_t gqa_tok);
+vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip = true);
+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, bool use_kv_rows, ggml_type k_type, ggml_type v_type, uint32_t bias_bins, uint32_t gqa_tok);
 uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch);
 void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested = nullptr);
 bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type);
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
index 74e9a514d..ae80d0d89 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
@@ -1014,10 +1014,13 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph

         if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
             const float * params = (const float *)tensor->op_params;
-            tensor_clone = ggml_flash_attn_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], params[0], params[1], params[2]);
+            tensor_clone = ggml_flash_attn_ext_rows(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], src_clone[5], params[0], params[1], params[2]);
             if (src_clone[4]) {
                 ggml_flash_attn_ext_set_sinks(tensor_clone, src_clone[4]);
             }
+            if (src_clone[6]) {
+                ggml_flash_attn_ext_set_bias(tensor_clone, src_clone[6], src_clone[7]);
+            }
         } else if (tensor->op == GGML_OP_MUL_MAT) {
             tensor_clone = src_clone[2] ? ggml_mul_mat_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], nullptr)
                                         : ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
index 9d957fa14..c64d67ec2 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
@@ -132,7 +132,7 @@ struct vk_flash_attn_push_constants {
     uint32_t ne3;

     uint32_t neq2;
-    uint32_t neq3;
+    uint32_t n_kv_cache;
     uint32_t nek2;
     uint32_t nek3;
     uint32_t nev2;
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
index cdb4327d3..1514e228f 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
@@ -475,10 +475,11 @@ struct vk_xe_fa_pipeline_state {
     bool partial_row_mask;
     bool multi_head_mask;
     uint32_t bias_bins;
+    bool kv_rows;

     bool operator<(const vk_xe_fa_pipeline_state &b) const {
-        return std::tie(HSK, HSV, qk_ratio, pv_ratio, decode_n, unaligned_seq_len, unaligned_q, partial_row_mask, multi_head_mask, bias_bins) <
-               std::tie(b.HSK, b.HSV, b.qk_ratio, b.pv_ratio, b.decode_n, b.unaligned_seq_len, b.unaligned_q, b.partial_row_mask, b.multi_head_mask, b.bias_bins);
+        return std::tie(HSK, HSV, qk_ratio, pv_ratio, decode_n, unaligned_seq_len, unaligned_q, partial_row_mask, multi_head_mask, bias_bins, kv_rows) <
+               std::tie(b.HSK, b.HSV, b.qk_ratio, b.pv_ratio, b.decode_n, b.unaligned_seq_len, b.unaligned_q, b.partial_row_mask, b.multi_head_mask, b.bias_bins, b.kv_rows);
     }
 };

@@ -879,6 +880,7 @@ struct vk_device_struct {

     vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
     vk_pipeline pipeline_dequant_transpose[GGML_TYPE_COUNT]; // fused dequant+transpose for FA quant-KV
+    vk_pipeline pipeline_fa_kv_rows_copy;
     vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
     vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
     vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
@@ -1481,13 +1483,14 @@ struct vk_fa_tuning_params {
     bool q_in_regs;
     bool flip;
     bool flip_direct;
+    bool kv_rows;
     uint32_t limit_occupancy_shmem;

     void print() const {
         std::cerr << "path=" << path << " workgroup_size=" << workgroup_size << " subgroup_size=" << subgroup_size <<
                      " block_rows=" << block_rows << " block_cols=" << block_cols << " d_split=" << d_split <<
                      " row_split=" << row_split << " shmem_staging=" << shmem_staging << " disable_subgroups=" << disable_subgroups <<
-                     " q_in_regs=" << q_in_regs << " flip=" << flip << " flip_direct=" << flip_direct << " limit_occupancy_shmem=" << limit_occupancy_shmem << std::endl;
+                     " q_in_regs=" << q_in_regs << " flip=" << flip << " flip_direct=" << flip_direct << " kv_rows=" << kv_rows << " limit_occupancy_shmem=" << limit_occupancy_shmem << std::endl;
     }
 };

diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
index 67fafc52c..e80fb170d 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp
+++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
@@ -234,7 +234,8 @@ uint64_t ggml_vk_get_node_flops(const ggml_tensor * node) {
         const ggml_tensor * q = node->src[0];
         const ggml_tensor * k = node->src[1];
         const ggml_tensor * v = node->src[2];
-        return 2ull * q->ne[1] * q->ne[2] * (k->ne[0] + v->ne[0]) * k->ne[1] * q->ne[3];
+        const int64_t n_kv = node->src[5] ? node->src[5]->ne[0] : k->ne[1];
+        return 2ull * q->ne[1] * q->ne[2] * (k->ne[0] + v->ne[0]) * n_kv * q->ne[3];
     }
     return 0;
 }
@@ -1263,10 +1264,11 @@ void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
     );
 }

-static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) {
+static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, bool kv_rows) {

     vk_fa_tuning_params result{};
     result.path = FA_SCALAR;
+    result.kv_rows = kv_rows;

     if (device->vendor_id == VK_VENDOR_ID_INTEL) {
         // Disable subgroup use due to performance issues when enforcing subgroup sizes
@@ -1349,11 +1351,12 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device,
     return result;
 }

-static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool allow_flip) {
+static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) {
     GGML_UNUSED(n_kv);

     vk_fa_tuning_params result{};
     result.path = FA_COOPMAT1;
+    result.kv_rows = kv_rows;

     const uint32_t D = hsk | hsv;

@@ -1421,12 +1424,13 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device
     return result;
 }

-static vk_fa_tuning_params get_fa_tuning_params_coopmat2(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) {
+static vk_fa_tuning_params get_fa_tuning_params_coopmat2(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, bool kv_rows) {
     GGML_UNUSED(n_kv);
     GGML_UNUSED(f32acc);

     vk_fa_tuning_params result{};
     result.path = FA_COOPMAT2;
+    result.kv_rows = kv_rows;

     const uint32_t D = hsk | hsv;

@@ -1449,7 +1453,7 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat2(const vk_device& device
     return result;
 }

-vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool allow_flip) {
+vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) {
     FaCodePath path = device->coopmat2 ? FA_COOPMAT2 :
                       device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;

@@ -1468,11 +1472,11 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk,
     if (path == FA_COOPMAT1) {
         bool shape_ok = (f32acc && device->coopmat_support_16x16x16_f32acc) ||
                         (!f32acc && device->coopmat_support_16x16x16_f16acc);
-        vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, allow_flip);
+        vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip);
         bool shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type);
         if (!shmem_ok && params.flip) {
             allow_flip = false;
-            params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, allow_flip);
+            params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip);
             shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type);
         }

@@ -1488,11 +1492,11 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk,

     switch (path) {
     case FA_SCALAR:
-        return get_fa_tuning_params_scalar(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc);
+        return get_fa_tuning_params_scalar(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, kv_rows);
     case FA_COOPMAT1:
-        return get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, allow_flip);
+        return get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip);
     case FA_COOPMAT2:
-        return get_fa_tuning_params_coopmat2(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc);
+        return get_fa_tuning_params_coopmat2(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, kv_rows);
     default:
         throw std::runtime_error("unsupported FaCodePath");
     }
@@ -1502,7 +1506,7 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk,
 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,
+                                                  bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, bool use_kv_rows, ggml_type k_type, ggml_type v_type,
                                                   uint32_t bias_bins, uint32_t gqa_tok) {
     const bool old_amd_windows = device->vendor_id == VK_VENDOR_ID_AMD && device->driver_id == vk::DriverId::eAmdProprietary &&
                                  (device->architecture == AMD_GCN || device->architecture == AMD_RDNA1 || device->architecture == AMD_RDNA2);
@@ -1514,7 +1518,8 @@ vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_
                      (use_sparse        ? 16 : 0) |
                      (params.q_in_regs  ? 32 : 0) |
                      (params.flip       ? 64 : 0) |
-                     (params.flip_direct ? 128 : 0);
+                     (params.flip_direct ? 128 : 0) |
+                     (use_kv_rows       ? 512 : 0);

     const uint32_t subgroup_size = params.disable_subgroups ? 0 : params.subgroup_size;

@@ -1705,7 +1710,7 @@ static vk_xe_fa_tuning_params get_xe_fa_tuning_params(const vk_device_struct * d
         size_t shmem_lf_sz = CEIL_DIV(sg_per_gw * p_loops, sg_sz) * sg_sz * sizeof(float);
         size_t shmem_oob_staging_sz = sg_per_gw * tm * tk * sizeof(ggml_fp16_t);
         size_t shmem_o_sz = sg_per_gw * out_col_per_wg_ph2 * omat_row * sizeof(float);
-        size_t shmem_reuse_sz = 2 * shmem_group_max_sz + std::max(shmem_oob_staging_sz, 2 * shmem_p_sz);
+        size_t shmem_reuse_sz = 2 * shmem_group_max_sz + (pipeline_state.kv_rows ? shmem_oob_staging_sz + 2 * shmem_p_sz : std::max(shmem_oob_staging_sz, 2 * shmem_p_sz));

         shmem_ph2_sz = shmem_lf_sz + shmem_global_max_sz;
         // Shmem of p/group max is reused with output accumulation, calculate the max size
@@ -2536,14 +2541,16 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {

             const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16;
             const bool bias_stage = (fa.first.flags & FA_FLAG_BIAS_STAGE) != 0;
+            // the barriers in fa_kv_rows_load slow down dense pipelines on NVIDIA, even when skipped
+            const bool kv_rows = (fa.first.flags & 512) != 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 = 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;
+                spv_data = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_data : kv_rows ? flash_attn_f32_f16_bf16_cm2_rows_data : flash_attn_f32_f16_bf16_cm2_data;
+                spv_size = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_len  : kv_rows ? flash_attn_f32_f16_bf16_cm2_rows_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
@@ -2552,12 +2559,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
             } 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"; }
+            } else if (f32acc) {
+                spv_data = kv_rows ? flash_attn_f32_f16_cm2_rows_data : flash_attn_f32_f16_cm2_data;
+                spv_size = kv_rows ? flash_attn_f32_f16_cm2_rows_len  : flash_attn_f32_f16_cm2_len;
+                name = aligned ? "flash_attn_f32_f16_aligned_f32acc_cm2" : "flash_attn_f32_f16_f32acc_cm2";
             } else {
-                if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data;        spv_size = flash_attn_f32_f16_cm2_len;        name = "flash_attn_f32_f16_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_f16acc_cm2"; }
+                spv_data = kv_rows ? flash_attn_f32_f16_f16acc_cm2_rows_data : flash_attn_f32_f16_f16acc_cm2_data;
+                spv_size = kv_rows ? flash_attn_f32_f16_f16acc_cm2_rows_len  : flash_attn_f32_f16_f16acc_cm2_len;
+                name = aligned ? "flash_attn_f32_f16_aligned_f16acc_cm2" : "flash_attn_f32_f16_f16acc_cm2";
             }
             ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10,
                                     sizeof(vk_flash_attn_push_constants), {Br, 1, 1},
@@ -3656,7 +3665,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
-    ggml_vk_create_pipeline(device, device->pipeline_dequant_transpose[GGML_TYPE_Q8_0], "dequant_q8_0_transpose", dequant_q8_0_transpose_len, dequant_q8_0_transpose_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
+    ggml_vk_create_pipeline(device, device->pipeline_dequant_transpose[GGML_TYPE_Q8_0], "dequant_q8_0_transpose", dequant_q8_0_transpose_len, dequant_q8_0_transpose_data, "main", 3, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
     ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
@@ -3761,8 +3770,13 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
                                              xe_fa_params.decode_params.out_row_per_wg_ph2, xe_fa_params.subgroup_size[1], xe_fa_params.decode_params.split_p_per_iter_ph2,
                                              xe_fa_params.decode_params.p_chunk_ph1, xe_fa_params.decode_params.out_col_per_wg_ph2,
                                              xe_fa_params.tm, xe_fa_params.tn, xe_fa_params.decode_params.pipeline_flag_ph2 };
-            ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 7, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]);
-            ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, 1, 1 }, sc_ph2, 1, false, true, xe_fa_params.subgroup_size[0]);
+            if (pipeline_state.kv_rows) {
+                ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1_rows", fa_decode_ph1_cm1_rows_len, fa_decode_ph1_cm1_rows_data, "main", 8, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]);
+                ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2_rows", fa_decode_ph2_cm1_rows_len, fa_decode_ph2_cm1_rows_data, "main", 6, sizeof(vk_xe_fa_push_constants), { 1, 1, 1 }, sc_ph2, 1, false, true, xe_fa_params.subgroup_size[0]);
+            } else {
+                ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 7, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]);
+                ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, 1, 1 }, sc_ph2, 1, false, true, xe_fa_params.subgroup_size[0]);
+            }
         }

         for (auto& it : device->pipeline_xe_fa_prefill) {
@@ -3800,6 +3814,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
             ggml_vk_create_pipeline(device, device->pipeline_fa_sparse_compact, "fa_sparse_compact", fa_sparse_compact_len, fa_sparse_compact_data, "main", 2, sizeof(vk_op_flash_attn_sparse_compact_push_constants), {1, 1, 1}, {compact_max}, 1, true);
         }
     }
+    ggml_vk_create_pipeline(device, device->pipeline_fa_kv_rows_copy, "fa_kv_rows_copy", fa_kv_rows_copy_len, fa_kv_rows_copy_data, "main", 3, 5 * sizeof(uint32_t), {256 * 8, 1, 1}, {}, 1);

     if (device->subgroup_clustered && device->subgroup_require_full_support) {
         ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
@@ -9228,7 +9243,9 @@ bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_f

     const uint32_t occupancy_limiter = std::max(params.limit_occupancy_shmem, 1u) * 4 * sizeof(float);

-    const uint32_t total_size = tmpsh + tmpshv4 + masksh + iq_shmem + Qf + kvsh + kblocksh_size + occupancy_limiter;
+    const uint32_t kv_rows_sh = (params.kv_rows ? std::max(Bc, 128u) : 4u) * (uint32_t)sizeof(uint32_t);
+
+    const uint32_t total_size = tmpsh + tmpshv4 + masksh + iq_shmem + Qf + kvsh + kblocksh_size + occupancy_limiter + kv_rows_sh;
     const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;

     VK_LOG_DEBUG("ggml_vk_flash_attn_scalar_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", mmq=" << mmq << ", total_size=" << total_size << ", supported=" << supported);
@@ -9279,7 +9296,9 @@ bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_
         pvsh = Br * osh_stride * pvsh_elem_size;
     }

-    uint32_t total_size = tmpsh + iq_shmem + Qf + Psh + sfsh + ksh + pvsh + slope + params.limit_occupancy_shmem * 16;
+    const uint32_t kv_rows_sh = (params.kv_rows ? std::max(Bc, 128u) : 4u) * (uint32_t)sizeof(uint32_t);
+
+    uint32_t total_size = tmpsh + iq_shmem + Qf + Psh + sfsh + ksh + pvsh + slope + kv_rows_sh + params.limit_occupancy_shmem * 16;

     if (params.flip) {
         const uint32_t d_pad = std::max(hsk_pad, hsv_pad);
@@ -9342,7 +9361,8 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
     const uint32_t HSK = nek0;
     const uint32_t HSV = nev0;
     uint32_t N = neq1;
-    const uint32_t KV = nek1;
+    const ggml_tensor * kv_rows = dst->src[5];
+    const uint32_t KV = kv_rows ? kv_rows->ne[0] : nek1;

     GGML_ASSERT(ne0 == HSV);
     GGML_ASSERT(ne2 == N);
@@ -9384,39 +9404,72 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
     const bool k_quant = k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_BF16 && k->type != GGML_TYPE_F32;
     const bool v_quant = v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_BF16 && v->type != GGML_TYPE_F32;
     const bool kv_raw = (k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16) && k->type == v->type;
+    auto tensor_aligned_with = [&](const ggml_tensor * t, uint32_t in) {
+        GGML_ASSERT(t != nullptr && in != 0);
+        return t->nb[1] % in == 0 && t->nb[2] % in == 0 && t->nb[3] % in == 0 && ggml_vk_tensor_buffer_offset(ctx, t) % in == 0;
+    };
+    auto vk_dev = ctx->device.get();
+    const bool xe_fa_supported_platform = vk_dev->xe_fa_support && vk_dev->properties.deviceID != 0xFD80 && vk_dev->properties.deviceID != 0xFD81;
+    const bool xe_fa_candidate = xe_fa_supported_platform && neq0 % 32 == 0 && nev0 % 16 == 0 &&
+                                 q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 &&
+                                 mask != nullptr && mask->type == GGML_TYPE_F16 &&
+                                 ggml_get_op_params_f32(dst, 1) == 0.0f && ggml_get_op_params_f32(dst, 2) == 0.0f &&
+                                 tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u);
+    // the xe prefill kernel reads row lists compacted into a dense scratch
+    const bool xe_fa_rows_prefill = kv_rows && xe_fa_candidate && (neq1 > 8 || neq2 / nev2 > 64);
+    // compact row lists in a pre-pass instead of gathering in the FA shader
+    const bool rows_compact = kv_rows && (xe_fa_rows_prefill || (neq1 >= 64 &&
+                              (ctx->device->vendor_id == VK_VENDOR_ID_AMD ||
+                               (ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA &&
+                                get_fa_tuning_params(ctx->device, HSK, HSV, neq1, KV, k->type, v->type, f32acc, qk_ratio, kv_rows).path == FA_COOPMAT2))));
     // gated to AMD, except RDNA4, which regressed in benchmarks
-    const bool kv_raw_strided = ctx->device->vendor_id == VK_VENDOR_ID_AMD &&
-                                ctx->device->architecture != vk_device_architecture::AMD_RDNA4 &&
-                                neq1 >= 256 &&
-                                kv_raw &&
-                                (k->nb[1] != (uint64_t)HSK * ggml_type_size(k->type) ||
-                                 v->nb[1] != (uint64_t)HSV * ggml_type_size(v->type)) &&
-                                (HSK % 8) == 0 && (HSV % 8) == 0;
+    const bool kv_raw_strided = (rows_compact && kv_raw && (HSK % 8) == 0 && (HSV % 8) == 0) ||
+                                (ctx->device->vendor_id == VK_VENDOR_ID_AMD &&
+                                 ctx->device->architecture != vk_device_architecture::AMD_RDNA4 &&
+                                 neq1 >= 256 &&
+                                 kv_raw &&
+                                 (k->nb[1] != (uint64_t)HSK * ggml_type_size(k->type) ||
+                                  v->nb[1] != (uint64_t)HSV * ggml_type_size(v->type)) &&
+                                 (HSK % 8) == 0 && (HSV % 8) == 0);
     const size_t kv_scratch_ts = kv_raw_strided ? ggml_type_size(k->type) : sizeof(ggml_fp16_t);
+    const uint64_t k_nel = (uint64_t)HSK * nek2 * KV * (kv_rows ? neq3 : nek3);
+    const uint64_t v_nel = (uint64_t)HSV * nev2 * KV * (kv_rows ? neq3 : nev3);
+    const uint64_t k_sz = k_nel * kv_scratch_ts;
+    const uint64_t v_sz = v_nel * kv_scratch_ts;
+    const uint64_t v_scratch_offset = ROUNDUP_POW2(k_sz, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
     // K and V share one scratch buffer, so the sum must fit in one allocation
-    const uint64_t dequant_kv_sz = ((uint64_t)ggml_nelements(k) + (uint64_t)ggml_nelements(v)) * kv_scratch_ts;
+    const uint64_t dequant_kv_sz = v_scratch_offset + v_sz;
+    const bool copy_dense_kv = kv_raw_strided && !kv_rows;
+    vk_pipeline & pack_k = kv_raw_strided ? ctx->device->pipeline_fa_kv_rows_copy : ctx->device->pipeline_dequant_transpose[k->type];
+    vk_pipeline & pack_v = kv_raw_strided ? ctx->device->pipeline_fa_kv_rows_copy : ctx->device->pipeline_dequant_transpose[v->type];
+    auto pack_fits = [&](const vk_pipeline & pipeline, uint64_t n_el) {
+        return pipeline && CEIL_DIV(n_el, pipeline->wg_denoms[0]) <= ctx->device->properties.limits.maxComputeWorkGroupCount[0];
+    };
     const uint32_t cm2_min_queries = KV >= 8192 ? 512 : 1024;
     const uint32_t cm2_min_reuse = KV >= 8192 ? 4096 : 8192;
     // Query reuse must cover the conversion and synchronization cost.
     const bool cm2_dequant_kv = KV >= 4096 && neq1 >= cm2_min_queries && (uint64_t) neq1 * qk_ratio >= cm2_min_reuse;
     const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 &&
                                 is_dense_kv_cache(k) && is_dense_kv_cache(v) &&
-                                (uint64_t)ggml_nelements(k) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange &&
-                                (uint64_t)ggml_nelements(v) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange &&
+                                k_nel <= UINT32_MAX && v_nel <= UINT32_MAX &&
+                                k_sz <= ctx->device->properties.limits.maxStorageBufferRange &&
+                                v_sz <= ctx->device->properties.limits.maxStorageBufferRange &&
                                 dequant_kv_sz <= ctx->device->max_buffer_size &&
                                 dequant_kv_sz <= ctx->device->max_memory_allocation_size &&
-                                (kv_raw_strided ||
-                                 (ctx->device->pipeline_dequant_transpose[k->type] != nullptr &&
-                                  ctx->device->pipeline_dequant_transpose[v->type] != nullptr)) &&
+                                (copy_dense_kv || (pack_fits(pack_k, k_nel) && pack_fits(pack_v, v_nel))) &&
                                 // Intel Xe1 regresses, see PR 25494
-                                (ctx->device->vendor_id != VK_VENDOR_ID_INTEL ||
+                                (ctx->device->vendor_id != VK_VENDOR_ID_INTEL || xe_fa_rows_prefill ||
                                  (ctx->device->coopmat_support && ctx->device->architecture != vk_device_architecture::INTEL_XE1)) &&
-                                (!ctx->device->coopmat2 || cm2_dequant_kv);
+                                (!ctx->device->coopmat2 || cm2_dequant_kv || rows_compact);
+    const bool use_kv_rows = kv_rows && !use_dequant_kv;
+    const bool compact_kv = kv_rows && use_dequant_kv;
+    // RDNA4 direct flip is slower on the head-major scratch
+    const bool compact_cell_major = compact_kv && kv_raw_strided && ctx->device->architecture == vk_device_architecture::AMD_RDNA4;
     const ggml_type k_type_eff = (use_dequant_kv && !kv_raw_strided) ? GGML_TYPE_F16 : k->type;
     const ggml_type v_type_eff = (use_dequant_kv && !kv_raw_strided) ? GGML_TYPE_F16 : v->type;

     // N=32 avoids the cm1 prefill block_rows doubling
-    vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio);
+    vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows);
     const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u);

     if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa &&
@@ -9429,7 +9482,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
         workgroups_y /= gqa_ratio;
     }

-    tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio);
+    tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows);

     float scale         = 1.0f;
     float max_bias      = 0.0f;
@@ -9455,7 +9508,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
         return (t->type != GGML_TYPE_F16 && t->type != GGML_TYPE_BF16) ||
                (t->nb[1] | t->nb[2] | t->nb[3]) % (4 * sizeof(ggml_fp16_t)) == 0;
     };
-    const bool use_sparse = !disable_sparse && n_kv_max > 0 && mask &&
+    const bool use_sparse = !kv_rows && !disable_sparse && n_kv_max > 0 && mask &&
                             max_bias == 0.0f && logit_softcap == 0.0f &&
                             (tuning_params.path != FA_COOPMAT2 || (sparse_gather_aligned(k) && sparse_gather_aligned(v))) &&
                             nem0 == KV &&
@@ -9476,7 +9529,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
         bool fold_pays = true;
         if (tuning_params.path == FA_SCALAR) {
             // the scalar tile size depends on the row count, so size it for all folded rows
-            fold_params = get_fa_tuning_params(ctx->device, HSK, HSV, gqa_ratio * neq1, KV, k_type_eff, v_type_eff, f32acc, qk_ratio);
+            fold_params = get_fa_tuning_params(ctx->device, HSK, HSV, gqa_ratio * neq1, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows);
             // scalar: fold if the unfolded dispatch gets no split_k (more tokens than rows), or if the fold adds no padded rows and each KV split keeps at least 16 blocks
             const uint32_t fold_tok = std::max(1u, fold_params.block_rows / gqa_ratio);
             const uint32_t fold_wgs = CEIL_DIV(neq1, fold_tok) * workgroups_y * workgroups_z;
@@ -9510,7 +9563,14 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const

     uint32_t nbk2_eff = (uint32_t)nbk2, nbk3_eff = (uint32_t)nbk3;
     uint32_t nbv2_eff = (uint32_t)nbv2, nbv3_eff = (uint32_t)nbv3;
-    if (use_dequant_kv) {
+    if (compact_cell_major) {
+        k_stride = HSK * (uint32_t)nek2;
+        v_stride = HSV * (uint32_t)nev2;
+        nbk2_eff = HSK * sizeof(ggml_fp16_t);
+        nbk3_eff = (uint32_t)((uint64_t)HSK * KV * nek2 * sizeof(ggml_fp16_t));
+        nbv2_eff = HSV * sizeof(ggml_fp16_t);
+        nbv3_eff = (uint32_t)((uint64_t)HSV * KV * nev2 * sizeof(ggml_fp16_t));
+    } else if (use_dequant_kv) {
         k_stride = HSK;
         v_stride = HSV;
         nbk2_eff = (uint32_t)((uint64_t)HSK * KV * sizeof(ggml_fp16_t));
@@ -9534,8 +9594,8 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
         // flipped coopmat1 path reads K/V rows with 16-byte loads
         const bool kv_16b = use_dequant_kv ||
             (((uintptr_t)k->data | (uintptr_t)v->data | nbk2_eff | nbk3_eff | nbv2_eff | nbv3_eff) % 16) == 0;
-        if (!aligned || use_sparse || gqa_ratio != 1 || !kv_16b) {
-            tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, false);
+        if (!aligned || use_sparse || (use_kv_rows && tuning_params.flip_direct) || gqa_ratio != 1 || !kv_16b) {
+            tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows, false);
             alignment = tuning_params.block_cols;
             aligned = fa_aligned(tuning_params);
         }
@@ -9550,29 +9610,18 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
     bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16
                         && (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256);
     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,
+                                                                   mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, use_kv_rows, k_type_eff, v_type_eff,
                                                                    bias_bins, gqa_tok);
     // GQA rows share one index row, the per-element bias is cheaper there
-    if (bias_bins && gqa_ratio == 1 && tuning_params.path == FA_COOPMAT2 &&
+    if (bias_bins && gqa_ratio == 1 && !use_kv_rows && 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;

-    auto tensor_aligned_with = [&](const ggml_tensor * t, uint32_t in) {
-        GGML_ASSERT(t != nullptr && in != 0);
-        return t->nb[1] % in == 0 && t->nb[2] % in == 0 && t->nb[3] % in == 0 && ggml_vk_tensor_buffer_offset(ctx, t) % in == 0;
-    };
-    auto vk_dev = ctx->device.get();
-    bool xe_fa_opt = false;
+    bool xe_fa_opt = xe_fa_candidate && !use_sparse && (!kv_rows || compact_kv || !xe_fa_rows_prefill);
     bool xe_fa_use_2phases = false;
-    bool xe_fa_supported_platform = vk_dev->xe_fa_support && vk_dev->properties.deviceID != 0xFD80 && vk_dev->properties.deviceID != 0xFD81;
-    bool xe_fa_supported_usage = neq0 % 32 == 0 && nev0 % 16 == 0 && mask != nullptr && !use_sparse && max_bias == 0.0f && logit_softcap == 0.0f &&
-                                 tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u);
-    bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 &&
-                                 mask != nullptr && mask->type == GGML_TYPE_F16;
-    xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype;
     std::pair<vk_pipeline, vk_pipeline> xe_fa_pipeline_dual_phases = { nullptr , nullptr };
     vk_pipeline xe_fa_pipeline = nullptr;
     size_t size_q_staging = 0;
@@ -9588,8 +9637,8 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
             if (neq1 > 8 || pv_ratio > 64) {
                 uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type));
                 uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type));
-                vk_xe_fa_pipeline_state prefill_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, 0, false, false, false, false, bias_bins };
-                prefill_state.unaligned_seq_len = nek1 % 32 != 0;
+                vk_xe_fa_pipeline_state prefill_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, 0, false, false, false, false, bias_bins, false };
+                prefill_state.unaligned_seq_len = KV % 32 != 0;
                 prefill_state.unaligned_q = head_stride_q % 8 != 0 || q_stride % 8 != 0 || batch_stride_q % 8 != 0;
                 prefill_state.partial_row_mask = neq1 > nem1;
                 prefill_state.multi_head_mask = nem2 > 1;
@@ -9606,18 +9655,18 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
                     xe_fa_opt = false;
                 }
             } else {
-                vk_xe_fa_pipeline_state decode_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, (uint32_t)neq1, false, false, false, false, bias_bins };
-                decode_state.unaligned_seq_len = nek1 % 256 != 0;
+                vk_xe_fa_pipeline_state decode_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, (uint32_t)neq1, false, false, false, false, bias_bins, use_kv_rows };
+                decode_state.unaligned_seq_len = KV % 256 != 0;
                 xe_fa_params = get_xe_fa_tuning_params(vk_dev, decode_state, false);
                 const uint32_t split_p_size = xe_fa_params.decode_params.p_chunk_ph1;
-                const size_t max_dim = std::max<size_t>(CEIL_DIV(nek1, split_p_size), 1);
+                const size_t max_dim = std::max<size_t>(CEIL_DIV(KV, split_p_size), 1);
                 const size_t p_dim = max_dim * split_p_size;
                 const size_t q_head_padding = 16;
                 size_q_staging = neq0 * neq1 * (neq2 * neq3 + q_head_padding) * sizeof(ggml_fp16_t);
                 size_p = neq1 * neq2 * p_dim * neq3 * sizeof(ggml_fp16_t);
                 size_group_max = neq1 * neq2 * max_dim * neq3 * sizeof(float);
                 size_decode_temp = size_q_staging + size_p + size_group_max;
-                uint32_t ph1_wg1 = CEIL_DIV(nek1, xe_fa_params.decode_params.p_chunk_ph1);
+                uint32_t ph1_wg1 = CEIL_DIV(KV, xe_fa_params.decode_params.p_chunk_ph1);
                 if (xe_fa_params.shmem_sz <= vk_dev->properties.limits.maxComputeSharedMemorySize &&
                     ph1_wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] &&
                     size_decode_temp <= ctx->device->properties.limits.maxStorageBufferRange) {
@@ -9781,7 +9830,10 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
     vk_subbuffer bias_buf = bias ? ggml_vk_tensor_subbuffer(ctx, bias) : q_buf;
     vk_subbuffer bias_idxs_buf = bias_idxs ? ggml_vk_tensor_subbuffer(ctx, bias_idxs) : q_buf;
     vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf;
-    vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf;
+    vk_subbuffer indices_buf = kv_rows ? ggml_vk_tensor_subbuffer(ctx, kv_rows) : q_buf;
+    if (use_sparse) {
+        indices_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0);
+    }
     if (use_mask_opt || use_sparse) {
         // the mask opt bits and the sparse index list overwrite a matmul input converted into prealloc_y
         ctx->prealloc_y_last_pipeline_used = nullptr;
@@ -9789,17 +9841,13 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
     }

     if (use_dequant_kv) {
-        const uint64_t k_sz = (uint64_t)ggml_nelements(k) * kv_scratch_ts;
-        const uint64_t v_sz = (uint64_t)ggml_nelements(v) * kv_scratch_ts;
-        if (ctx->prealloc_size_x < k_sz + v_sz) {
-            ctx->prealloc_size_x = k_sz + v_sz;
+        if (ctx->prealloc_size_x < dequant_kv_sz) {
+            ctx->prealloc_size_x = dequant_kv_sz;
             ggml_vk_preallocate_buffers(ctx, subctx);
         }
         vk_subbuffer k_dst = vk_subbuffer{ ctx->prealloc_x, 0,    k_sz };
-        vk_subbuffer v_dst = vk_subbuffer{ ctx->prealloc_x, k_sz, v_sz };
-        const uint32_t k_nel = (uint32_t)ggml_nelements(k);
-        const uint32_t v_nel = (uint32_t)ggml_nelements(v);
-        if (kv_raw_strided) {
+        vk_subbuffer v_dst = vk_subbuffer{ ctx->prealloc_x, v_scratch_offset, v_sz };
+        if (copy_dense_kv) {
             vk_pipeline cp_k = ggml_vk_get_cpy_pipeline(ctx, k, nullptr, k->type);
             vk_pipeline cp_v = ggml_vk_get_cpy_pipeline(ctx, v, nullptr, v->type);
             ggml_pipeline_request_descriptor_sets(ctx, cp_k, 1);
@@ -9823,21 +9871,22 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
                 return { ne, 1, 1 };
             };
             ggml_vk_dispatch_pipeline(ctx, subctx, cp_k, { k_buf, k_dst },
-                make_pc((uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, k_nel), cpy_elems(k_nel));
+                make_pc(HSK, (uint32_t)nek2, KV, (uint32_t)k_nel), cpy_elems((uint32_t)k_nel));
             ggml_vk_dispatch_pipeline(ctx, subctx, cp_v, { v_buf, v_dst },
-                make_pc((uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, v_nel), cpy_elems(v_nel));
+                make_pc(HSV, (uint32_t)nev2, KV, (uint32_t)v_nel), cpy_elems((uint32_t)v_nel));
         } else {
-            vk_pipeline tr_k = ctx->device->pipeline_dequant_transpose[k->type];
-            vk_pipeline tr_v = ctx->device->pipeline_dequant_transpose[v->type];
-            ggml_pipeline_request_descriptor_sets(ctx, tr_k, 1);
-            ggml_pipeline_request_descriptor_sets(ctx, tr_v, 1);
+            ggml_pipeline_request_descriptor_sets(ctx, pack_k, 1);
+            ggml_pipeline_request_descriptor_sets(ctx, pack_v, 1);
             if (ctx->prealloc_x_need_sync) {
                 ggml_vk_sync_buffers(ctx, subctx);
             }
-            { const std::vector<uint32_t> pc = { (uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, 0, k_nel };
-              ggml_vk_dispatch_pipeline(ctx, subctx, tr_k, { k_buf, k_dst }, pc, { k_nel, 1, 1 }); }
-            { const std::vector<uint32_t> pc = { (uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, 0, v_nel };
-              ggml_vk_dispatch_pipeline(ctx, subctx, tr_v, { v_buf, v_dst }, pc, { v_nel, 1, 1 }); }
+            const uint32_t n_kv_cache = compact_kv ? (uint32_t)nek1 : 0;
+            // n_cols = 1 keeps the cache's cell-major layout
+            const uint32_t n_cols = compact_cell_major ? 1 : KV;
+            { const std::vector<uint32_t> pc = { HSK, (uint32_t)nek2, n_cols, n_kv_cache, (uint32_t)k_nel };
+              ggml_vk_dispatch_pipeline(ctx, subctx, pack_k, { k_buf, k_dst, indices_buf }, pc, { (uint32_t)k_nel, 1, 1 }); }
+            { const std::vector<uint32_t> pc = { HSV, (uint32_t)nev2, n_cols, n_kv_cache, (uint32_t)v_nel };
+              ggml_vk_dispatch_pipeline(ctx, subctx, pack_v, { v_buf, v_dst, indices_buf }, pc, { (uint32_t)v_nel, 1, 1 }); }
         }
         ggml_vk_sync_buffers(ctx, subctx);
         k_buf = k_dst;
@@ -9879,16 +9928,16 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
         };

         ggml_vk_dispatch_pipeline(ctx, subctx, sparse_compact_pipeline,
-                                  { mask_buf, sparse_buf }, sc_pc,
+                                  { mask_buf, indices_buf }, sc_pc,
                                   { nem1, nem2, nem3 });
         ggml_vk_sync_buffers(ctx, subctx);
     }

     const vk_flash_attn_push_constants pc = { N, KV,
                                               (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
-                                              (uint32_t)neq2, (uint32_t)neq3,
-                                              (uint32_t)nek2, (uint32_t)nek3,
-                                              (uint32_t)nev2, (uint32_t)nev3,
+                                              (uint32_t)neq2, (uint32_t)nek1,
+                                              (uint32_t)nek2, (uint32_t)(compact_kv ? neq3 : nek3),
+                                              (uint32_t)nev2, (uint32_t)(compact_kv ? neq3 : nev3),
                                               nem1, nem2, nem3,
                                               q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
                                               k_stride, nbk2_eff, nbk3_eff,
@@ -9899,15 +9948,15 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const

     if (xe_fa_opt) {
         uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type));
-        uint32_t head_stride_k = uint32_t(nbk2 / ggml_type_size(k->type));
-        uint32_t head_stride_v = uint32_t(nbv2 / ggml_type_size(v->type));
+        uint32_t head_stride_k = uint32_t((compact_kv ? nbk2_eff : nbk2) / ggml_type_size(k->type));
+        uint32_t head_stride_v = uint32_t((compact_kv ? nbv2_eff : nbv2) / ggml_type_size(v->type));
         uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type));
-        uint32_t batch_stride_k = uint32_t(nbk3 / ggml_type_size(k->type));
-        uint32_t batch_stride_v = uint32_t(nbv3 / ggml_type_size(v->type));
+        uint32_t batch_stride_k = uint32_t((compact_kv ? nbk3_eff : nbk3) / ggml_type_size(k->type));
+        uint32_t batch_stride_v = uint32_t((compact_kv ? nbv3_eff : nbv3) / ggml_type_size(v->type));
         uint32_t batch_stride_o = uint32_t(nb3 / ggml_type_size(dst->type));

         vk_xe_fa_push_constants pc_xe_fa = { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3,
-                                             (uint32_t)nek1, (uint32_t)nek2, (uint32_t)nek3, (uint32_t)nev2, (uint32_t)nev3,
+                                             KV, (uint32_t)nek2, (uint32_t)(compact_kv ? neq3 : nek3), (uint32_t)nev2, (uint32_t)(compact_kv ? neq3 : nev3),
                                              (uint32_t)nem1, (uint32_t)nem2, (uint32_t)nem3,
                                              q_stride, head_stride_q, k_stride, head_stride_k, v_stride, head_stride_v,
                                              batch_stride_q, batch_stride_k, batch_stride_v, batch_stride_o,
@@ -9933,15 +9982,27 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
             ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, q, q_buf, q_temp_buf);

             ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.first, 1);
-            ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first,
-                { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf, bias_buf, bias_idxs_buf },
-                pc_xe_fa, { (uint32_t)ph1_wg, (uint32_t)nek1, (uint32_t)neq3 });
+            if (use_kv_rows) {
+                ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first,
+                    { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf, bias_buf, bias_idxs_buf, indices_buf },
+                    pc_xe_fa, { (uint32_t)ph1_wg, KV, (uint32_t)neq3 });
+            } else {
+                ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first,
+                    { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf, bias_buf, bias_idxs_buf },
+                    pc_xe_fa, { (uint32_t)ph1_wg, KV, (uint32_t)neq3 });
+            }

             ggml_vk_sync_buffers(ctx, subctx);
             ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.second, 1);
-            ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second,
-                { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf },
-                pc_xe_fa, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 });
+            if (use_kv_rows) {
+                ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second,
+                    { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf, indices_buf },
+                    pc_xe_fa, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 });
+            } else {
+                ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second,
+                    { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf },
+                    pc_xe_fa, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 });
+            }

             ctx->prealloc_x_need_sync = true;
         } else {
@@ -9969,7 +10030,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const

         vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
         ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
-                                    {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf, bias_buf, bias_idxs_buf},
+                                    {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, indices_buf, bias_buf, bias_idxs_buf},
                                     pc, { dispatch_x, workgroups_y, workgroups_z });

         ggml_vk_sync_buffers(ctx, subctx);
@@ -9984,7 +10045,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
             workgroups_x *= pipeline->wg_denoms[0];
         }
         ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
-                                    {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf, bias_buf, bias_idxs_buf},
+                                    {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, indices_buf, bias_buf, bias_idxs_buf},
                                     pc, { workgroups_x, workgroups_y, workgroups_z });
     }

@@ -17536,16 +17597,41 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
             }
         case GGML_OP_FLASH_ATTN_EXT:
             {
-                if (op->src[5] != nullptr) {
+                if (ggml_flash_attn_ext_has_bias(op) && !ggml_flash_attn_ext_bias_is_indexed(op)) {
                     return false;
                 }
-                if (ggml_flash_attn_ext_has_bias(op) && !ggml_flash_attn_ext_bias_is_indexed(op)) {
+                if (op->src[1]->ne[1] == 0 || (op->src[5] && op->src[5]->ne[0] == 0)) {
+                    return false;
+                }
+                for (const ggml_tensor * t : op->src) {
+                    if (t && (vk_tensor_offset(t) + t->view_offs) % device->properties.limits.minStorageBufferOffsetAlignment != 0) {
+                        return false;
+                    }
+                }
+                if ((vk_tensor_offset(op) + op->view_offs) % device->properties.limits.minStorageBufferOffsetAlignment != 0) {
                     return false;
                 }
                 if (ggml_flash_attn_ext_bias_is_indexed(op) &&
                     ((uint64_t)ggml_nelements(op->src[6]) > UINT32_MAX || (uint64_t)ggml_nelements(op->src[7]) > UINT32_MAX)) {
                     return false;
                 }
+                if (const ggml_tensor * kv_rows = op->src[5]) {
+                    const ggml_tensor * mask = op->src[3];
+                    if (kv_rows->type != GGML_TYPE_I32 || !ggml_is_contiguous(kv_rows) ||
+                        kv_rows->ne[1] != op->src[0]->ne[3] || kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 ||
+                        !mask || !ggml_is_contiguous(mask) || mask->ne[0] != kv_rows->ne[0] ||
+                        op->src[1]->ne[3] != 1 || op->src[2]->ne[3] != 1) {
+                        return false;
+                    }
+                    // f16/f32 K/V rows are read as vec4
+                    auto misaligned = [](const ggml_tensor * t) {
+                        return (t->type == GGML_TYPE_F16 || t->type == GGML_TYPE_BF16 || t->type == GGML_TYPE_F32) &&
+                               (t->nb[1] | t->nb[2]) % (4 * ggml_type_size(t->type)) != 0;
+                    };
+                    if (misaligned(op->src[1]) || misaligned(op->src[2])) {
+                        return false;
+                    }
+                }
                 bool coopmat2 = device->coopmat2;
                 uint32_t HSK = op->src[1]->ne[0];
                 uint32_t HSV = op->src[2]->ne[0];
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_q8_0.comp b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_q8_0.comp
index 3b3fbbe89..200a94bba 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_q8_0.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_q8_0.comp
@@ -6,6 +6,9 @@ layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;

 layout (binding = 0) readonly buffer A {block_q8_0 data_a[];};
 layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
+#ifdef DEQUANT_TRANSPOSE
+layout (binding = 2) readonly buffer R {int data_rows[];};
+#endif

 void main() {
     const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
@@ -18,6 +21,7 @@ void main() {
         return;
     }

+    uint a_idx = ib;
 #ifdef DEQUANT_TRANSPOSE
     // read [HS, NH, KV, NS], write [HS, KV, NH, NS]
     const uint HS = p.M, NH = p.K, KVn = p.stride_a;
@@ -27,16 +31,28 @@ void main() {
                      + ((e0 / HS) % NH) * (HS * KVn)
                      + (e0 / (HS * NH * KVn)) * (HS * KVn * NH)
                      + 16 * il;
+    // A nonzero stride_b is the size of the shared cache for row-list gathers.
+    if (p.stride_b != 0) {
+        const uint blocks_per_row = HS * NH / 32;
+        const uint row = uint(data_rows[ib / blocks_per_row]);
+        if (row >= p.stride_b) {
+            [[unroll]] for (uint l = 0; l < 16; ++l) {
+                data_b[b_idx + l] = D_TYPE(0.0);
+            }
+            return;
+        }
+        a_idx = row * blocks_per_row + ib % blocks_per_row;
+    }
 #else
     const uint b_idx = 1024*i + 32*ir + 16*il;
 #endif

-    const float d = float(data_a[ib].d);
+    const float d = float(data_a[a_idx].d);

     const uint q_idx = 16*il;

     [[unroll]] for (uint l = 0; l < 16; l += 2) {
-        data_b[b_idx + l    ] = D_TYPE(d * data_a[ib].qs[q_idx + l    ]);
-        data_b[b_idx + l + 1] = D_TYPE(d * data_a[ib].qs[q_idx + l + 1]);
+        data_b[b_idx + l    ] = D_TYPE(d * data_a[a_idx].qs[q_idx + l    ]);
+        data_b[b_idx + l + 1] = D_TYPE(d * data_a[a_idx].qs[q_idx + l + 1]);
     }
 }
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp
index b56665f61..3422a9606 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp
@@ -22,6 +22,7 @@

 #include "types.glsl"
 #include "dot_product_funcs.glsl"
+#define FA_KV_ROWS_SHMEM
 #include "flash_attn_base.glsl"
 #include "flash_attn_dequant.glsl"

@@ -221,14 +222,14 @@ void main() {
                     [[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);
+                        uint32_t mcol, bq, bh;
+                        const bool m_active = fa_mask_index(j * Bc + c, mcol);
+                        mact[it] = it * WorkGroupSize + tid < Bc * Br && m_active && (!nem1_bounds_check || i * Br + r < p.nem1);
                         bact[it] = fa_bias_row(r, bq, bh) && mact[it];
                         const uint32_t m_row = GQA_TOK > 1 ? min(row_tok(r), p.nem1 - 1) * KV : (i * Br + r) * m_stride;
-                        mv[it] = FLOAT_TYPE(data_m[mact[it] && !mask_zero ? m_offset + m_row + kcol : 0]);
+                        mv[it] = FLOAT_TYPE(data_m[mact[it] && !mask_zero ? m_offset + m_row + mcol : 0]);
                         bin_base[it] = (bq * p.neq2 + bh) * BiasBins;
-                        bin[it] = data_bias_idx[bact[it] ? bq * p.KV + kcol : 0];
+                        bin[it] = data_bias_idx[bact[it] ? bq * p.KV + mcol : 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];
@@ -243,11 +244,10 @@ void main() {
                     uint32_t c = (idx + tid) % Bc;
                     uint32_t r = (idx + tid) / Bc;
                     if (idx + tid < Bc * Br) {
-                        uint32_t kcol;
-                        bool kv_active = fa_kv_index(j * Bc + c, kcol);
-                        if (kv_active && (!nem1_bounds_check || i * Br + r < p.nem1)) {
+                        uint32_t mcol;
+                        if (fa_mask_index(j * Bc + c, mcol) && (!nem1_bounds_check || i * Br + r < p.nem1)) {
                             const uint32_t m_row = GQA_TOK > 1 ? min(row_tok(r), p.nem1 - 1) * KV : (i * Br + r) * m_stride;
-                            FLOAT_TYPE m = USE_BIAS ? mb[idx / WorkGroupSize] : FLOAT_TYPE(data_m[m_offset + m_row + kcol]);
+                            FLOAT_TYPE m = USE_BIAS ? mb[idx / WorkGroupSize] : FLOAT_TYPE(data_m[m_offset + m_row + mcol]);
                             max_mask = max(max_mask, float(m));
                             masksh[c * masksh_stride + r] = m;
                         } else {
@@ -275,6 +275,8 @@ void main() {
             }
         }

+        fa_kv_rows_load(j);
+
         ACC_TYPE Sf[rows_per_thread][cols_per_thread];
         [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
             [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
@@ -341,7 +343,7 @@ void main() {
                 [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
                     uint32_t kcol;
                     bool kv_active = fa_kv_index(j * Bc + c * cols_per_iter + col_tid, kcol);
-                    if (!kv_active) {
+                    if (!USE_KV_ROWS && !kv_active) {
                         continue;
                     }

@@ -356,6 +358,7 @@ void main() {
                     } else {
                         K_Tf = FLOAT_TYPEV4(data_kv4[k_offset / 4 + kcol * k_stride / 4 + d * D_split + d_tid]);
                     }
+                    K_Tf = kv_active ? K_Tf : FLOAT_TYPEV4(0);
                     [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
                         Sf[r][c] = dot_product(Q_cache[r], K_Tf, Sf[r][c]);
                     }
@@ -365,7 +368,7 @@ void main() {
             [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
                 uint32_t kcol;
                 bool kv_active = fa_kv_index(j * Bc + c * cols_per_iter + col_tid, kcol);
-                if (!kv_active) {
+                if (!USE_KV_ROWS && !kv_active) {
                     continue;
                 }

@@ -381,6 +384,7 @@ void main() {
                     } else {
                         K_Tf = FLOAT_TYPEV4(data_kv4[k_offset / 4 + kcol * k_stride / 4 + d * D_split + d_tid]);
                     }
+                    K_Tf = kv_active ? K_Tf : FLOAT_TYPEV4(0);
                     [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
                         Sf[r][c] = dot_product(Qf[tile_row(r) * qf_stride + d * D_split + d_tid], K_Tf, Sf[r][c]);
                     }
@@ -395,7 +399,8 @@ void main() {

         [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
             uint32_t kcol;
-            if (!fa_kv_index(j * Bc + c * cols_per_iter + col_tid, kcol)) {
+            const bool kv_active = fa_kv_index(j * Bc + c * cols_per_iter + col_tid, kcol);
+            if (!USE_KV_ROWS && !kv_active) {
                 continue;
             }

@@ -450,6 +455,8 @@ void main() {
                     }
                 }

+                k_dm = kv_active ? k_dm : ACC_TYPEV2(0);
+
                 [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
                     const uint qib = tile_row(r) * qf_stride + (d_tid * (HSK_per_thread / 4) + d_block) / 8;
                     const uint qiqs = (d_tid * (HSK_per_thread / 4) + d_block) % 8;
@@ -550,13 +557,13 @@ void main() {
         [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
             uint32_t vcol;
             bool kv_active = fa_kv_index(j * Bc + c * cols_per_iter + col_tid, vcol);
-            if (!kv_active) {
+            if (!USE_KV_ROWS && !kv_active) {
                 continue;
             }

             FLOAT_TYPE Pf[rows_per_thread];
             [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
-                Pf[r] = FLOAT_TYPE(exp(float(Sf[r][c]) - Mf[r]));
+                Pf[r] = kv_active ? FLOAT_TYPE(exp(float(Sf[r][c]) - Mf[r])) : FLOAT_TYPE(0);
                 Lf[r] += Pf[r];
             }

@@ -572,6 +579,7 @@ void main() {
                 } else {
                     Vf = FLOAT_TYPEV4(data_vv4[v_offset / 4 + vcol * v_stride / 4 + d * D_split + d_tid]);
                 }
+                Vf = kv_active ? Vf : FLOAT_TYPEV4(0);
                 [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
                     Of[r][d] += FLOAT_TYPEV4(Pf[r] * Vf);
                 }
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl
index 156372919..848798895 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl
@@ -35,6 +35,8 @@ const bool Q_IN_REGS       = (Flags & 32) != 0;
 const bool FLIP            = (Flags & 64) != 0;
 const bool FLIP_DIRECT     = (Flags & 128) != 0;
 const bool USE_BIAS        = BiasBins != 0;
+const bool USE_KV_ROWS     = (Flags & 512) != 0;
+const bool GATHER_KV       = USE_SPARSE || USE_KV_ROWS;

 // Round up head sizes to a multiple of 16, for coopmat1/coopmat2 paths
 const uint32_t HSK_pad = (HSK + 15) & ~15;
@@ -51,7 +53,7 @@ layout (push_constant) uniform parameter {
     uint32_t ne3;

     uint32_t neq2;
-    uint32_t neq3;
+    uint32_t n_kv_cache;
     uint32_t nek2;
     uint32_t nek3;
     uint32_t nev2;
@@ -93,7 +95,7 @@ layout (binding = 5) writeonly buffer OV4 {D_TYPEV4 data_ov4[];};

 layout (binding = 6) readonly buffer MO {uint32_t data_mask_opt[];};

-layout (binding = 7) readonly buffer SP {int32_t data_sparse[];};
+layout (binding = 7) readonly buffer KI {int32_t data_kv_indices[];};

 layout (binding = 8) readonly buffer BT {float data_bias_table[];};
 layout (binding = 9) readonly buffer BI {int32_t data_bias_idx[];};
@@ -165,7 +167,14 @@ ACC_TYPE perElemOpGetSink(const in uint32_t r, const in uint32_t c, const in ACC

 uint32_t i, N, KV, split_k_index, Tr, start_j, end_j,
          gqa_iq1, iq2, iq3, rk2, rk3, rv2, rv3, ik2, ik3, iv2, iv3,
-         q_stride, k_stride, v_stride, m_stride, sparse_base;
+         q_stride, k_stride, v_stride, m_stride, kv_indices_base;
+
+#ifdef FA_KV_ROWS_SHMEM
+const uint32_t kv_rows_sh_size = !USE_KV_ROWS ? 4 : (Bc >= 128 ? Bc : 128);
+shared uint32_t kv_rows_sh[kv_rows_sh_size];
+uint32_t kv_rows_sh_base = 0x80000000u;
+const uint32_t FA_KV_ROW_INVALID = 0xFFFFFFFFu;
+#endif

 void init_indices()
 {
@@ -205,10 +214,10 @@ void init_indices()

     // broadcast factors
     rk2 = p.neq2/p.nek2;
-    rk3 = p.neq3/p.nek3;
+    rk3 = p.ne3/p.nek3;

     rv2 = p.neq2/p.nev2;
-    rv3 = p.neq3/p.nev3;
+    rv3 = p.ne3/p.nev3;

     // k indices
     ik3 = iq3 / rk3;
@@ -234,12 +243,14 @@ void init_indices()
     // partitions the n_kv_max blocks.
     if (USE_SPARSE) {
         uint32_t qrow = (p.gqa_ratio > 1) ? gqa_iq1 : (i * Br);
-        sparse_base = (((iq3 % p.nem3) * p.nem2 + (iq2 % p.nem2)) * p.nem1 + qrow) * p.split_kv;
+        kv_indices_base = (((iq3 % p.nem3) * p.nem2 + (iq2 % p.nem2)) * p.nem1 + qrow) * p.split_kv;

         uint32_t total_blocks = CEIL_DIV(p.split_kv, Bc);
         uint32_t per_blocks   = CEIL_DIV(total_blocks, p.k_num);
         start_j = min(split_k_index * per_blocks, total_blocks);
         end_j   = min((split_k_index + 1) * per_blocks, total_blocks);
+    } else if (USE_KV_ROWS) {
+        kv_indices_base = iq3 * KV;
     }
 }

@@ -254,16 +265,24 @@ bool row_valid(const in uint32_t r) {
     return r < N && row_tok(r) < p.ne2;
 }

-// Resolve a linear KV slot to a real column; false for inactive (sparse padding/-1, or dense OOB).
+// Resolve an attention column to a K/V row; false for inactive (padding or out of range).
 bool fa_kv_index(uint lin, out uint kv_col) {
-    if (USE_SPARSE) {
-        if (lin >= p.split_kv) {
+#ifdef FA_KV_ROWS_SHMEM
+    if (USE_KV_ROWS) {
+        const uint row = kv_rows_sh[lin - kv_rows_sh_base];
+        kv_col = row != FA_KV_ROW_INVALID ? row : 0;
+        return row != FA_KV_ROW_INVALID;
+    }
+#endif
+    if (GATHER_KV) {
+        if (lin >= (USE_SPARSE ? p.split_kv : KV)) {
             kv_col = 0;
             return false;
         }
-        int idx = data_sparse[sparse_base + lin];
-        kv_col = idx >= 0 ? uint(idx) : 0;
-        return idx >= 0;
+        uint idx = uint(data_kv_indices[kv_indices_base + lin]);
+        bool valid = idx < p.n_kv_cache;
+        kv_col = valid ? idx : 0;
+        return valid;
     }
     kv_col = lin;
     return !KV_bounds_check || lin < KV;
@@ -287,6 +306,33 @@ float fa_bias(const in uint32_t query, const in uint32_t head, const in uint32_t
     return data_bias_table[(query * p.neq2 + head) * BiasBins + bin];
 }

+#ifdef FA_KV_ROWS_SHMEM
+void fa_kv_rows_load(const uint32_t j) {
+    if (!USE_KV_ROWS || j * Bc - kv_rows_sh_base <= kv_rows_sh_size - Bc) {
+        return;
+    }
+    kv_rows_sh_base = j * Bc;
+    barrier();
+    [[unroll]] for (uint32_t c = 0; c < kv_rows_sh_size; c += gl_WorkGroupSize.x) {
+        const uint32_t idx = c + gl_LocalInvocationIndex;
+        if (idx < kv_rows_sh_size) {
+            const uint32_t lin = kv_rows_sh_base + idx;
+            const uint32_t row = lin < KV ? uint(data_kv_indices[kv_indices_base + lin]) : FA_KV_ROW_INVALID;
+            kv_rows_sh[idx] = row < p.n_kv_cache ? row : FA_KV_ROW_INVALID;
+        }
+    }
+    barrier();
+}
+#endif
+
+bool fa_mask_index(uint lin, out uint mask_col) {
+    if (USE_SPARSE) {
+        return fa_kv_index(lin, mask_col);
+    }
+    mask_col = lin;
+    return !KV_bounds_check || lin < KV;
+}
+
 // Bias applied to softmax to stay in fp16 range.
 // Based on ggml-cuda issue https://github.com/ggml-org/llama.cpp/issues/18606
 const float FATTN_KQ_MAX_OFFSET = 3.0f*0.6931f;
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp
index 14e4409ee..6c14e9255 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp
@@ -17,6 +17,7 @@
 #extension GL_KHR_cooperative_matrix : enable

 #include "types.glsl"
+#define FA_KV_ROWS_SHMEM
 #include "flash_attn_base.glsl"
 #if !defined(BFLOAT16)
 #include "flash_attn_dequant.glsl"
@@ -253,14 +254,14 @@ void main() {
                     uint32_t c = (idx + tid) / (Br / 4);
                     uint32_t r = (idx + tid) % (Br / 4);
                     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 (USE_BIAS && kv_active && p.gqa_ratio > 1 && GQA_TOK == 1 && mask_opt_bits != MASK_OPT_ALL_ZERO) {
+                        uint32_t mcol;
+                        bool m_active = fa_mask_index(j * Bc + c, mcol);
+                        if (USE_BIAS && m_active && p.gqa_ratio > 1 && GQA_TOK == 1 && mask_opt_bits != MASK_OPT_ALL_ZERO) {
                             // GQA, one token per tile: 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]);
+                            const float mv = float(data_m[m_offset + mcol]);
+                            const uint32_t bin = uint32_t(data_bias_idx[bq * p.KV + mcol]);
                             vec4 mb = vec4(mv);
                             [[unroll]] for (uint32_t k = 0; k < 4; ++k) {
                                 uint32_t q, h;
@@ -270,7 +271,7 @@ void main() {
                             }
                             max_mask = max(max_mask, mv);
                             mask_cache[idx / WorkGroupSize] = f16vec4(mb);
-                        } else if (kv_active) {
+                        } else if (m_active) {
                             f16vec4 m;
                             if (USE_BIAS && mask_opt_bits == MASK_OPT_ALL_ZERO) {
                                 m = f16vec4(0.0);
@@ -283,7 +284,7 @@ void main() {
                                 max_mask = max(max(max(max(max_mask, float(m[0])), float(m[1])), float(m[2])), float(m[3]));
                             } else if (USE_SPARSE) {
                                 // sparse is gqa-gated (m_stride == 0): all four rows share the value
-                                FLOAT_TYPE mv = FLOAT_TYPE(data_m[m_offset + kcol]);
+                                FLOAT_TYPE mv = FLOAT_TYPE(data_m[m_offset + mcol]);
                                 m = f16vec4(mv);
                                 max_mask = max(max_mask, float(mv));
                             } else if (!nem1_bounds_check || i * Br + r * 4 + 3 < p.nem1) {
@@ -325,7 +326,7 @@ void main() {
                                 }
                                 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]);
+                                    bin[k] = uint32_t(data_bias_idx[bq[k] * p.KV + mcol]);
                                 }
                                 [[unroll]] for (uint32_t k = 0; k < 4; ++k) {
                                     const float b = data_bias_table[(bq[k] * p.neq2 + bh[k]) * BiasBins + bin[k]];
@@ -355,6 +356,8 @@ void main() {
             }
         }

+        fa_kv_rows_load(j);
+
         if (SHMEM_STAGING != 0) {
             [[unroll]] for (uint32_t idx = 0; idx < Bc * HSK_pad / 4; idx += gl_WorkGroupSize.x) {
                 uint32_t d = (idx + tid) % (HSK_pad / 4);
@@ -392,6 +395,15 @@ void main() {
         coopmat<FLOAT_TYPE, gl_ScopeSubgroup, MatBc, 16, gl_MatrixUseA> KMat;
         coopmat<FLOAT_TYPE, gl_ScopeSubgroup, 16, MatBr, gl_MatrixUseB> QMat;

+        uint32_t k_rows[(Bc * MatBr / 4 + WorkGroupSize - 1) / WorkGroupSize];
+        bool k_act[k_rows.length()];
+        if (USE_KV_ROWS && SHMEM_STAGING == 0) {
+            [[unroll]] for (uint32_t i = 0; i < k_rows.length(); ++i) {
+                const uint32_t row = (i * WorkGroupSize + tid) / (MatBr / 4);
+                k_act[i] = row < Bc && fa_kv_index(j * Bc + row, k_rows[i]);
+            }
+        }
+
         [[unroll]] for (uint32_t d = 0; d < d_tiles; ++d) {
             // If SHMEM_STAGING is set, a Bc * HSK_pad size tile of K is loaded to shmem
             // If not, K is loaded directly from global memory if aligned, otherwise
@@ -400,7 +412,7 @@ void main() {
             if (SHMEM_STAGING == 0) {
             // For quants we always need to dequant into kvsh; for f16/bf16 we can load
             // directly from global memory when alignment / bounds allow it.
-            const bool stage_k = USE_DECODE_K || KV_bounds_check || USE_SPARSE || d * 16 + 16 > HSK;
+            const bool stage_k = USE_DECODE_K || KV_bounds_check || GATHER_KV || d * 16 + 16 > HSK;
             if (stage_k) {
                 barrier();
                 [[unroll]] for (uint32_t idx = 0; idx < Bc * MatBr / 4; idx += gl_WorkGroupSize.x) {
@@ -408,8 +420,11 @@ void main() {
                     uint32_t row = (idx + tid) / (MatBr / 4);
                     if (idx + tid < Bc * MatBr / 4) {
                         FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(0);
-                        uint32_t kcol;
-                        bool kv_active = fa_kv_index(j * Bc + row, kcol);
+                        uint32_t kcol = k_rows[idx / WorkGroupSize];
+                        bool kv_active = k_act[idx / WorkGroupSize];
+                        if (!USE_KV_ROWS) {
+                            kv_active = fa_kv_index(j * Bc + row, kcol);
+                        }
                         if (kv_active && (HSK == HSK_pad || d * 16 + col_vec * 4 < HSK)) {
 #if !defined(BFLOAT16)
                             if (USE_DECODE_K) {
@@ -573,6 +588,14 @@ void main() {

         const uint num_hsv_tiles = (HSV + MatBc * row_split - 1) / (MatBc * row_split); // round up

+        uint32_t v_rows_c[Bc * v_cols / WorkGroupSize];
+        bool v_act[v_rows_c.length()];
+        if (USE_KV_ROWS && SHMEM_STAGING == 0) {
+            [[unroll]] for (uint32_t i = 0; i < v_rows_c.length(); ++i) {
+                v_act[i] = fa_kv_index(j * Bc + (i * WorkGroupSize + tid) / v_cols, v_rows_c[i]);
+            }
+        }
+
         // Each subgroup handles HSV/4 columns
         [[unroll]] for (uint32_t hsv_tile = 0; hsv_tile < num_hsv_tiles; ++hsv_tile) {
             const uint hsv_offset = (hsv_tile * row_split + gl_SubgroupID) * 16;
@@ -592,22 +615,25 @@ void main() {
             if (SHMEM_STAGING == 0) {
             // For quants we always preload via kvsh. For f16/bf16 we only preload when
             // alignment / bounds force it (otherwise we coopMatLoad direct from data_vv4).
-            const bool stage_v = USE_DECODE_V || KV_bounds_check || USE_SPARSE;
+            const bool stage_v = USE_DECODE_V || KV_bounds_check || GATHER_KV;
             if (stage_v) {
                 [[unroll]] for (uint32_t i = 0; i < v_loads_per_thread; ++i) {
                     const uint idx = i * gl_WorkGroupSize.x + tid;
                     const uint row = idx / v_cols;
                     const uint col = idx % v_cols;

-                    uint32_t v_row;
-                    bool kv_active = fa_kv_index(j * Bc + row, v_row);
+                    uint32_t v_row = v_rows_c[i];
+                    bool kv_active = v_act[i];
+                    if (!USE_KV_ROWS) {
+                        kv_active = fa_kv_index(j * Bc + row, v_row);
+                    }
                     const uint v_col = hsv_tile * MatBc * row_split + col * 4;

                     const uint coord = v_row * v_stride * BLOCK_SIZE_V + v_col;
                     const uint ib = coord / BLOCK_SIZE_V;
                     const uint iqs = coord % BLOCK_SIZE_V;

-                    if (USE_SPARSE ? (kv_active && v_col < HSV) : (!KV_bounds_check || (v_row < KV && v_col < HSV))) {
+                    if (kv_active && v_col < HSV) {
 #if !defined(BFLOAT16)
                         if (USE_DECODE_V) {
                             kvsh[row * vsh_stride + col] = dequantize4(ib, iqs, v_offset, BINDING_IDX_V);
@@ -629,7 +655,7 @@ void main() {
             if (hsv_offset < HSV_pad) {
                 [[unroll]] for (uint32_t bc_chunk = 0; bc_chunk < Bc / MatBc; ++bc_chunk) {
                     if (SHMEM_STAGING == 0) {
-                    if (!USE_DECODE_V && !KV_bounds_check && !USE_SPARSE) {
+                    if (!USE_DECODE_V && !KV_bounds_check && !GATHER_KV) {
                         // F16/BF16 values can be loaded directly from global memory
                         const uint v_tile_row = j * Bc + bc_chunk * MatBc;
                         const uint v_tile_offset = v_offset / 4 + v_tile_row * v_stride / 4 + hsv_offset / 4;
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp
index 2c38dbc7e..e93f203bd 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp
@@ -134,7 +134,8 @@ void fl_load_k(const uint32_t j, const uint32_t k_offset) {
         if (idx < Bc * HSK_pad / 8) {
             const uint32_t c = idx / (HSK_pad / 8);
             const uint32_t d = idx % (HSK_pad / 8);
-            fl_kr[l] = data_ku[(k_offset + (j * Bc + c) * k_stride) / 8 + d];
+            uint32_t row;
+            fl_kr[l] = fa_kv_index(j * Bc + c, row) ? data_ku[(k_offset + row * k_stride) / 8 + d] : uvec4(0);
         }
     }
 }
@@ -148,7 +149,8 @@ void fl_load_v(const uint32_t j, const uint32_t v_offset) {
             if (FL_VT) {
                 c = (gl_LocalInvocationIndex / (HSV_pad / 8)) * FL_VLD + l;
             }
-            fl_vr[l] = data_vu[(v_offset + (j * Bc + c) * v_stride) / 8 + d];
+            uint32_t row;
+            fl_vr[l] = fa_kv_index(j * Bc + c, row) ? data_vu[(v_offset + row * v_stride) / 8 + d] : uvec4(0);
         }
     }
 }
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm2.comp
index 692ccdc4b..57fd203bd 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm2.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm2.comp
@@ -119,7 +119,7 @@ layout (binding = 1) readonly buffer K {uint8_t data_k[];};
 layout (binding = 2) readonly buffer V {uint8_t data_v[];};
 layout (binding = 3) readonly buffer M {uint8_t data_m[];};

-// Native 16-bit aliases for the sparse gather callbacks.
+// Native 16-bit aliases for the gather callbacks.
 layout (binding = 1) readonly buffer K16 {FLOAT_TYPE data_k16[];};
 layout (binding = 2) readonly buffer V16 {FLOAT_TYPE data_v16[];};
 layout (binding = 3) readonly buffer MF16 {float16_t data_mf16[];};
@@ -132,57 +132,53 @@ layout (binding = 2) readonly buffer V16V4 {FLOAT_TYPEV4 data_v16v4[];};
 uint32_t g_k_off_elem, g_v_off_elem, g_m_off_elem;

 FLOAT_TYPE faGatherK(const decodeBufFA_K bl_in, const uint32_t blockCoords[2], const uint32_t coordInBlock[2]) {
-    if (blockCoords[0] >= p.split_kv) { return FLOAT_TYPE(0.0); }
-    const int r = data_sparse[sparse_base + blockCoords[0]];
-    if (r < 0) { return FLOAT_TYPE(0.0); }
+    uint r;
+    if (!fa_kv_index(blockCoords[0], r)) { return FLOAT_TYPE(0.0); }
 #if !defined(BFLOAT16)
     if (USE_DECODE_K) {
-        decodeBufFA_K block = decodeBufFA_K(decodeBufFA_Byte(bl_in) + uint64_t(uint(r) - blockCoords[0]) * k_stride * FaBlockBytesK);
+        decodeBufFA_K block = decodeBufFA_K(decodeBufFA_Byte(bl_in) + uint64_t(int64_t(r) - int64_t(blockCoords[0])) * k_stride * FaBlockBytesK);
         return faDecodeK(block, blockCoords, coordInBlock);
     }
 #endif
-    return data_k16[g_k_off_elem + uint(r) * k_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1]];
+    return data_k16[g_k_off_elem + r * k_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1]];
 }

 FLOAT_TYPE faGatherV(const decodeBufFA_V bl_in, const uint32_t blockCoords[2], const uint32_t coordInBlock[2]) {
-    if (blockCoords[0] >= p.split_kv) { return FLOAT_TYPE(0.0); }
-    const int r = data_sparse[sparse_base + blockCoords[0]];
-    if (r < 0) { return FLOAT_TYPE(0.0); }
+    uint r;
+    if (!fa_kv_index(blockCoords[0], r)) { return FLOAT_TYPE(0.0); }
 #if !defined(BFLOAT16)
     if (USE_DECODE_V) {
-        decodeBufFA_V block = decodeBufFA_V(decodeBufFA_Byte(bl_in) + uint64_t(uint(r) - blockCoords[0]) * v_stride * FaBlockBytesV);
+        decodeBufFA_V block = decodeBufFA_V(decodeBufFA_Byte(bl_in) + uint64_t(int64_t(r) - int64_t(blockCoords[0])) * v_stride * FaBlockBytesV);
         return faDecodeV(block, blockCoords, coordInBlock);
     }
 #endif
-    return data_v16[g_v_off_elem + uint(r) * v_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1]];
+    return data_v16[g_v_off_elem + r * v_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1]];
 }

 #ifdef GL_NV_cooperative_matrix_decode_vector
 FLOAT_TYPEV4 faGatherKVector(const decodeBufFA_K bl_in, const uint32_t blockCoords[2], const uint32_t coordInBlock[2]) {
-    if (blockCoords[0] >= p.split_kv) { return FLOAT_TYPEV4(0.0); }
-    const int r = data_sparse[sparse_base + blockCoords[0]];
-    if (r < 0) { return FLOAT_TYPEV4(0.0); }
+    uint r;
+    if (!fa_kv_index(blockCoords[0], r)) { return FLOAT_TYPEV4(0.0); }
 #if !defined(BFLOAT16)
     if (USE_DECODE_K) {
-        decodeBufFA_K block = decodeBufFA_K(decodeBufFA_Byte(bl_in) + uint64_t(uint(r) - blockCoords[0]) * k_stride * FaBlockBytesK);
+        decodeBufFA_K block = decodeBufFA_K(decodeBufFA_Byte(bl_in) + uint64_t(int64_t(r) - int64_t(blockCoords[0])) * k_stride * FaBlockBytesK);
         return faDecodeKVector(block, blockCoords, coordInBlock);
     }
 #endif
-    const uint32_t o = g_k_off_elem + uint(r) * k_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1];
+    const uint32_t o = g_k_off_elem + r * k_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1];
     return data_k16v4[o / 4];
 }

 FLOAT_TYPEV4 faGatherVVector(const decodeBufFA_V bl_in, const uint32_t blockCoords[2], const uint32_t coordInBlock[2]) {
-    if (blockCoords[0] >= p.split_kv) { return FLOAT_TYPEV4(0.0); }
-    const int r = data_sparse[sparse_base + blockCoords[0]];
-    if (r < 0) { return FLOAT_TYPEV4(0.0); }
+    uint r;
+    if (!fa_kv_index(blockCoords[0], r)) { return FLOAT_TYPEV4(0.0); }
 #if !defined(BFLOAT16)
     if (USE_DECODE_V) {
-        decodeBufFA_V block = decodeBufFA_V(decodeBufFA_Byte(bl_in) + uint64_t(uint(r) - blockCoords[0]) * v_stride * FaBlockBytesV);
+        decodeBufFA_V block = decodeBufFA_V(decodeBufFA_Byte(bl_in) + uint64_t(int64_t(r) - int64_t(blockCoords[0])) * v_stride * FaBlockBytesV);
         return faDecodeVVector(block, blockCoords, coordInBlock);
     }
 #endif
-    const uint32_t o = g_v_off_elem + uint(r) * v_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1];
+    const uint32_t o = g_v_off_elem + r * v_stride + blockCoords[1] * FA_GATHER_BS + coordInBlock[1];
     return data_v16v4[o / 4];
 }

@@ -202,13 +198,12 @@ FLOAT_TYPEV4 faGatherVVector(const decodeBufFA_V bl_in, const uint32_t blockCoor

 ACC_TYPE faAddSparseMask(const uint32_t row, const uint32_t col, const ACC_TYPE elem, const uint32_t jblk) {
     const uint32_t kvslot = jblk * Bc + col;
-    if (kvslot >= p.split_kv) { return ACC_TYPE_NEG; }
-    const int r = data_sparse[sparse_base + kvslot];
-    if (r < 0) { return ACC_TYPE_NEG; }
-    ACC_TYPE mv = ACC_TYPE(data_mf16[g_m_off_elem + row * m_stride + uint(r)]);
+    uint r;
+    if (!fa_kv_index(kvslot, r)) { return ACC_TYPE_NEG; }
+    ACC_TYPE mv = ACC_TYPE(data_mf16[g_m_off_elem + row * m_stride + r]);
     uint32_t bq, bh;
     if (USE_BIAS && fa_bias_row(row, bq, bh)) {
-        mv += ACC_TYPE(fa_bias(bq, bh, uint(r)));
+        mv += ACC_TYPE(fa_bias(bq, bh, r));
     }
     return elem + mv;
 }
@@ -344,8 +339,8 @@ void main() {

     tensorViewNV<2, false, 1, 0> tensorViewTranspose = createTensorViewNV(2, false, 1, 0);

-    const uint bs_k = USE_SPARSE ? max(FA_GATHER_BS, BLOCK_SIZE_K) : BLOCK_SIZE_K;
-    const uint bs_v = USE_SPARSE ? max(FA_GATHER_BS, BLOCK_SIZE_V) : BLOCK_SIZE_V;
+    const uint bs_k = GATHER_KV ? max(FA_GATHER_BS, BLOCK_SIZE_K) : BLOCK_SIZE_K;
+    const uint bs_v = GATHER_KV ? max(FA_GATHER_BS, BLOCK_SIZE_V) : BLOCK_SIZE_V;
     tensorLayoutK = setTensorLayoutBlockSizeNV(tensorLayoutK, 1, bs_k);
     tensorLayoutV = setTensorLayoutBlockSizeNV(tensorLayoutV, 1, bs_v);

@@ -480,6 +475,9 @@ void main() {
             }
         }

+#ifdef FA_KV_ROWS_SHMEM
+        fa_kv_rows_load(j);
+#endif
 #ifdef FA_BIAS_STAGE
         if (MASK_ENABLE) {
             barrier();
@@ -494,7 +492,7 @@ void main() {

         uint32_t k_offset = ik2*p.nb12 + ik3*p.nb13;
         // F16: bs_k==1 (direct load). F32: bs_k==4 (vec4 / dequantFuncF32). Quantized types: bs_k==32.
-        if (USE_SPARSE) {
+        if (GATHER_KV) {
             coopMatLoadTensorNV(K_T, data_k, k_offset, sliceTensorLayoutNV(tensorLayoutK, j * Bc, Bc, 0, HSK_pad), tensorViewTranspose FAGATHERK);
 #if !defined(BFLOAT16)
         } else if (USE_DECODE_K) {
@@ -575,7 +573,7 @@ void main() {

         coopmat<FLOAT_TYPE, gl_ScopeWorkgroup, Bc, HSV_pad, gl_MatrixUseB> V;
         uint32_t v_offset = iv2*p.nb22 + iv3*p.nb23;
-        if (USE_SPARSE) {
+        if (GATHER_KV) {
             coopMatLoadTensorNV(V, data_v, v_offset, sliceTensorLayoutNV(tensorLayoutV, j * Bc, Bc, 0, HSV_pad) FAGATHERV);
 #if !defined(BFLOAT16)
         } else if (USE_DECODE_V) {
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp
index 293749fc6..4d19e3aee 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp
@@ -18,6 +18,9 @@ layout (binding = 3) buffer P {float16_t data_p[];};
 layout (binding = 4) buffer MAX {float data_max[];};
 layout (binding = 5) readonly buffer BT {float data_bias_table[];};
 layout (binding = 6) readonly buffer BI {int data_bias_idx[];};
+#ifdef KV_ROWS
+layout (binding = 7) readonly buffer KR {int data_kv_rows[];};
+#endif

 layout (push_constant) uniform parameter
 {
@@ -90,6 +93,12 @@ shared shf16v4_alias {
     f16vec4 F16V4sh[ksh_size / 4];
 } F16V4Poolsh;

+#ifdef KV_ROWS
+int kv_row(const uint base, const uint lin) {
+    return lin < p.nek1 ? data_kv_rows[base + lin] : -1;
+}
+#endif
+
 void main() {
     const uint lane = gl_SubgroupInvocationID;
     const uint head_k_idx = gl_WorkGroupID.x % p.nek2;
@@ -119,6 +128,9 @@ void main() {
     const uint k_seq_boundary = ((p.nek1 - 1) * k_dim + batch_k_idx * p.nbk3 + head_k_idx * p.nbk2 + HSK) / 4 - 1;
     const uint k_head_base = (batch_k_idx * p.nbk3 + head_k_idx * p.nbk2) / 4;
     const float NEG_FLT_MAX_OVER_2 = uintBitsToFloat(0xFEFFFFFF);
+#ifdef KV_ROWS
+    const uint kv_rows_base = batch_idx * p.nek1;
+#endif

     float Maskf[p_reduce / SubGroupSize];

@@ -158,7 +170,12 @@ void main() {
             uint k_offset = k_base + row_idx * k_dim / 4 + col_idx;
             k_offset = min(k_offset, k_seq_boundary);
             const uint ksh_offset = (row_idx * TK + sh_chunk_r * TK * p_per_loop) / 4 + sh_chunk_c;
+#ifdef KV_ROWS
+            const int kr = kv_row(kv_rows_base, p_idx * p_reduce + row_idx);
+            F16V4Poolsh.F16V4sh[ksh_offset] = kr >= 0 ? data_kv4[k_head_base + uint(kr) * k_dim / 4 + col_idx] : f16vec4(0.0f);
+#else
             F16V4Poolsh.F16V4sh[ksh_offset] = data_kv4[k_offset];
+#endif
         }
     }

@@ -173,7 +190,12 @@ void main() {
                     const uint col_idx = flat_offset % hsk_v4;
                     uint k_offset = k_base + row_idx * k_dim / 4 + col_idx;
                     k_offset = min(k_offset, k_seq_boundary);
+#ifdef KV_ROWS
+                    const int kr = kv_row(kv_rows_base, p_idx * p_reduce + row_idx);
+                    kv4_temp[idx] = kr >= 0 ? data_kv4[k_head_base + uint(kr) * k_dim / 4 + col_idx] : f16vec4(0.0f);
+#else
                     kv4_temp[idx] = data_kv4[k_offset];
+#endif
                 }
             }
         }
@@ -202,7 +224,12 @@ void main() {
                             const uint col_idx = flat_offset % (TK / 4);
                             const uint k_temp_offset = kv4_base_offset + row_idx * p.nbk1 / 4 + col_idx;
                             const uint ksh_temp_offset = sg * TM * TK / 4 + idx * SubGroupSize + lane;
+#ifdef KV_ROWS
+                            const int kr = kv_row(kv_rows_base, k_base_row + row_idx);
+                            f16vec4 kv4_temp = kr >= 0 ? data_kv4[k_head_base + uint(kr) * p.nbk1 / 4 + loop * TK / 4 + col_idx] : f16vec4(0.0f);
+#else
                             f16vec4 kv4_temp = (k_base_row + row_idx) < p.nek1 ? data_kv4[k_temp_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f);
+#endif
                             F16V4Poolsh.F16V4sh[ksh_temp_offset] = kv4_temp;
                         }

diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp
index 42a5101d8..f8987efb5 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp
@@ -17,6 +17,9 @@ layout (binding = 1) readonly buffer VV4 {f16vec4 data_vv4[];};
 layout (binding = 2) readonly buffer MAX {float data_max[];};
 layout (binding = 3) readonly buffer S {float data_s[];};
 layout (binding = 4) buffer OV4 {vec4 data_ov4[];};
+#ifdef KV_ROWS
+layout (binding = 5) readonly buffer KR {int data_kv_rows[];};
+#endif

 layout (push_constant) uniform parameter
 {
@@ -105,9 +108,22 @@ shared shf16_alias {
     float16_t F16sh[SLM_POOL_SIZE_GLOBAL_MAX * 2 + SLM_POOL_SIZE_SOFTMAX_SUM * 2 + SLM_POOL_SIZE_MAX * 2 * 2 + psh_size * 2];
 } F16Poolsh;

+#ifdef KV_ROWS
+const uint vrows_sh_base = (psh_base + psh_size * 2) / 4;
+shared shf16v4_alias {
+    f16vec4 F16V4sh[vrows_sh_base + SLM_POOL_SIZE_OOB_STAGING];
+} F16V4Poolsh;
+#else
 shared shf16v4_alias {
     f16vec4 F16V4sh[(SLM_POOL_SIZE_GLOBAL_MAX + SLM_POOL_SIZE_SOFTMAX_SUM + SLM_POOL_SIZE_MAX * 2) / 2 + SLM_POOL_SIZE_OOB_STAGING];
 } F16V4Poolsh;
+#endif
+
+#ifdef KV_ROWS
+int kv_row(const uint base, const uint lin) {
+    return lin < p.nek1 ? data_kv_rows[base + lin] : -1;
+}
+#endif

 void main() {
     const uint lane = gl_SubgroupInvocationID;
@@ -131,6 +147,11 @@ void main() {
     const float NEG_FLT_MAX_OVER_2 = uintBitsToFloat(0xFEFFFFFF);
     const float POS_FLT_MAX_OVER_2 = uintBitsToFloat(0x7EFFFFFF);
     uint v_offset = v_base;
+#ifdef KV_ROWS
+    const uint kv_rows_base = batch_idx * p.nek1;
+    const uint v_head_base = (batch_v_idx * p.nbv3 + head_v_idx * p.nbv2 + v_idx * Bc) / 4;
+    const uint v_stage_count = TM * TK / SubGroupSize / 4;
+#endif

     coopmat<float, gl_ScopeSubgroup, TM, TN, gl_MatrixUseAccumulator> OMat[omat_row][omat_col];
     f16vec4 pv4_temp[p_loops];
@@ -292,9 +313,29 @@ void main() {
         {
             const uint coord_p = psh_base + sh_pingpong_load * psh_size + sg * TK;
             coopmat<float16_t, gl_ScopeSubgroup, TM, TK, gl_MatrixUseA> VMat[omat_col];
+#ifdef KV_ROWS
+            uint v_row_offset[v_stage_count];
+            bool v_row_valid[v_stage_count];
+            [[unroll]] for (uint idx = 0; idx < v_stage_count; ++idx) {
+                const uint vv4_idx = idx * SubGroupSize + lane;
+                const int vr = kv_row(kv_rows_base, loop * p_per_loop + sg * TK + vv4_idx / (TM / 4));
+                v_row_valid[idx] = vr >= 0;
+                v_row_offset[idx] = v_head_base + uint(max(vr, 0)) * p.nbv1 / 4 + vv4_idx % (TM / 4);
+            }
+            const uint vv4sh_rows = vrows_sh_base + sg * TM * TK / 4;
+            [[unroll]] for (uint c = 0; c < omat_col; ++c) {
+                [[unroll]] for (uint idx = 0; idx < v_stage_count; ++idx) {
+                    F16V4Poolsh.F16V4sh[vv4sh_rows + idx * SubGroupSize + lane] = v_row_valid[idx] ? data_vv4[v_row_offset[idx] + c * TM / 4] : f16vec4(0.0f);
+                }
+                subgroupBarrier();
+                coopMatLoad(VMat[c], F16V4Poolsh.F16V4sh, vv4sh_rows, TM / 4, gl_CooperativeMatrixLayoutColumnMajor);
+                subgroupBarrier();
+            }
+#else
             [[unroll]] for (uint c = 0; c < omat_col; ++c) {
                 coopMatLoad(VMat[c], data_v, v_offset + TM * c, v_dim, gl_CooperativeMatrixLayoutColumnMajor);
             }
+#endif
             [[unroll]] for (uint r = 0; r < omat_row; ++r) {
                 coopmat<float16_t, gl_ScopeSubgroup, TK, TN, gl_MatrixUseB> PMat;
                 coopMatLoad(PMat, F16Poolsh.F16sh, coord_p + r * TN * p_per_loop, p_per_loop, gl_CooperativeMatrixLayoutColumnMajor);
@@ -344,9 +385,13 @@ void main() {
                 const uint vv4_idx = idx * SubGroupSize + lane;
                 const uint row_idx = vv4_idx / (TM / 4);
                 const uint col_idx = vv4_idx % (TM / 4);
+#ifdef KV_ROWS
+                const int vr = kv_row(kv_rows_base, v_global_coord_base + row_idx);
+                f16vec4 vv4_temp = vr >= 0 ? data_vv4[v_head_base + uint(vr) * p.nbv1 / 4 + c * TM / 4 + col_idx] : f16vec4(0.0f);
+#else
                 const uint vv4_offset = v_global_offset + row_idx * p.nbv1 / 4 + c * TM / 4 + col_idx;
-
                 f16vec4 vv4_temp = (v_global_coord_base + row_idx < p.nek1) ? data_vv4[vv4_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f);
+#endif
                 F16V4Poolsh.F16V4sh[vv4sh_base + vv4_idx] = vv4_temp;
             }

diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_kv_rows_copy.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_kv_rows_copy.comp
new file mode 100644
index 000000000..cd8e11832
--- /dev/null
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_kv_rows_copy.comp
@@ -0,0 +1,30 @@
+#version 450
+
+layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
+
+layout (binding = 0) readonly buffer A {uvec4 data_a[];};
+layout (binding = 1) writeonly buffer D {uvec4 data_d[];};
+layout (binding = 2) readonly buffer R {int data_rows[];};
+
+layout (push_constant) uniform parameter {
+    uint head_size;
+    uint n_heads;
+    uint n_cols;
+    uint n_cache_rows;
+    uint n_elements;
+} p;
+
+void main() {
+    const uint i = gl_GlobalInvocationID.x;
+    if (i >= p.n_elements / 8) {
+        return;
+    }
+
+    const uint head_vecs = p.head_size / 8;
+    const uint d = i % head_vecs;
+    const uint head = (i / head_vecs) % p.n_heads;
+    const uint list_idx = i / (head_vecs * p.n_heads);
+    const uint row = uint(data_rows[list_idx]);
+    const uint dst = ((list_idx / p.n_cols * p.n_heads + head) * p.n_cols + list_idx % p.n_cols) * head_vecs + d;
+    data_d[dst] = row < p.n_cache_rows ? data_a[(row * p.n_heads + head) * head_vecs + d] : uvec4(0);
+}
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
index dc0c61e73..29df658de 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
@@ -748,6 +748,8 @@ void process_shaders() {
                     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");
+                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_KV_ROWS_SHMEM", "1"}}), fp16, false, true, f16acc, "_rows");
 #endif

 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
@@ -802,6 +804,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"}, {"FA_BIAS_STAGE", "1"}}),
         true, false, true, false, "_bias");
+    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_KV_ROWS_SHMEM", "1"}}),
+        true, false, true, false, "_rows");
 #endif

     std::map<std::string, std::string> base_dict = {{"FLOAT_TYPE", "float"}, {"FLOAT_TYPEV2", "vec2"}};
@@ -979,11 +984,14 @@ void process_shaders() {
 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
     string_to_spv("fa_decode_ph1", "flash_attn_decode_phase_1.comp", {}, true, true, false, false);
     string_to_spv("fa_decode_ph2", "flash_attn_decode_phase_2.comp", {}, true, true, false, false);
+    string_to_spv("fa_decode_ph1", "flash_attn_decode_phase_1.comp", {{"KV_ROWS", "1"}}, true, true, false, false, "_rows");
+    string_to_spv("fa_decode_ph2", "flash_attn_decode_phase_2.comp", {{"KV_ROWS", "1"}}, true, true, false, false, "_rows");
     string_to_spv("fa_prefill", "flash_attn_prefill.comp", {}, true, true, false, false);
 #endif

     string_to_spv("fa_sparse_compact", "flash_attn_sparse_compact.comp", {});
     string_to_spv("fa_sparse_compact_subgroup", "flash_attn_sparse_compact.comp", {{"USE_SUBGROUPS", "1"}});
+    string_to_spv("fa_kv_rows_copy", "flash_attn_kv_rows_copy.comp", {});

     string_to_spv("quantize_q8_1", "quantize_q8_1.comp", {});
     string_to_spv("quantize_q8_1_subgroup", "quantize_q8_1.comp", {{"USE_SUBGROUPS", "1"}});
diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
index 485995e50..01bb6d069 100644
--- a/ggml/src/ggml.c
+++ b/ggml/src/ggml.c
@@ -5527,6 +5527,8 @@ static struct ggml_tensor * ggml_flash_attn_ext_impl(
         float                 max_bias,
         float                 logit_softcap) {
     GGML_ASSERT(ggml_can_mul_mat(k, q));
+    GGML_ASSERT(ggml_is_contiguous_rows(q));
+    GGML_ASSERT(q->nb[1] % 16 == 0 && q->nb[2] % 16 == 0 && q->nb[3] % 16 == 0);
     // TODO: check if vT can be multiplied by (k*qT)

     if (kv_rows) {
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index c0c29a0ee..82baacb5b 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -10575,11 +10575,12 @@ struct test_flash_attn_ext_kv_rows : public test_case {
     const int64_t nb;       // queries per slice
     const int64_t n_slices;
     const ggml_type type_KV;
+    const bool empty_slice;

     std::vector<int32_t> rows;

     std::string vars() override {
-        return VARS_TO_STR8(hs, nh, gqa, n_cells, kv, nb, n_slices, type_KV);
+        return VARS_TO_STR9(hs, nh, gqa, n_cells, kv, nb, n_slices, type_KV, empty_slice);
     }

     double max_nmse_err() override {
@@ -10587,8 +10588,8 @@ struct test_flash_attn_ext_kv_rows : public test_case {
     }

     test_flash_attn_ext_kv_rows(int64_t hs = 256, int64_t nh = 2, int64_t gqa = 8, int64_t n_cells = 2048, int64_t kv = 512,
-                                int64_t nb = 8, int64_t n_slices = 4, ggml_type type_KV = GGML_TYPE_F16)
-        : hs(hs), nh(nh), gqa(gqa), n_cells(n_cells), kv(kv), nb(nb), n_slices(n_slices), type_KV(type_KV) {}
+                                int64_t nb = 8, int64_t n_slices = 4, ggml_type type_KV = GGML_TYPE_F16, bool empty_slice = false)
+        : hs(hs), nh(nh), gqa(gqa), n_cells(n_cells), kv(kv), nb(nb), n_slices(n_slices), type_KV(type_KV), empty_slice(empty_slice) {}

     ggml_tensor * build_graph(ggml_context * ctx) override {
         ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_slices);
@@ -10622,7 +10623,7 @@ struct test_flash_attn_ext_kv_rows : public test_case {
         // per slice: distinct random cells, the tail of the list is padding
         rows.assign(kv*n_slices, -1);
         std::vector<int32_t> order(n_cells);
-        for (int64_t s = 0; s < n_slices; ++s) {
+        for (int64_t s = 0; s < n_slices - empty_slice; ++s) {
             for (int64_t i = 0; i < n_cells; ++i) {
                 order[i] = i;
             }
@@ -15177,9 +15178,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
     // asymmetric head_dim (hsk != hsv) with one or both sides not 64-aligned
     test_cases.emplace_back(new test_flash_attn_ext(72, 64, 4, {1, 1}, 256, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
     test_cases.emplace_back(new test_flash_attn_ext(64, 72, 4, {1, 1}, 256, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
-    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, true, true, 8.0f, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
-    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 17, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
-    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
+    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, true, true, 8.0f, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 0, 3));
+    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 17, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 0, 3));
+    test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 0, 3));

     // mixed quant and Q1_0 test cases
     test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0));
@@ -15246,6 +15247,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
     test_cases.emplace_back(new test_flash_attn_ext(128, 128, 1, { 8, 1}, 4096, 4, true, false, 8.0f, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false,  512));

     // flash attention over a list of K/V rows per slice (unified KV cache)
+    test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 1, 1000, 257, 3, 2, GGML_TYPE_F16, true));
+    test_cases.emplace_back(new test_flash_attn_ext_kv_rows(64, 2, 1, 1000, 257, 256, 2, GGML_TYPE_F16, true));
+    test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 1, 1000, 256, 8, 2, GGML_TYPE_BF16));
+    test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 1, 1000, 256, 256, 2, GGML_TYPE_BF16));
     for (int64_t nb : {1, 3, 8, 64, 512}) {
         for (int64_t n_slices : {1, 4}) {
             test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 2, 8, 4096, 1024, nb, n_slices));