OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU][PA] Support bidirectional masking in PagedAttention MIXED stage (#38897)
Jade Cho677c8ec737bc
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.clindex e9b08ccd9ac..e58319d9578 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl@@ -26,6 +26,46 @@#define DISABLE_QK_LOOP_UNROLL#endif+#if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+// An empty token_type_ids input (runtime size 0) disables the bidirectional masking.+#define TT_PRESENT (TOKEN_TYPE_IDS_BATCH_NUM > 0)+// token_type_ids has one value per scheduled token (all subsequences joined). Indexes below are global token indexes.+// A group is a run of 1s (type-1 tokens). All lanes of the sub-group get the same result.++// End (exclusive) of the group that contains `token`.+inline uint FUNC(pa_bidir_group_end)(const __global int* token_type_ids, const uint token, const uint subsequence_end) {+ const uint sglid = get_sub_group_local_id();+ uint e = token + 1;+ while (true) {+ const uint idx = e + sglid;+ const bool is_boundary = (idx >= subsequence_end) || (token_type_ids[idx] != 1);+ const uint first = sub_group_reduce_min(is_boundary ? idx : UINT_MAX);+ if (first != UINT_MAX) {+ return first;+ }+ e += SUBGROUP_SIZE;+ }+}++// Start (inclusive) of the group that contains `token`.+inline uint FUNC(pa_bidir_group_begin)(const __global int* token_type_ids, const uint token, const uint subsequence_begin) {+ const int sglid = (int)get_sub_group_local_id();+ const int lowest = (int)subsequence_begin - 1; // boundary just before the subsequence+ int e = (int)token; // lane l checks e - 1 - l+ while (true) {+ const int idx = e - 1 - sglid;+ // a token that is not type 1, or the subsequence start, ends the group+ const bool is_boundary = (idx <= lowest) || (token_type_ids[idx] != 1);+ // the nearest boundary has the largest index+ const int nearest = sub_group_reduce_max(is_boundary ? max(idx, lowest) : INT_MIN);+ if (nearest != INT_MIN) {+ return (uint)(nearest + 1);+ }+ e -= SUBGROUP_SIZE;+ }+}+#endif+#ifdef SDPA_STAGE_0#if SEQ_LEN_PARTITION_SIZE % PAGED_ATTENTION_BLOCK_SIZE != 0@@ -84,6 +124,9 @@ KERNEL(pa_sdpa_opt)(#if HAS_QQ_BIASconst __global QQ_BIAS_DATA_T* qq_bias,const __global QQ_BIAS_BEGINS_DATA_T* qq_bias_begins,+#endif+#if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+ const __global int* token_type_ids,#endif__global OUTPUT_TYPE* output,#if PAGED_ATTENTION_SCORES_OUTPUT@@ -165,8 +208,23 @@ KERNEL(pa_sdpa_opt)(const int subsequence_idx = gws_subseq_mapping[seq_idx];const int subsequence_begin = subsequence_begins[subsequence_idx];const int subsequence_end = subsequence_begins[subsequence_idx + 1];+#if !HAS_TOKEN_TYPE_IDSconst uint seq_len = past_lens[subsequence_idx] + 1 + (seq_idx - subsequence_begin);+#endifconst uint past_len = past_lens[subsequence_idx];+#if HAS_TOKEN_TYPE_IDS+ // causal_len: keys up to the query itself (used by ALiBi and the sliding window).+ // seq_len: keys really read. A type-1 token also reads the rest of its group.+ const uint causal_len = past_len + 1 + (seq_idx - subsequence_begin);+ uint seq_len = causal_len;+ uint sliding_window_begin_ext = 0xFFFFFFFFu; // window start of a type-1 token: its group start+ if (TT_PRESENT && token_type_ids[seq_idx] == 1) {+ seq_len = past_len + (FUNC_CALL(pa_bidir_group_end)(token_type_ids, seq_idx, subsequence_end) - subsequence_begin);+ #if SLIDING_WINDOW_SIZE != 0+ sliding_window_begin_ext = past_len + (FUNC_CALL(pa_bidir_group_begin)(token_type_ids, seq_idx, subsequence_begin) - subsequence_begin);+ #endif+ }+#endif#if HAS_QQ_BIASconst uint qq_bias_num = qq_bias_begins[subsequence_idx + 1] - qq_bias_begins[subsequence_idx];const uint qq_bias_spec_num = (uint)native_sqrt((float)qq_bias_num);@@ -434,14 +492,24 @@ KERNEL(pa_sdpa_opt)(const uint token_idx = swa_start_token + partition_idx * SEQ_LEN_PARTITION_SIZE + block_num * SUBGROUPS_PER_WG * SUBGROUP_SIZE + sgid * SUBGROUP_SIZE + sglid;#ifdef HAS_ALIBI+#if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+ const int alibi_val = (1 - (int)causal_len) + token_idx;+#elseconst int alibi_val = (1 - seq_len) + token_idx;+#endifunroll_for (uint q_idx = 0; q_idx < HEADS_PER_WI; q_idx++) {GET_VECTOR_ELEMENT(qk_acc, q_idx) += alibi_slopes[head_num_idx + q_idx] * alibi_val;}#endif#if SLIDING_WINDOW_SIZE != 0+ #if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+ // a type-1 token keeps its whole group inside the window+ if (token_idx >= seq_len ||+ (causal_len > SLIDING_WINDOW_SIZE && token_idx < min(causal_len - SLIDING_WINDOW_SIZE, sliding_window_begin_ext)))+ #elseif (token_idx >= seq_len || (seq_len > SLIDING_WINDOW_SIZE && token_idx < (seq_len - SLIDING_WINDOW_SIZE)))+ #endif#elseif (token_idx >= seq_len)#endif@@ -449,6 +517,7 @@ KERNEL(pa_sdpa_opt)(#if HAS_QQ_BIAS && MULTI_TOKENS_PROCESSING// token_idx < seq_len, speculative tree mask+ // (seq_len includes the group, so a key hidden by qq_bias stays hidden)if (qq_bias_num > 0 && token_idx >= past_len && token_idx < seq_len) {const uint spec_offset = token_idx - past_len;if (spec_offset < qq_bias_spec_num) {@@ -603,6 +672,7 @@ KERNEL(pa_sdpa_opt)(#if PAGED_ATTENTION_SCORES_OUTPUT#if MULTI_TOKENS_PROCESSING+ // NOTE: scores output with token_type_ids is not tested. A type-1 token saves its whole group range.const uint subsequence_idx = gws_subseq_mapping[seq_idx];const uint subsequence_start_pos = subsequence_begins[subsequence_idx];const uint subsequence_end_pos = subsequence_begins[subsequence_idx + 1];@@ -996,9 +1066,15 @@ KERNEL(pa_sdpa_opt)(REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)KERNEL(pa_sdpa_finalization_stage)(+#if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+ OPTIONAL_SHAPE_INFO_ARG+#endifconst __global INPUT3_TYPE* past_lens,#if MULTI_TOKENS_PROCESSINGconst __global INPUT6_TYPE* subsequence_begins,+#endif+#if HAS_TOKEN_TYPE_IDS && MULTI_TOKENS_PROCESSING+ const __global int* token_type_ids,#endif__global OUTPUT_TYPE* output,#if PAGED_ATTENTION_SCORES_OUTPUT@@ -1023,7 +1099,16 @@ KERNEL(pa_sdpa_finalization_stage)(#if MULTI_TOKENS_PROCESSINGconst int subsequence_idx = gws_subseq_mapping[seq_idx];const int subsequence_begin = subsequence_begins[subsequence_idx];+#if HAS_TOKEN_TYPE_IDS+ // same as the main kernel+ uint seq_len = past_lens[subsequence_idx] + 1 + (seq_idx - subsequence_begin);+ if (TT_PRESENT && token_type_ids[seq_idx] == 1) {+ const int subsequence_end = subsequence_begins[subsequence_idx + 1];+ seq_len = past_lens[subsequence_idx] + (FUNC_CALL(pa_bidir_group_end)(token_type_ids, seq_idx, subsequence_end) - subsequence_begin);+ }+#elseconst uint seq_len = past_lens[subsequence_idx] + 1 + (seq_idx - subsequence_begin);+#endif#elseconst uint seq_len = past_lens[seq_idx] + 1;#endif@@ -1331,3 +1416,68 @@ KERNEL(pa_sdpa_scores_calculation)(#undef MAX_PARTITIONS_NUM#endif++#ifdef TT_BOUNDS_STAGE+/* Per-token bidirectional group bounds from token_type_ids, consumed by sdpa_micro (USE_TT_BOUNDS).+ One work-group of TT_BOUNDS_WG work-items per subsequence. For token u (index among the subsequence's new tokens):+ bounds[2 * (subsequence_begin + u)] = first index of its type-1 run,+ bounds[2 * (subsequence_begin + u) + 1] = last index of its type-1 run (inclusive).+ Text tokens, and every token when token_type_ids is empty, get the empty range (1, 0). */+#define TT_BOUNDS_WG 256+__attribute__((reqd_work_group_size(TT_BOUNDS_WG, 1, 1)))+KERNEL(pa_tt_bounds)(+ const __global int* subsequence_begins,+ const __global int* token_type_ids,+ __global int* bounds,+ int num_seqs,+ int tt_count) {+ const int s = get_group_id(0);+ if (s >= num_seqs) {+ return;+ }+ const int lid = get_local_id(0);+ const int b = subsequence_begins[s];+ const int n = subsequence_begins[s + 1] - b;++ /* run begin = running max of run-start indices */+ int carry = -1;+ for (int c0 = 0; c0 < n; c0 += TT_BOUNDS_WG) {+ const int u = c0 + lid;+ int tt = 0;+ int start = -1;+ if (u < n && tt_count > 0) {+ tt = token_type_ids[b + u];+ if (tt == 1 && (u == 0 || token_type_ids[b + u - 1] != 1)) {+ start = u;+ }+ }+ const int pm = max(work_group_scan_inclusive_max(start), carry);+ carry = max(carry, work_group_reduce_max(start));+ if (u < n) {+ bounds[2 * (b + u)] = (tt == 1) ? pm : 1;+ }+ }++ /* run end = running min of run-end indices, scanning the chunks from the back (lane order reversed) */+ const int big = 0x7fffffff;+ int carry_end = big;+ const int last_chunk = ((n + TT_BOUNDS_WG - 1) / TT_BOUNDS_WG - 1) * TT_BOUNDS_WG;+ for (int c0 = last_chunk; c0 >= 0; c0 -= TT_BOUNDS_WG) {+ const int u = c0 + (TT_BOUNDS_WG - 1 - lid);+ int tt = 0;+ int end = big;+ if (u < n && tt_count > 0) {+ tt = token_type_ids[b + u];+ if (tt == 1 && (u == n - 1 || token_type_ids[b + u + 1] != 1)) {+ end = u;+ }+ }+ const int sm = min(work_group_scan_inclusive_min(end), carry_end);+ carry_end = min(carry_end, work_group_reduce_min(end));+ if (u < n) {+ bounds[2 * (b + u) + 1] = (tt == 1) ? sm : 0;+ }+ }+}+#undef TT_BOUNDS_WG+#endifdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cppindex 573c47f781b..f278ccf9b56 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp@@ -614,6 +614,9 @@ public:jit.make("HEADS_PER_WI", 1);const auto desc = params.typed_desc<paged_attention>();+ if (desc->has_token_type_ids) {+ jit.make("HAS_TOKEN_TYPE_IDS", 1);+ }const auto has_alibi = params.get_input_layout(PagedAttentionInputIdx::ALIBI).count() > 0;const auto has_qq_bias = desc->has_qq_bias;const auto has_scale_input = !desc->scale_val.has_value();@@ -648,6 +651,11 @@ public:jit.make("QQ_BIAS_BEGINS_DATA_T", to_ocl_type(qq_begins_layout.data_type));}jit.add(make_layout_jit_constants("OUTPUT", params.output_layouts[0], out_offsets_map.at(0)));+ if (desc->has_token_type_ids) {+ // the kernel checks the runtime size: an empty token_type_ids input disables the bidirectional masking+ const size_t tensor_id = PagedAttentionInputIdx::TOKEN_TYPE_IDS;+ jit.add(make_layout_jit_constants("TOKEN_TYPE_IDS", params.input_layouts[tensor_id], in_offsets_map.at(tensor_id)));+ }return jit;}@@ -689,6 +697,9 @@ public:args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS}); // qq_biasargs.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS_BEGINS}); // qq_bias_begins}+ if (desc->has_token_type_ids) {+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::TOKEN_TYPE_IDS}); // token_type_ids+ }args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});add_intermediate_inputs(args, has_scores_output, true, desc->has_score_aggregation);return args;@@ -722,6 +733,10 @@ public:jit.make("SDPA_STAGE_1", 1);jit.make("MULTI_TOKENS_PROCESSING", 1);jit.make("HEADS_PER_WI", 1);+ const bool has_token_type_ids = params.typed_desc<paged_attention>()->has_token_type_ids;+ if (has_token_type_ids) {+ jit.make("HAS_TOKEN_TYPE_IDS", 1);+ }const auto& in_offsets_map = params.in_port_to_shape_info_offset;const auto& out_offsets_map = params.out_port_to_shape_info_offset;@@ -729,6 +744,10 @@ public:jit.add(make_layout_jit_constants("INPUT3", params.input_layouts[5], in_offsets_map.at(5)));jit.add(make_layout_jit_constants("INPUT6", params.input_layouts[6], in_offsets_map.at(6)));jit.add(make_layout_jit_constants("OUTPUT", params.output_layouts[0], out_offsets_map.at(0)));+ if (has_token_type_ids) {+ const size_t tensor_id = PagedAttentionInputIdx::TOKEN_TYPE_IDS;+ jit.add(make_layout_jit_constants("TOKEN_TYPE_IDS", params.input_layouts[tensor_id], in_offsets_map.at(tensor_id)));+ }return jit;}@@ -737,8 +756,14 @@ public:Arguments args;const auto desc = params.typed_desc<paged_attention>();+ if (params.is_dynamic() && desc->has_token_type_ids) {+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0}); // to read the runtime size of token_type_ids+ }args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past_lensargs.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence_begins+ if (desc->has_token_type_ids) {+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::TOKEN_TYPE_IDS}); // token_type_ids+ }args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});const auto has_scores_output = desc->has_scores_output();@@ -772,6 +797,50 @@ public:}};+// Precomputes, for every token, the first/last index of its bidirectional (token_type_ids == 1) run,+// so that sdpa_micro (USE_TT_BOUNDS) compares indices instead of scanning token_type_ids between q and k.+class PagedAttentionGeneratorTTBounds : public PagedAttentionGeneratorBase {+public:+ PagedAttentionGeneratorTTBounds() : PagedAttentionGeneratorBase("_tt_bounds") {}+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {+ auto jit = PagedAttentionGeneratorBase::get_jit_constants(params);+ jit.make("TT_BOUNDS_STAGE", 1);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS});+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::TOKEN_TYPE_IDS});+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 4}); // tt_bounds+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // num_seqs+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // token_type_ids element count (0 = empty input)+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {+ assert(!params.is_dynamic());+ auto& wgs = kd.params.workGroups;+ auto& scalars = kd.params.scalars;+ scalars.resize(2);++ constexpr size_t wg_size = 256; // TT_BOUNDS_WG+ const size_t num_seqs = params.input_layouts[PagedAttentionInputIdx::SUBSEQUENCE_BEGINS].get_partial_shape()[0].get_length() - 1;+ const auto& tt_layout = params.input_layouts[PagedAttentionInputIdx::TOKEN_TYPE_IDS];+ const size_t tt_count = tt_layout.is_static() ? ov::shape_size(tt_layout.get_shape()) : 0;++ wgs.global = {num_seqs * wg_size, 1, 1};+ wgs.local = {wg_size, 1, 1};++ scalars[0].t = ScalarDescriptor::Types::UINT32;+ scalars[0].v.u32 = static_cast<uint32_t>(num_seqs);+ scalars[1].t = ScalarDescriptor::Types::UINT32;+ scalars[1].v.u32 = static_cast<uint32_t>(tt_count);+ }};+ }+};+class PagedAttentionGeneratorScoresCalculation : public PagedAttentionGeneratorBase {public:PagedAttentionGeneratorScoresCalculation() : PagedAttentionGeneratorBase("_scores_calculation") {}@@ -1341,6 +1410,7 @@ public:#ifdef ENABLE_ONEDNN_FOR_GPUStage::Ptr pa_sdpa_micro = make_stage<SDPAMicroGenerator>(true);Stage::Ptr pa_sdpa_micro_mixed = make_stage<SDPAMicroGenerator>(false);+ Stage::Ptr pa_tt_bounds = make_stage<PagedAttentionGeneratorTTBounds>();#endifPagedAttentionOptImpl() : SDPAImplBase(PagedAttentionOpt::get_type_info_static()) {}@@ -1355,6 +1425,9 @@ public:if (use_micro_sdpa) {add_stage(pa_sdpa_micro, params);add_stage(pa_sdpa_micro_mixed, params);+ if (pa_micro_uses_tt_bounds(*desc)) {+ add_stage(pa_tt_bounds, params);+ }}#endif@@ -1388,9 +1461,7 @@ public:return false;}- // MIXED may use micro SDPA regardless of token_type_ids: bidirectional masking is implemented- // only in the PREFILL kernels, and in MIXED neither micro SDPA nor paged_attention_opt.cl consumes token_type_ids.- // TODO: implement bidirectional attention for MIXED with token_type_ids+ // token_type_ids does not change the choice: micro and OCL kernels both support it.bool can_use_micro_sdpa_for(const kernel_impl_params& params, const PagedAttentionStage& stage) const {const auto can_use_micro_sdpa = supports_micro_sdpa(params) && valid_micro_stage(stage);GPU_DEBUG_TRACE_DETAIL << "can_use_micro_sdpa_for: stage = " << static_cast<size_t>(stage)@@ -1572,6 +1643,9 @@ public:if (rt_params->stage == PagedAttentionStage::PREFILL) {#ifdef ENABLE_ONEDNN_FOR_GPUif (rt_params->use_micro_sdpa) {+ if (pa_micro_uses_tt_bounds(*desc)) {+ res_event = {execute_stage(res_event, instance, pa_tt_bounds)};+ }res_event = {execute_stage(res_event, instance, pa_sdpa_micro)};} else#endif@@ -1586,6 +1660,9 @@ public:} else {#ifdef ENABLE_ONEDNN_FOR_GPUif (multi_tokens_mode && rt_params->use_micro_sdpa) {+ if (pa_micro_uses_tt_bounds(*desc)) {+ res_event = {execute_stage(res_event, instance, pa_tt_bounds)};+ }res_event = {execute_stage(res_event, instance, pa_sdpa_micro_mixed)};} else#endif@@ -1797,6 +1874,11 @@ public:const auto target_seq_len = std::max(paged_attention_aligned_seq_len, static_cast<int64_t>(1));const auto indexes_buf_size = ceil_div(target_seq_len, wg_tile_q) * 2;internal_buffers.emplace_back(indexes_buf_size * 4, indexes_dt, lockable, not_shareable);+ if (pa_micro_uses_tt_bounds(*desc)) {+ // 4: per-token [first, last] index of the token_type_ids == 1 run, filled by pa_tt_bounds.+ // Not lockable: only kernels access it, so it stays in device memory.+ internal_buffers.emplace_back(total_tokens * 2 * sizeof(int32_t), indexes_dt);+ }}#endifdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hppindex 0211778b666..70c159ae440 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp@@ -17,6 +17,13 @@ using namespace cldnn; // TODO: Remove once namespaces are alignednamespace ov::intel_gpu::ocl {+// sdpa_micro reads the per-token token_type_ids group bounds precomputed by the pa_tt_bounds stage+// (internal buffer 4, right after the micro-kernel buffer 3). Not used with scores output or adaptive RKV,+// which add internal buffers before that index.+inline bool pa_micro_uses_tt_bounds(const paged_attention& desc) {+ return desc.has_token_type_ids && !desc.has_scores_output() && !desc.has_adaptive_rkv;+}+enum class PagedAttentionStage : uint8_t { GENERATE = 0, PREFILL = 1, MIXED = 2, UNKNOWN = 3 };struct PagedAttentionRuntimeParams : public ImplRuntimeParams {diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cppindex e84cf07ad21..baf657bb037 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp@@ -1339,8 +1339,14 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& parjit.make("WITH_ATTN_MASK", 0);jit.make("PAGED_ATTENTION_BLOCK_SIZE", config.paged_attention_block_size);const auto desc = params.typed_desc<paged_attention>();- if (desc->has_token_type_ids && m_is_prefill) {+ if (desc->has_token_type_ids) {jit.make("HAS_TOKEN_TYPE_IDS", 1);+ // the kernel checks the runtime size: an empty token_type_ids input disables the bidirectional masking+ const size_t tensor_id = PagedAttentionInputIdx::TOKEN_TYPE_IDS;+ jit.add(make_layout_jit_constants("TOKEN_TYPE_IDS", params.input_layouts[tensor_id], params.in_port_to_shape_info_offset.at(tensor_id)));+ if (pa_micro_uses_tt_bounds(*desc)) {+ jit.make("USE_TT_BOUNDS", 1); // group bounds precomputed by the pa_tt_bounds stage+ }}}@@ -1683,11 +1689,14 @@ Arguments SDPAMicroGenerator::get_arguments_desc(const kernel_impl_params& param{ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS_BEGINS}); // qq_bias_begins // qq_bias_num}- if (desc->has_token_type_ids && m_is_prefill) {+ if (desc->has_token_type_ids) {args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::TOKEN_TYPE_IDS}); // token_type_ids}args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 3}); // blocked_indexes_start_and_gws_mapping+ if (pa_micro_uses_tt_bounds(*desc)) {+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 4}); // tt_bounds+ }} else {args.push_back({ArgumentDescriptor::Types::INPUT, ScaledDotProductAttentionInputIdx::KEY}); // Kargs.push_back({ArgumentDescriptor::Types::INPUT, ScaledDotProductAttentionInputIdx::QUERY}); // Qdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.clindex f7fe3140fc8..8b1f964856c 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl@@ -182,6 +182,12 @@ DECLARE_2D_TILE_RSELECT(a_scale_tile_type, SUBGROUP_SIZE, ugemm_vs_sg_tile_n, 1,#define binary_add(x, y) ((x) + (y))__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE)))+#if IS_PREFILL+#define TT_MASK_PRESENT 1+#else+#define TT_MASK_PRESENT (TOKEN_TYPE_IDS_BATCH_NUM > 0)+#endif+KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGconst global KEY_DATA_T *K,const global QRY_DATA_T *Q,@@ -217,6 +223,9 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#endif#if IS_PAGED_ATTENTIONconst __global int* blocked_indexes_start_and_gws_mapping+ #if USE_TT_BOUNDS+ , const __global int* tt_bounds+ #endif#elseint d, int k, int q#endif@@ -305,23 +314,43 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#elsecausal_k = min(k, (int)wg_j0 + ugemm_kq_wg_tile_n);#endif- #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION && IS_PREFILL+ #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION+ /* token_type_ids has the new tokens only. t is the index among them: K position = past_len + t. */+ #define TT_NEW(t) token_type_ids[subsequence_begin + (t)]+ /* token types by K position: valid for K positions in [past_len, k) */+ const __global int *tt_kpos = token_type_ids + subsequence_begin - past_len;+ /* An empty token_type_ids input (runtime size 0) disables the bidirectional masking. */+ #if IS_PREFILL+ const bool tt_present = true; /* PREFILL: unchanged */+ #else+ const bool tt_present = TOKEN_TYPE_IDS_BATCH_NUM > 0;+ #endif/* Extend causal_k to cover the full bidirectional group that overlapsthe current WG's query range. Without this, future K positions inthe same image-token group would be skipped entirely.- Only lane 0 performs the scan; result is broadcast to all WIs. */+ With USE_TT_BOUNDS the group bounds come from pa_tt_bounds; otherwise lane 0 scans and broadcasts the result. */{- int wg_q_end = min((int)wg_j0 + ugemm_kq_wg_tile_n, k) - 1;+ /* last query of this tile (queries are only the q new tokens) */+ const int wg_q_end = min((int)wg_j0 + ugemm_kq_wg_tile_n, (int)q) - 1;int bidir_causal_k = causal_k;- if (wg_q_end >= 0 && wg_q_end < k && token_type_ids[wg_q_end] == 1) {+ #if USE_TT_BOUNDS+ /* group bounds precomputed by pa_tt_bounds: (1, 0) = not in a group */+ if (wg_q_end >= 0) {+ const int grp_end = tt_bounds[2 * (subsequence_begin + wg_q_end) + 1];+ if (grp_end >= tt_bounds[2 * (subsequence_begin + wg_q_end)])+ bidir_causal_k = max(causal_k, past_len + grp_end + 1);+ }+ #else+ if (tt_present && wg_q_end >= 0 && TT_NEW(wg_q_end) == 1) {int bidir_end = wg_q_end + 1;if (get_sub_group_local_id() == 0) {- while (bidir_end < k && token_type_ids[bidir_end] == 1)+ while (bidir_end < (int)q && TT_NEW(bidir_end) == 1)bidir_end++;}bidir_end = sub_group_broadcast(bidir_end, 0);- bidir_causal_k = max(causal_k, bidir_end);+ bidir_causal_k = max(causal_k, past_len + bidir_end);}+ #endifcausal_k = bidir_causal_k;}#endif@@ -343,20 +372,29 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#elsewindow_k_begin = MAX(0, (int)wg_j0 - SLIDING_WINDOW_SIZE + 1);#endif- #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION && IS_PREFILL+ #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION/* Extend sliding window start to include the full bidirectional groupthat overlaps the window boundary. Without this, K positions in thesame image-token group but before window_k_begin would be skipped.- Only lane 0 performs the scan; result is broadcast to all WIs. */- if (window_k_begin > 0 && token_type_ids[window_k_begin] == 1) {- int wb = window_k_begin;+ Groups exist only in the new tokens (K >= past_len).+ With USE_TT_BOUNDS the group bounds come from pa_tt_bounds; otherwise lane 0 scans and broadcasts the result. */+ #if USE_TT_BOUNDS+ if (window_k_begin > past_len && window_k_begin - past_len < (int)q) {+ const int loc = window_k_begin - past_len;+ if (tt_bounds[2 * (subsequence_begin + loc) + 1] >= tt_bounds[2 * (subsequence_begin + loc)])+ window_k_begin = past_len + tt_bounds[2 * (subsequence_begin + loc)];+ }+ #else+ if (tt_present && window_k_begin > past_len && TT_NEW(window_k_begin - past_len) == 1) {+ int wb = window_k_begin - past_len;if (get_sub_group_local_id() == 0) {- while (wb > 0 && token_type_ids[wb - 1] == 1)+ while (wb > 0 && TT_NEW(wb - 1) == 1)wb--;}- window_k_begin = sub_group_broadcast(wb, 0);+ window_k_begin = past_len + sub_group_broadcast(wb, 0);}#endif+ #endifwindow_k0_begin = (window_k_begin / ugemm_kq_wg_tile_m) * ugemm_kq_wg_tile_m;#endif@@ -1154,40 +1192,71 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGcausal_q_begin += k - q;#endif- #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION && IS_PREFILL- /* Apply causal mask with bidirectional for image tokens */+ #if HAS_TOKEN_TYPE_IDS && IS_PAGED_ATTENTION+ /* Apply causal mask with bidirectional for image tokens.+ offset_k / offset_q are K positions; token_type_ids is indexed by position - past_len. */{- const int k_base = k0 + sg_i0_kq;- for (int j = 0; j < (ugemm_kq_c_type_block1 * ugemm_kq_c_type_nblock1); j++) {- const int offset_k = k_base + j;+ const int tt_k_begin = k0 + sg_i0_kq;+ const int tt_k_end = tt_k_begin + ugemm_kq_c_type_block1 * ugemm_kq_c_type_nblock1;+ #if SLIDING_WINDOW_SIZE+ const int tt_q_end = causal_q_begin + ugemm_kq_c_type_block0 * ugemm_kq_c_type_nblock0 - 1;+ /* Tile is fully causal and inside the window: nothing to mask (same check as the text-only path). */+ const bool tt_block_fully_valid = (tt_k_begin > tt_q_end - SLIDING_WINDOW_SIZE) && (tt_k_end <= causal_q_begin);+ #else+ const bool tt_block_fully_valid = !(tt_k_end > causal_q_begin);+ #endif+ if (!tt_block_fully_valid) {+ #if USE_TT_BOUNDSfor (int i0 = 0; i0 < (ugemm_kq_c_type_block0 * ugemm_kq_c_type_nblock0); i0 += SUBGROUP_SIZE) {- int i = i0 + get_sub_group_local_id();- const int offset_q = col_offset + i;- if (greater_than(offset_k, offset_q)) {- bool is_bidirectional = false;- if (offset_k < q && offset_q < q &&- token_type_ids[offset_k] == 1 &&- token_type_ids[offset_q] == 1) {- /* Verify no 0 exists between q and k (same 1-group).- Scan from the smaller to the larger index so this- works both for future tokens (k>q) and for past- tokens outside the sliding window (k<q). */- is_bidirectional = true;- const int scan_begin = min(offset_q, offset_k) + 1;- const int scan_end = max(offset_q, offset_k);- for (int p = scan_begin; p < scan_end; p++) {- if (token_type_ids[p] != 1) {- is_bidirectional = false;- break;- }- }- }- if (!is_bidirectional) {+ const int offset_q = col_offset + i0 + get_sub_group_local_id();+ /* group of this query row, precomputed by pa_tt_bounds (empty = (1, 0) for text tokens) */+ int g_lo = 1, g_hi = 0;+ if (offset_q >= past_len && offset_q < k) {+ const int bidx = 2 * (subsequence_begin + (offset_q - past_len));+ g_lo = past_len + tt_bounds[bidx];+ g_hi = past_len + tt_bounds[bidx + 1];+ }+ for (int j = 0; j < (ugemm_kq_c_type_block1 * ugemm_kq_c_type_nblock1); j++) {+ const int offset_k = tt_k_begin + j;+ if (greater_than(offset_k, offset_q) && !(offset_k >= g_lo && offset_k <= g_hi)) {tile_access(S_tile, i0, j, SUBGROUP_SIZE, ugemm_kq_c_type_block0,ugemm_kq_c_type_block1, ugemm_kq_c_type_nblock0) = -FLT_MAX;}}}+ #else+ for (int j = 0; j < (ugemm_kq_c_type_block1 * ugemm_kq_c_type_nblock1); j++) {+ const int offset_k = tt_k_begin + j;+ for (int i0 = 0; i0 < (ugemm_kq_c_type_block0 * ugemm_kq_c_type_nblock0); i0 += SUBGROUP_SIZE) {+ int i = i0 + get_sub_group_local_id();+ const int offset_q = col_offset + i;+ if (greater_than(offset_k, offset_q)) {+ bool is_bidirectional = false;+ if (TT_MASK_PRESENT && offset_k >= past_len && offset_k < k && offset_q >= past_len && offset_q < k &&+ tt_kpos[offset_k] == 1 &&+ tt_kpos[offset_q] == 1) {+ /* Verify no 0 exists between q and k (same 1-group).+ Scan from the smaller to the larger index so this+ works both for future tokens (k>q) and for past+ tokens outside the sliding window (k<q). */+ is_bidirectional = true;+ const int scan_begin = min(offset_q, offset_k) + 1;+ const int scan_end = max(offset_q, offset_k);+ for (int p = scan_begin; p < scan_end; p++) {+ if (tt_kpos[p] != 1) {+ is_bidirectional = false;+ break;+ }+ }+ }+ if (!is_bidirectional) {+ tile_access(S_tile, i0, j, SUBGROUP_SIZE, ugemm_kq_c_type_block0,+ ugemm_kq_c_type_block1, ugemm_kq_c_type_nblock0) = -FLT_MAX;+ }+ }+ }+ }+ #endif}}#elsediff --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.clindex 7321275b813..530e7d5092d 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@@ -1465,7 +1465,9 @@ 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,+ // token_type_ids covers all subsequences, but the indexes below are per subsequence: move to this subsequence.+ const __global int* subsequence_token_type_ids = token_type_ids + subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]];+ const SEQ_RANGE bi_dir_range = FUNC_CALL(calc_bi_dir_seq_range)(subsequence_token_type_ids,reduce_buffer,SOURCE_SEQ_LEN,default_this_work_item_seq_range,diff --git a/src/plugins/intel_gpu/tests/unit/dynamic_execution/update_shape_test.cpp b/src/plugins/intel_gpu/tests/unit/dynamic_execution/update_shape_test.cppindex 8e4d9d0209a..297c1cd41e9 100644--- a/src/plugins/intel_gpu/tests/unit/dynamic_execution/update_shape_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/dynamic_execution/update_shape_test.cpp@@ -573,8 +573,9 @@ TEST(update_shape_test, paged_attention_mixed_stage_token_type_ids_buffer_layout// Allocation-time and execution-time micro/non-micro decisions must agree; a mismatch shows up// as the wrong buffer count. token_type_ids no longer forces the non-micro path in MIXED.+ // The micro path has one extra buffer for the token_type_ids group bounds.const bool micro_layout = engine.get_device_info().supports_immad;- ASSERT_EQ(intermediate_mems.size(), micro_layout ? 4u : 7u);+ ASSERT_EQ(intermediate_mems.size(), micro_layout ? 5u : 7u);}TEST(update_shape_test, paged_attention_mixed_stage_h256_micro_qtile64_buffers) {tests::random_generator rg(GET_SUITE_NAME);@@ -846,10 +847,9 @@ TEST(update_shape_test, paged_attention_mixed_stage_h256_micro_qtile64_buffers)<< "size matches the generic h256 PA config with q tile 32 (aligned_seq_len " << aligned_qtile32<< "): " << dump_sizes();EXPECT_EQ(intermediate_mems[0]->size(), ((aligned_qtile64 + 15) / 16) * 4) << dump_sizes();- if (intermediate_mems.size() > 4) {- ASSERT_EQ(intermediate_mems[4]->size(), 16u) << dump_sizes();- ASSERT_EQ(intermediate_mems[5]->size(), 16u) << dump_sizes();- }+ // [4]: token_type_ids group bounds for the micro kernel, two int32 values per token+ ASSERT_EQ(intermediate_mems.size(), 5u) << dump_sizes();+ ASSERT_EQ(intermediate_mems[4]->size(), 200u * 2 * sizeof(int32_t)) << dump_sizes();}} // update_shape_testdiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.h b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.hindex 148d7eafa5a..1ae680b341d 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.h+++ b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.h@@ -131,7 +131,8 @@ 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+ // optional token_type_ids: one value per scheduled token (all subsequences, no past).+ // When empty, a single {0} is used (only if has_token_type_ids is false).std::vector<int> token_type_ids;cldnn::engine& test_engine;cldnn::stream& test_stream;@@ -1916,9 +1917,18 @@ public:pam.qq_bias_begins = p.qq_bias_config.qq_bias_begins;}+ // token_type_ids: one value per scheduled token (all subsequences, no past).+ size_t total_scheduled_tokens = 0;+ for (const auto& desc : pam.subsequence_descs) {+ total_scheduled_tokens += static_cast<size_t>(desc.num_tokens);+ }+if (p.token_type_ids.has_value()) {pam.token_type_ids = p.token_type_ids.value();- EXPECT_EQ(pam.token_type_ids.size(), static_cast<size_t>(pam.subsequence_descs.back().num_tokens + pam.subsequence_descs.back().past_len));+ EXPECT_EQ(pam.token_type_ids.size(), total_scheduled_tokens);+ } else if (p.has_sink_input) {+ // Sink tests force has_token_type_ids on, so pass valid all-zero ids (text only).+ pam.token_type_ids.assign(total_scheduled_tokens, 0);}if (p.has_sink_input && p.sink_values.has_value()) {diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_token_type_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_token_type_gpu_test.cppindex 268e16441f5..d81fc28dfd5 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_token_type_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_token_type_gpu_test.cpp@@ -7,6 +7,12 @@struct paged_attention_token_type_test_params : public paged_attention_test_params {test::TestData token_type_test_data;+ // Multi-subsequence tests: golden cases that make up the subsequences.+ std::vector<std::string> case_names;+ // MIXED multi-subsequence test: past_len of each subsequence.+ std::vector<int> case_past;+ // Head-size test: how many times the golden head (32) is repeated.+ int head_repeat = 1;};class paged_attention_token_type_test : public PagedAttentionTest<paged_attention_token_type_test_params> {@@ -152,9 +158,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_micro_sdpa_prefill,::testing::ValuesIn(make_micro_sdpa_prefill_test_params()),get_micro_sdpa_prefill_test_name);-// Micro SDPA in the MIXED stage while token_type_ids is present. MIXED used to fall back to-// paged_attention_opt__multi_tokens, which carries no token_type_ids handling of its own, so the-// fallback only ever cost performance.+// Micro SDPA stays selected in the MIXED stage when token_type_ids is present.//// The PREFILL golden data is replayed as a chunked prefill://@@ -163,9 +167,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_micro_sdpa_prefill,// q | - | passed as input |// golden | - | compared |//-// past_len is picked so the query chunk holds text tokens only. A bidirectional pair needs both the-// query and the key to be image tokens, so a text-only chunk is masked purely causally - which is-// what both MIXED kernels produce, neither of them implementing token_type_ids.+// past_len is picked so the chunk has text tokens only, so the mask is plain causal.+// Image groups are tested by the mixed_image test.class paged_attention_token_type_micro_sdpa_mixed_test : public paged_attention_token_type_test {public:void apply_mixed_test_data(PagedAttentionManager& pam, const paged_attention_token_type_test_params& p, const test::TestData& data) {@@ -192,7 +195,8 @@ public:const auto query_data = to_float16(data.qData);pam.query_data = {std::vector<ov::float16>(query_data.begin() + past_len * hidden_dim, query_data.end())};- pam.token_type_ids.assign(data.tokenTypes.begin(), data.tokenTypes.end());+ // token_type_ids: scheduled tokens only (no past).+ pam.token_type_ids.assign(data.tokenTypes.begin() + past_len, data.tokenTypes.end());}};@@ -254,6 +258,7 @@ static std::vector<paged_attention_token_type_test_params> make_micro_sdpa_mixedauto p = make_token_type_test_param(data, ENABLE_FA_V2);p.subsequences = {{static_cast<int>(data.tokenTypes.size()) - past_len, past_len}};+ p.token_type_ids = std::vector<int>(data.tokenTypes.begin() + past_len, data.tokenTypes.end());params.push_back(p);}return params;@@ -269,4 +274,442 @@ INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_micro_sdpa_mixed,paged_attention_token_type_micro_sdpa_mixed_test,::testing::ValuesIn(make_micro_sdpa_mixed_test_params()),get_micro_sdpa_mixed_test_name);++// MIXED with image tokens in the scheduled chunk.+//+// The PREFILL golden is valid for the chunk only if the split is not inside an image group,+// so the splits are on group boundaries and the chunk has at least one image token.+static std::vector<paged_attention_token_type_test_params> make_micro_sdpa_mixed_image_test_params() {+ std::vector<paged_attention_token_type_test_params> params;+ // - middle_segment, two_small_image_groups: a few image groups+ // - casual_indirectly: single image tokens between text tokens (no group)+ // - long_sequence: many groups, chunk longer than one tile+ // - long_chain_of_1s: one long group at the start of the chunk+ // - long_input_with_mixed_token_types (SW5): sliding window with many groups+ struct Case { const char* name; int past; };+ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ for (const Case& c : {Case{"middle_segment", 3},+ Case{"casual_indirectly", 8},+ Case{"long_sequence", 85},+ Case{"long_chain_of_1s", 1},+ Case{"two_small_image_groups", 12},+ Case{"long_input_with_mixed_token_types", 99}}) {+ const auto it = std::find_if(all.begin(), all.end(), [&](const test::TestData& d) { return d.name == c.name; });+ OPENVINO_ASSERT(it != all.end(), "token type test data not found: ", c.name);+ const auto& data = *it;+ auto p = make_token_type_test_param(data, ENABLE_FA_V2);+ p.subsequences = {{static_cast<int>(data.tokenTypes.size()) - c.past, c.past}};+ p.token_type_ids = std::vector<int>(data.tokenTypes.begin() + c.past, data.tokenTypes.end());+ params.push_back(p);+ }+ return params;+}++static std::string get_micro_sdpa_mixed_image_test_name(const testing::TestParamInfo<paged_attention_token_type_test_params>& obj) {+ const auto& p = obj.param;+ return p.token_type_test_data.name + "_SW" + std::to_string(p.sliding_window_size) + "_Past" + std::to_string(p.subsequences[0].past_len) ++ "_MicroSDPA_MixedImage";+}++class paged_attention_token_type_micro_sdpa_mixed_image_test : public paged_attention_token_type_micro_sdpa_mixed_test {};++TEST_P(paged_attention_token_type_micro_sdpa_mixed_image_test, mixed_stage_with_image_in_chunk) {+ // Same as mixed_stage, but the chunk has image tokens.+ const auto& device_info = tests::get_test_engine().get_device_info();+ if (!device_info.supports_immad || device_info.arch < cldnn::gpu_arch::xe_hpg)+ GTEST_SKIP() << "Micro SDPA requires DPAS/XMX support";++ auto p = GetParam();++ ASSERT_TRUE(this->pam.has_value());+ auto& pam = *this->pam;++ apply_mixed_test_data(pam, p, p.token_type_test_data);+ auto result = run_gpu_inference(pam, p);++ auto pa_inst = result.network->get_primitive("paged_attention");+ ASSERT_NE(pa_inst, nullptr);+ const auto kernel_entries = pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries();+ EXPECT_NE(kernel_entries.find("sdpa_micro"), std::string::npos) << "Expected micro SDPA kernel for MIXED, got: " << kernel_entries;++ const size_t hidden_dim = static_cast<size_t>(p.num_heads) * static_cast<size_t>(p.v_head_size);+ const size_t cached_values = static_cast<size_t>(p.subsequences[0].past_len) * hidden_dim;+ const auto& golden_output = p.token_type_test_data.expectedOutput;+ const std::vector<float> expected_output(golden_output.begin() + cached_values, golden_output.end());++ cldnn::memory::ptr output_data_mem = result.outputs.at("output_data").get_memory();+ compare_token_type_output(output_data_mem, expected_output);+}++INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_micro_sdpa_mixed_image,+ paged_attention_token_type_micro_sdpa_mixed_image_test,+ ::testing::ValuesIn(make_micro_sdpa_mixed_image_test_params()),+ get_micro_sdpa_mixed_image_test_name);+#endif++// PREFILL with two subsequences.+//+// token_type_ids covers all subsequences, so subsequence B starts at subsequence_begins[B].+// A kernel that uses the index inside B reads A's values and the output no longer matches the golden.+class paged_attention_token_type_multi_subsequence_test : public paged_attention_token_type_test {+public:+ static const test::TestData& find_case(const std::vector<test::TestData>& all, const std::string& name) {+ for (const auto& d : all) {+ if (d.name == name)+ return d;+ }+ OPENVINO_THROW("token type test data not found: ", name);+ }+};++TEST_P(paged_attention_token_type_multi_subsequence_test, prefill_two_subsequences) {+ auto p = GetParam();++ ASSERT_TRUE(this->pam.has_value());+ auto& pam = *this->pam;++ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ ASSERT_EQ(p.case_names.size(), p.subsequences.size());++ pam.query_data.clear();+ pam.key_data.clear();+ pam.value_data.clear();+ pam.token_type_ids.clear();+ std::vector<float> expected;+ for (const auto& name : p.case_names) {+ const auto& d = find_case(all, name);+ ASSERT_EQ(d.slidingWindowSize, p.sliding_window_size);+ pam.query_data.push_back(to_float16(d.qData));+ pam.key_data.push_back(to_float16(d.kData));+ pam.value_data.push_back(to_float16(d.vData));+ pam.token_type_ids.insert(pam.token_type_ids.end(), d.tokenTypes.begin(), d.tokenTypes.end());+ expected.insert(expected.end(), d.expectedOutput.begin(), d.expectedOutput.end());+ }++ auto result = run_gpu_inference(pam, p);+ cldnn::memory::ptr output_data_mem = result.outputs.at("output_data").get_memory();++ compare_token_type_output(output_data_mem, expected);+}++static paged_attention_token_type_test_params make_multi_subsequence_param(const std::vector<std::string>& names, bool disable_fa_v2) {+ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ auto p = make_token_type_test_param(paged_attention_token_type_multi_subsequence_test::find_case(all, names.front()), disable_fa_v2);+ p.case_names = names;+ p.subsequences.clear();+ std::vector<int> ids;+ for (const auto& name : names) {+ const auto& d = paged_attention_token_type_multi_subsequence_test::find_case(all, name);+ p.subsequences.push_back({static_cast<int>(d.tokenTypes.size()), 0});+ ids.insert(ids.end(), d.tokenTypes.begin(), d.tokenTypes.end());+ }+ p.token_type_ids = ids;+ return p;+}++static std::vector<paged_attention_token_type_test_params> make_multi_subsequence_test_params() {+ std::vector<paged_attention_token_type_test_params> params;+ // The image group is in the second subsequence, and in the first.+ for (const auto& names : std::vector<std::vector<std::string>>{{"plain_casual", "middle_segment"}, {"middle_segment", "plain_casual"}}) {+ params.push_back(make_multi_subsequence_param(names, ENABLE_FA_V2));+ }+ return params;+}++static std::string get_multi_subsequence_test_name(const testing::TestParamInfo<paged_attention_token_type_test_params>& obj) {+ const auto& p = obj.param;+ std::string name;+ for (const auto& n : p.case_names) {+ name += (name.empty() ? "" : "_then_") + n;+ }+ return name + "_SW" + std::to_string(p.sliding_window_size) + (p.disable_flashattn_v2 == DISABLE_FA_V2 ? "_FlashAttnV2Disabled" : "_FlashAttnV2Enabled");+}++INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_multi_subsequence,+ paged_attention_token_type_multi_subsequence_test,+ ::testing::ValuesIn(make_multi_subsequence_test_params()),+ get_multi_subsequence_test_name);++// MIXED with two subsequences, each with image groups: one has past (past_len > 0), one does not.+// Both orders are used, so the image group has a zero and a non-zero subsequence_begin.+class paged_attention_token_type_mixed_multi_subsequence_test : public paged_attention_token_type_multi_subsequence_test {};++TEST_P(paged_attention_token_type_mixed_multi_subsequence_test, mixed_stage_two_subsequences) {+ auto p = GetParam();+#ifdef ENABLE_ONEDNN_FOR_GPU+ const auto& device_info = tests::get_test_engine().get_device_info();+ const bool micro_expected = device_info.supports_immad && device_info.arch >= cldnn::gpu_arch::xe_hpg;+#else+ const bool micro_expected = false; // no micro SDPA without oneDNN#endif++ ASSERT_TRUE(this->pam.has_value());+ auto& pam = *this->pam;++ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ ASSERT_EQ(p.case_names.size(), p.subsequences.size());+ ASSERT_EQ(p.case_past.size(), p.subsequences.size());+ const size_t hidden_dim = static_cast<size_t>(p.num_heads) * static_cast<size_t>(p.k_head_size);++ pam.query_data.clear();+ pam.key_data.clear();+ pam.value_data.clear();+ pam.token_type_ids.clear();+ std::vector<float> expected;+ for (size_t i = 0; i < p.case_names.size(); i++) {+ const auto& d = find_case(all, p.case_names[i]);+ const size_t past = static_cast<size_t>(p.case_past[i]);+ ASSERT_EQ(d.slidingWindowSize, p.sliding_window_size);+ ASSERT_EQ(past + static_cast<size_t>(p.subsequences[i].num_tokens), d.tokenTypes.size());++ // Key/Value: whole sequence (past goes to the cache). Query: scheduled tokens only.+ const auto q = to_float16(d.qData);+ pam.query_data.push_back(std::vector<ov::float16>(q.begin() + past * hidden_dim, q.end()));+ pam.key_data.push_back(to_float16(d.kData));+ pam.value_data.push_back(to_float16(d.vData));+ pam.token_type_ids.insert(pam.token_type_ids.end(), d.tokenTypes.begin() + past, d.tokenTypes.end());+ expected.insert(expected.end(), d.expectedOutput.begin() + past * hidden_dim, d.expectedOutput.end());+ }++ auto result = run_gpu_inference(pam, p);++ auto pa_inst = result.network->get_primitive("paged_attention");+ ASSERT_NE(pa_inst, nullptr);+ const auto kernel_entries = pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries();+ if (micro_expected) {+ EXPECT_NE(kernel_entries.find("sdpa_micro"), std::string::npos) << "Expected micro SDPA kernel for MIXED, got: " << kernel_entries;+ }++ compare_token_type_output(result.outputs.at("output_data").get_memory(), expected);+}++static paged_attention_token_type_test_params make_mixed_multi_subsequence_param(const std::vector<std::string>& names,+ const std::vector<int>& past,+ bool disable_fa_v2) {+ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ auto p = make_token_type_test_param(paged_attention_token_type_multi_subsequence_test::find_case(all, names.front()), disable_fa_v2);+ p.case_names = names;+ p.case_past = past;+ p.subsequences.clear();+ std::vector<int> ids;+ for (size_t i = 0; i < names.size(); i++) {+ const auto& d = paged_attention_token_type_multi_subsequence_test::find_case(all, names[i]);+ p.subsequences.push_back({static_cast<int>(d.tokenTypes.size()) - past[i], past[i]});+ ids.insert(ids.end(), d.tokenTypes.begin() + past[i], d.tokenTypes.end());+ }+ p.token_type_ids = ids;+ return p;+}++static std::vector<paged_attention_token_type_test_params> make_mixed_multi_subsequence_test_params() {+ std::vector<paged_attention_token_type_test_params> params;+ // Splits are on image-group boundaries.+ struct Case { std::vector<std::string> names; std::vector<int> past; };+ const std::vector<Case> cases = {+ // SW0: chunk with past, then a fresh prompt (and the reverse order)+ {{"middle_segment", "casual_indirectly"}, {3, 0}},+ {{"casual_indirectly", "middle_segment"}, {0, 3}},+ // SW5: same with a sliding window+ {{"two_small_image_groups", "short_seq_in_middle"}, {12, 0}},+ };+ for (const auto& c : cases) {+ params.push_back(make_mixed_multi_subsequence_param(c.names, c.past, ENABLE_FA_V2));+ }+ return params;+}++static std::string get_mixed_multi_subsequence_test_name(const testing::TestParamInfo<paged_attention_token_type_test_params>& obj) {+ const auto& p = obj.param;+ std::string name;+ for (size_t i = 0; i < p.case_names.size(); i++) {+ name += (name.empty() ? "" : "_then_") + p.case_names[i] + "_Past" + std::to_string(p.case_past[i]);+ }+ return name + "_SW" + std::to_string(p.sliding_window_size);+}++INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_mixed_multi_subsequence,+ paged_attention_token_type_mixed_multi_subsequence_test,+ ::testing::ValuesIn(make_mixed_multi_subsequence_test_params()),+ get_mixed_multi_subsequence_test_name);++#ifdef ENABLE_ONEDNN_FOR_GPU+// MIXED micro SDPA with token_type_ids at head size 64/128/256.+//+// The golden head size is 32. Repeating the head n times (q' = q / sqrt(n), k' = k, v' = v) keeps the scores,+// and the output is the golden output repeated n times.+//+// This checks that the micro kernel still builds and is selected (no fallback to paged_attention_opt__multi_tokens).+class paged_attention_token_type_micro_sdpa_mixed_head_test : public paged_attention_token_type_micro_sdpa_mixed_test {};++TEST_P(paged_attention_token_type_micro_sdpa_mixed_head_test, mixed_stage_head_size) {+ const auto& device_info = tests::get_test_engine().get_device_info();+ if (!device_info.supports_immad || device_info.arch < cldnn::gpu_arch::xe_hpg)+ GTEST_SKIP() << "Micro SDPA requires DPAS/XMX support";++ auto p = GetParam();+ ASSERT_TRUE(this->pam.has_value());+ auto& pam = *this->pam;++ const auto& d = p.token_type_test_data;+ const size_t n = static_cast<size_t>(p.head_repeat);+ const size_t base_hidden = 32;+ const size_t past_len = static_cast<size_t>(p.subsequences[0].past_len);+ const size_t seq_len = d.tokenTypes.size();+ ASSERT_EQ(static_cast<size_t>(p.k_head_size), base_hidden * n);++ auto repeat = [&](const std::vector<float>& src, float mul) {+ std::vector<float> out;+ out.reserve(src.size() * n);+ for (size_t t = 0; t < seq_len; t++) {+ for (size_t r = 0; r < n; r++) {+ for (size_t c = 0; c < base_hidden; c++) {+ out.push_back(src[t * base_hidden + c] * mul);+ }+ }+ }+ return out;+ };++ const auto q = to_float16(repeat(d.qData, 1.0f / std::sqrt(static_cast<float>(n))));+ const size_t hidden = base_hidden * n;+ pam.query_data = {std::vector<ov::float16>(q.begin() + past_len * hidden, q.end())};+ pam.key_data = {to_float16(repeat(d.kData, 1.0f))};+ pam.value_data = {to_float16(repeat(d.vData, 1.0f))};+ pam.token_type_ids.assign(d.tokenTypes.begin() + past_len, d.tokenTypes.end());++ auto result = run_gpu_inference(pam, p);++ auto pa_inst = result.network->get_primitive("paged_attention");+ ASSERT_NE(pa_inst, nullptr);+ const auto kernel_entries = pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries();+ EXPECT_NE(kernel_entries.find("sdpa_micro"), std::string::npos) << "head_size=" << p.k_head_size << ": micro SDPA not used for MIXED, got: " << kernel_entries;+ EXPECT_EQ(kernel_entries.find("paged_attention_opt__multi_tokens"), std::string::npos)+ << "head_size=" << p.k_head_size << ": MIXED fell back to the partition kernel: " << kernel_entries;++ const auto expected_full = repeat(d.expectedOutput, 1.0f);+ const std::vector<float> expected(expected_full.begin() + past_len * hidden, expected_full.end());+ compare_token_type_output(result.outputs.at("output_data").get_memory(), expected);+}++static std::vector<paged_attention_token_type_test_params> make_micro_sdpa_mixed_head_test_params() {+ std::vector<paged_attention_token_type_test_params> params;+ const auto all = test::PagedAttentionTokenTypeTestData::GetTestData();+ struct Case { const char* name; int past; std::vector<int> repeats; };+ // SW0: all head sizes. SW5: the largest only.+ for (const Case& c : {Case{"long_sequence", 85, {2, 4, 8}}, Case{"two_small_image_groups", 12, {8}}}) {+ const auto& d = paged_attention_token_type_multi_subsequence_test::find_case(all, c.name);+ for (const int n : c.repeats) { // head_size 64, 128, 256+ auto p = make_token_type_test_param(d, ENABLE_FA_V2);+ p.k_head_size = 32 * n;+ p.v_head_size = 32 * n;+ p.head_repeat = n;+ p.subsequences = {{static_cast<int>(d.tokenTypes.size()) - c.past, c.past}};+ p.token_type_ids = std::vector<int>(d.tokenTypes.begin() + c.past, d.tokenTypes.end());+ params.push_back(p);+ }+ }+ return params;+}++static std::string get_micro_sdpa_mixed_head_test_name(const testing::TestParamInfo<paged_attention_token_type_test_params>& obj) {+ const auto& p = obj.param;+ return p.token_type_test_data.name + "_SW" + std::to_string(p.sliding_window_size) + "_Past" + std::to_string(p.subsequences[0].past_len) + "_Head" ++ std::to_string(p.k_head_size);+}++INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_token_type_micro_sdpa_mixed_head,+ paged_attention_token_type_micro_sdpa_mixed_head_test,+ ::testing::ValuesIn(make_micro_sdpa_mixed_head_test_params()),+ get_micro_sdpa_mixed_head_test_name);+#endif // ENABLE_ONEDNN_FOR_GPU++// ---- Performance (DISABLED_; run with --gtest_also_run_disabled_tests) ----+//+// MIXED with token_type_ids, long past. Runs PA_TT_PERF_ITERS times (default 50) for kernel timing tools.+// Outputs are not checked.+struct pa_tt_perf_config {+ const char* name;+ int past_len;+ int chunk;+ int head_size;+ int num_heads;+ int num_kv_heads;+ bool with_images; // image groups in the chunk (otherwise all zero)+};++class paged_attention_token_type_perf_test : public paged_attention_token_type_test {};++static std::vector<int> make_chunk_token_types(int chunk, bool with_images) {+ std::vector<int> v(chunk, 0);+ if (with_images) {+ // two image groups, about half of the chunk+ const int len = chunk / 4;+ for (int g = 0; g < 2; g++) {+ const int start = chunk / 8 + g * (chunk / 2);+ for (int i = start; i < std::min(chunk, start + len); i++)+ v[i] = 1;+ }+ }+ return v;+}++TEST_P(paged_attention_token_type_perf_test, mixed_token_type_perf) {+ auto p = GetParam();+ const auto& device_info = tests::get_test_engine().get_device_info();+ if (!device_info.supports_immad || device_info.arch < cldnn::gpu_arch::xe_hpg)+ GTEST_SKIP() << "Micro SDPA requires DPAS/XMX support";+ ASSERT_TRUE(this->pam.has_value());+ auto& pam = *this->pam;++ auto result = run_gpu_inference(pam, p);++ int iters = 50;+ if (const char* e = std::getenv("PA_TT_PERF_ITERS"))+ iters = std::max(1, std::atoi(e));+ for (int i = 0; i < iters; i++) {+ result.network->execute();+ }+ tests::get_test_stream().finish();++ auto pa_inst = result.network->get_primitive("paged_attention");+ ASSERT_NE(pa_inst, nullptr);+ std::cout << "[perf] kernels: " << pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries() << " iters=" << iters << std::endl;+}++static std::vector<paged_attention_token_type_test_params> make_token_type_perf_params() {+ std::vector<paged_attention_token_type_test_params> params;+ const std::vector<pa_tt_perf_config> cfgs = {+ {"TextOnly_H128", 4096, 256, 128, 16, 8, false},+ {"Image_H128", 4096, 256, 128, 16, 8, true},+ {"TextOnly_H256", 4096, 256, 256, 8, 4, false},+ {"Image_H256", 4096, 256, 256, 8, 4, true},+ {"TextOnly_H128_Past16k", 16384, 256, 128, 16, 8, false},+ };+ for (const auto& c : cfgs) {+ paged_attention_token_type_test_params p;+ p.subsequences = {{c.chunk, c.past_len}};+ p.num_heads = c.num_heads;+ p.num_kv_heads = c.num_kv_heads;+ p.k_head_size = c.head_size;+ p.v_head_size = c.head_size;+ p.block_size = 16;+ p.sliding_window_size = 0;+ p.kv_cache_compression = DISABLE_CACHE_COMPRESSION;+ p.key_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN;+ p.dynamic_paddings = STATIC_INPUT_PAD;+ p.scores_mode = DISABLE_SCORES;+ p.rotation_config = DISABLE_ROTATION;+ p.disable_flashattn_v2 = ENABLE_FA_V2;+ p.run_reference = false;+ p.token_type_ids = make_chunk_token_types(c.chunk, c.with_images);+ p.token_type_test_data.name = c.name;+ p.case_names = {c.name};+ params.push_back(p);+ }+ return params;+}++INSTANTIATE_TEST_SUITE_P(DISABLED_smoke_paged_attention_token_type_perf,+ paged_attention_token_type_perf_test,+ ::testing::ValuesIn(make_token_type_perf_params()),+ [](const testing::TestParamInfo<paged_attention_token_type_test_params>& obj) { return obj.param.case_names.front(); });