Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[gpu][paged_attention]: Optimized bidirectional mask range calculation in paged attention kernel. (#35552)

Piotr Kowalczykd7c4dcffd7f9
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
index df0735b0dce..6fa2573f698 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
@@ -1085,33 +1085,117 @@ inline SEQ_RANGE FUNC(calc_sliding_window_seq_range)(const SEQ_RANGE default_seq
#endif
#if HAS_TOKEN_TYPE_IDS
- // Bidirectional attention for image token groups (e.g. Gemma3 VLM):
- // Compute per-lane effective causal limit to extend the visible range for image tokens
- // This is a REFERENCE implementation.
+// Cooperative wg search for the first zero idx in token_type_ids.
+#define FIND_FIRST_ZERO_IDX_WG_TEMPLATE(CLEAR_VAL, REDUCTION_OP, ADVANCE_EXPRESSION, EDGE_CASE_CHECK, INIT_IDX) \
+ const int sgid = get_sub_group_id(); \
+ const int sglid = get_sub_group_local_id(); \
+ const int lid = get_local_linear_id(); \
+ const int num_of_work_items = get_num_sub_groups()*get_sub_group_size(); \
+ \
+ const int base = start_idx; \
+ int idx_this_thread = INIT_IDX; \
+ int block_first_idx = CLEAR_VAL; \
+ bool work_group_should_contine_loop = true; \
+ while (work_group_should_contine_loop) { \
+ const bool is_zero = idx_this_thread EDGE_CASE_CHECK ? token_type_ids[idx_this_thread] == 0 : true; \
+ int min_idx_this_subgroup = sub_group_reduce_##REDUCTION_OP(is_zero ? idx_this_thread : CLEAR_VAL); \
+ \
+ if( sglid == 0 ) \
+ reduction_buffer[sgid] = min_idx_this_subgroup; \
+ \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ \
+ int reduce_val = CLEAR_VAL; \
+ for(int idx = sglid; idx < SUBGROUPS_PER_WG; idx += SUBGROUP_SIZE) { \
+ reduce_val = REDUCTION_OP(reduce_val, reduction_buffer[idx]); \
+ } \
+ \
+ block_first_idx = sub_group_reduce_##REDUCTION_OP(reduce_val); \
+ idx_this_thread ADVANCE_EXPRESSION num_of_work_items; \
+ work_group_should_contine_loop = (block_first_idx == CLEAR_VAL); \
+ } \
+ return block_first_idx;
+
+
+ inline int FUNC(find_first_zero_to_the_right_wg)(const __global int* token_type_ids,
+ __local int* reduction_buffer, int start_idx, int seq_len) {
+ FIND_FIRST_ZERO_IDX_WG_TEMPLATE(INT_MAX, min, +=, < seq_len, base + lid)
+ }
+
+ inline int FUNC(find_first_zero_to_the_left_wg)(const __global int* token_type_ids,
+ __local int* reduction_buffer, int start_idx, int seq_len) {
+ FIND_FIRST_ZERO_IDX_WG_TEMPLATE(INT_MIN, max, -=, >= 0, base - num_of_work_items + lid)
+ }
+
+ // Function calculates the range of bidirectional mask for this work item.
inline SEQ_RANGE FUNC(calc_bi_dir_seq_range)(
- const __global int* token_type_ids,
- const int seq_len,
- const SEQ_RANGE default_seq_range) {
+ const __global int* token_type_ids,
+ __local int* reduction_buffer,
+ const int seq_len,
+ const SEQ_RANGE default_seq_range,
+ bool begin_needed) {
+
+ // For this wg, each subgroup's work item min and max seq idx
+ // will be in the range of:
+ // [default_seq_range.subgroup_max - SUBGROUP_SIZE, default_seq_range.subgroup_max]
+ // So we can safetly assume that wg have to check:
+ // 1) where ends token group starting from default_seq_range.subgroup_max
+ // 2) where begins token group starting from default_seq_range.subgroup_max - SUBGROUP_SIZE
+ // becasue it will be the same for all work items.
+ // Wg will simply cooperatively calculate the first idx for which the token_type_id
+ // is equal to zero to the left and right from the above range.
+
+ // Optimization assumptions:
+ // 1) default_block_range_end - default_block_range_begin <= SUBGROUP_SIZE
+ // 2) all subgroups work on the same default_block_range
+
+ const int default_block_range_begin = max(0, default_seq_range.subgroup_max - SUBGROUP_SIZE);
+ const int default_block_range_end = default_seq_range.subgroup_max;
+ int found_block_range_end = default_block_range_end;
+ int found_block_range_begin = default_block_range_begin;
+
+ // block cooperative search for token group end
+ if (token_type_ids[default_block_range_end - 1] == 1) {
+ found_block_range_end = FUNC_CALL(find_first_zero_to_the_right_wg)(token_type_ids, reduction_buffer, default_block_range_end, seq_len);
+ }
+
+ // block cooperative search for token group start
+ if (token_type_ids[default_block_range_begin] == 1 && begin_needed) {
+ found_block_range_begin = FUNC_CALL(find_first_zero_to_the_left_wg)(token_type_ids, reduction_buffer, default_block_range_begin - 1, seq_len) + 1;
+ }
+
int token_group_end = default_seq_range.max;
int token_group_begin = default_seq_range.max;
+ // Special case: image group is less than subgroup size.
if (token_type_ids[token_group_end] == 1) {
int new_group_end = token_group_end + 1;
- while (new_group_end < seq_len && token_type_ids[new_group_end] == 1) {
+ while (new_group_end < default_block_range_end && token_type_ids[new_group_end] == 1) {
new_group_end++;
}
token_group_end = new_group_end - 1;
- int new_group_begin = token_group_begin - 1;
- while (new_group_begin >= 0 && token_type_ids[new_group_begin] == 1) {
- new_group_begin--;
+ if (token_group_end == (default_block_range_end - 1)) {
+ token_group_end = found_block_range_end - 1;
+ }
+
+ if (begin_needed) {
+ int new_group_begin = token_group_begin - 1;
+ while (new_group_begin >= default_block_range_begin && token_type_ids[new_group_begin] == 1) {
+ new_group_begin--;
+ }
+ token_group_begin = new_group_begin + 1;
+
+ if (token_group_begin == default_block_range_begin) {
+ token_group_begin = found_block_range_begin;
+ }
}
- token_group_begin = new_group_begin + 1;
}
+
SEQ_RANGE range;
range.min = token_group_begin;
range.max = token_group_end;
- range.subgroup_max = sub_group_reduce_max(token_group_end) + 1;
+ range.subgroup_max = found_block_range_end;
return range;
}
#endif
@@ -1220,6 +1304,18 @@ KERNEL(sdpa_opt)(
__local SOFTMAX_ACCUMULATOR_TYPE slm_max_val_cur[TARGET_SEQ_LEN_BLOCK_SIZE];
#endif
+#ifdef HAS_TOKEN_TYPE_IDS
+ // NOTE: if allocation of reduce_buffer causes SLM spill,
+ // we can reuse any other big enough allocated buffer.
+ // Having separate buffer makes the code easier to understand.
+ __local int reduce_buffer[SUBGROUPS_PER_WG];
+
+
+#if SUBGROUPS_PER_WG * SUBGROUP_SIZE != SEQ_LEN_PARTITION_SIZE
+ #error "sdpa_opt.cl: Unsupported configuration with token type ids. SUBGROUPS_PER_WG * SUBGROUP_SIZE must be equal to SEQ_LEN_PARTITION_SIZE."
+#endif
+#endif
+
#if IS_PAGED_ATTENTION
const uint block_start_pos = blocked_indexes_start[target_seq_dim];
const uint block_end_pos = blocked_indexes_end[target_seq_dim];
@@ -1234,9 +1330,11 @@ KERNEL(sdpa_opt)(
#if IS_PAGED_ATTENTION
#if HAS_TOKEN_TYPE_IDS
- const SEQ_RANGE bi_dir_range = FUNC_CALL(calc_bi_dir_seq_range)(token_type_ids,
- SOURCE_SEQ_LEN,
- default_this_work_item_seq_range);
+ const SEQ_RANGE bi_dir_range = FUNC_CALL(calc_bi_dir_seq_range)(token_type_ids,
+ reduce_buffer,
+ SOURCE_SEQ_LEN,
+ default_this_work_item_seq_range,
+ SLIDING_WINDOW_SIZE != 0);
this_work_item_seq_range_temp = bi_dir_range;
#endif //< HAS_TOKEN_TYPE_IDS
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
index d4a2b2857d7..167c16ce971 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
@@ -135,6 +135,9 @@ struct PagedAttentionManager {
std::vector<std::vector<uint8_t>> qq_bias;
std::vector<int> qq_bias_begins;
+
+ // optional token_type_ids; when empty, a default single-element {0} buffer is used
+ std::vector<int> token_type_ids;
cldnn::engine& test_engine;
cldnn::stream& test_stream;
tests::random_generator& rg;
@@ -835,8 +838,11 @@ struct PagedAttentionManager {
}
memory::ptr get_token_type_ids_memory() {
- std::vector<int> token_type_ids = { 0 };
- return get_memory_from_vec(token_type_ids);
+ if (!token_type_ids.empty()) {
+ return get_memory_from_vec(token_type_ids);
+ }
+ std::vector<int> default_token_type_ids = { 0 };
+ return get_memory_from_vec(default_token_type_ids);
}
memory::ptr get_qq_bias_memory() {
@@ -1807,6 +1813,7 @@ public:
void execute(T& p, bool run_reference = true) {
ov::element::Type kv_cache_precision = p.kv_cache_precision;
+
PagedAttentionManager pam(rg,
get_test_engine(),
get_test_stream(),
@@ -1867,6 +1874,11 @@ public:
pam.qq_bias_begins = p.qq_bias_config.qq_bias_begins;
}
+ if (p.token_type_ids.has_value()) {
+ pam.token_type_ids = p.token_type_ids.value();
+ ASSERT_EQ(pam.token_type_ids.size(), static_cast<size_t>(pam.subsequence_descs.back().num_tokens + pam.subsequence_descs.back().past_len));
+ }
+
if (p.kv_cache_compression) {
// INT4 quantization has larger error than INT8 (~17x larger step size)
tolerance = (kv_cache_precision == ov::element::u4 || kv_cache_precision == ov::element::i4) ? 75e-3 : 25e-3;
@@ -2044,6 +2056,7 @@ public:
pa_prim.heads_num = p.num_heads;
pa_prim.scale_val = pam.get_default_scale();
pa_prim.has_alibi = false;
+ pa_prim.has_token_type_ids = p.token_type_ids.has_value();
int num_outputs = 1;
if (p.scores_mode != ScoresMode::DISABLED) num_outputs++;
@@ -2838,6 +2851,10 @@ struct paged_attention_test_params {
bool has_qq_bias = false;
QueryToQueryAttentionDescriptor qq_bias_config = {};
bool run_reference = true;
+
+ // optional token_type_ids passed to PagedAttention; if set (non-empty), it is forwarded
+ // to the op as the TOKEN_TYPE_IDS input. When std::nullopt, a default {0} buffer is used.
+ std::optional<std::vector<int>> token_type_ids = std::nullopt;
};
class paged_attention_test : public PagedAttentionTest<paged_attention_test_params> {};
@@ -2939,6 +2956,22 @@ static paged_attention_test_params disable_reference_compare(paged_attention_tes
return p;
}
+static std::vector<int32_t> gen_tokens_ids_test_data(size_t seq_len, int num_images, size_t avg_img_len) {
+ std::vector<int32_t> v(seq_len, 0);
+ size_t gap = seq_len / (num_images + 1);
+ for (int img = 0; img < num_images; img++) {
+ size_t center = gap * (img + 1);
+ size_t half = avg_img_len / 2;
+ size_t start = (center > half) ? center - half : 0;
+ size_t end = std::min(seq_len, center + half);
+ for (size_t i = start; i < end; i++)
+ v[i] = 1;
+ }
+
+
+ return v;
+}
+
INSTANTIATE_TEST_SUITE_P(smoke_paged_attention, paged_attention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
/* with scores output, use SnapKV */
paged_attention_test_params{ {{10, 0}}, 2, 2, 64, 64, 16, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES_SNAPKV, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, false }, // 1st token
@@ -3428,3 +3461,10 @@ INSTANTIATE_TEST_SUITE_P(DISABLED_smoke_paged_attention_perf_cm, xattention_test
// mixed prefill+generate
disable_reference_compare(paged_attention_test_params{ {{1, 1*4096}, {1, 1*1024}, {4096, 1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f, 100.0f, 100.0f}, std::vector<int>{256, 256, 256} }),
}));
+
+static constexpr int TOKEN_IDS_SEQ_LEN = 8192;
+INSTANTIATE_TEST_SUITE_P(DISABLED_smoke_paged_attention_perf_token_ids_ocl, paged_attention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ disable_reference_compare(paged_attention_test_params{ {{TOKEN_IDS_SEQ_LEN, 0}}, 1, 1, 128, 128, 16, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, false, std::nullopt, std::nullopt, ov::element::dynamic, false, {}, true, gen_tokens_ids_test_data(TOKEN_IDS_SEQ_LEN, 3, TOKEN_IDS_SEQ_LEN/4) }),
+ disable_reference_compare(paged_attention_test_params{ {{TOKEN_IDS_SEQ_LEN, 0}}, 1, 1, 128, 128, 16, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, false, std::nullopt, std::nullopt, ov::element::dynamic, false, {}, true, gen_tokens_ids_test_data(TOKEN_IDS_SEQ_LEN, 1, TOKEN_IDS_SEQ_LEN) }),
+}));
+