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
[CPU][PA] Align bidirectional image attention and sliding window interaction with reference (#35446)
Przemyslaw Wysockif1c20045edfc
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cppindex 66a3cc3ff0f..6584caff456 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp@@ -446,13 +446,16 @@ struct MHAHelper {bool _use_softmax_sparse_mask = false;// Bidirectional attention for image token groups (e.g. Gemma3 VLM)- bool _has_image_tokens = false; // true only when token_type_ids input is provided- PlainTensor _token_type; // [total_batched_tokens], int32 — 0=text, 1=image- std::vector<int32_t> _image_group_end; // for image token i, the exclusive end of its group+ bool _has_image_tokens = false; // true only when token_type_ids input is provided+ PlainTensor _token_type; // [total_batched_tokens], int32 — 0=text, 1=image+ std::vector<int32_t> _image_group_end; // for image token i, the exclusive end of its group+ std::vector<int32_t> _image_group_begin; // for image token i, the inclusive start of its group// Precompute image group boundaries from token_type_ids.- // For each image token, _image_group_end[i] = index past the last contiguous image token in the same group.- // For text tokens, _image_group_end[i] = -1.+ // For each image token:+ // _image_group_end[i] = index past the last contiguous image token in the same group+ // _image_group_begin[i] = index of the first contiguous image token in the same group+ // For text tokens, both are -1.void set_token_type(const PlainTensor& token_type,const PlainTensor& subsequence_begins,const PlainTensor& past_lens) {@@ -460,27 +463,41 @@ struct MHAHelper {_token_type = token_type;auto total_tokens = static_cast<int32_t>(token_type.m_dims[0]);_image_group_end.resize(total_tokens);+ _image_group_begin.resize(total_tokens);auto seq_count = static_cast<int32_t>(past_lens.m_dims[0]);for (int32_t seq = 0; seq < seq_count; seq++) {auto seq_begin = subsequence_begins.ptr<int32_t>()[seq];auto seq_end = subsequence_begins.ptr<int32_t>()[seq + 1];- // Backward scan within this subsequence to find group ends- for (int32_t i = seq_end - 1; i >= seq_begin; i--) {- if (token_type.ptr<int32_t>()[i] == 1) { // image token- if (i + 1 < seq_end && token_type.ptr<int32_t>()[i + 1] == 1) {- _image_group_end[i] = _image_group_end[i + 1];- } else {- _image_group_end[i] = i + 1;- }- } else {+ // Record both boundaries for each contiguous image group+ for (int32_t i = seq_begin; i < seq_end;) {+ if (token_type.ptr<int32_t>()[i] != 1) {+ _image_group_begin[i] = -1;_image_group_end[i] = -1;+ ++i;+ } else {+ const int32_t group_begin = i;+ while (i < seq_end && token_type.ptr<int32_t>()[i] == 1) {+ ++i;+ }+ const int32_t group_end = i;+ for (int32_t j = group_begin; j < group_end; ++j) {+ _image_group_begin[j] = group_begin;+ _image_group_end[j] = group_end;+ }}}}}+ void clear_token_type() {+ _has_image_tokens = false;+ _token_type = PlainTensor();+ _image_group_end.clear();+ _image_group_begin.clear();+ }+// Return the adjusted ncausal that extends to the image group end for image tokens.// For text tokens, returns the original ncausal unchanged.size_t get_ncausal(size_t q_global_idx, size_t default_ncausal, size_t cur_kv_len) const {@@ -493,6 +510,17 @@ struct MHAHelper {}return default_ncausal;}++ [[nodiscard]] size_t get_sliding_start_idx(size_t q_global_idx, size_t default_ncausal) const {+ const size_t sw_start = default_ncausal > _sliding_window ? default_ncausal - _sliding_window : 0UL;+ if (!_has_image_tokens || q_global_idx >= _image_group_begin.size()) {+ return sw_start;+ }+ if (_token_type.ptr<int32_t>()[q_global_idx] == 1) {+ return std::min(static_cast<size_t>(_image_group_begin[q_global_idx]), sw_start);+ }+ return sw_start;+ }CpuParallelPtr _cpu_parallel;MHAHelper() {@@ -832,7 +860,8 @@ struct MHAHelper {for (size_t m = q_start; m < q_end; m++) {// apply attention mask & sofmax- auto ncausal = get_ncausal(q_token_start + m, cur_kv_len - q_cnt + (m - q_start) + 1, cur_kv_len);+ const auto causal_pos = cur_kv_len - q_cnt + (m - q_start) + 1;+ const auto ncausal = get_ncausal(q_token_start + m, causal_pos, cur_kv_len);auto* score = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);// dequantization of q matrix could be fused with _d_scale since softmax is done by rowfloat revised_d_scale =@@ -846,13 +875,9 @@ struct MHAHelper {sink = &sinks.at<float>({0, h, 0, 0}, true);}if (_sliding_window) {- size_t start_idx = 0;- auto new_causal = ncausal;+ const auto start_idx = get_sliding_start_idx(q_token_start + m, causal_pos);+ const auto new_causal = ncausal - start_idx;float* alibi_lookup = nullptr;- if (ncausal > _sliding_window) {- start_idx = ncausal - _sliding_window;- new_causal = _sliding_window;- }// Handle sparse attention mask for sliding windowif (!sparse_attention_mask.empty() && sparse_attention_mask[batch_in_seq].ptr_v() != nullptr &&@@ -1041,7 +1066,8 @@ struct MHAHelper {for (size_t m = q_start; m < q_end; m++) {// apply softmax in f32 precision- auto ncausal = get_ncausal(q_token_start + m, cur_kv_len - q_cnt + (m - q_start) + 1, cur_kv_len);+ const auto causal_pos = cur_kv_len - q_cnt + (m - q_start) + 1;+ const auto ncausal = get_ncausal(q_token_start + m, causal_pos, cur_kv_len);auto soft_in = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);auto score = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);PlainTensor f32_cvt;@@ -1053,13 +1079,9 @@ struct MHAHelper {soft_in = f32_cvt.ptr<float>(0);}if (_sliding_window) {- size_t start_idx = 0;- auto new_causal = ncausal;+ const auto start_idx = get_sliding_start_idx(q_token_start + m, causal_pos);+ const auto new_causal = ncausal - start_idx;float* alibi_lookup = nullptr;- if (ncausal > _sliding_window) {- start_idx = ncausal - static_cast<size_t>(_sliding_window);- new_causal = _sliding_window;- }attn_softmax_kernel<float>(soft_in + start_idx,reinterpret_cast<DATA_TYPE*>(score) + start_idx,_d_scale,@@ -1197,7 +1219,7 @@ struct MHAHelper {for (size_t pq = 0; pq < q_len; pq++) {for (size_t h = hq_beg; h < hq_end; h++) {// apply attention mask & sofmax- auto ncausal = get_ncausal(q_token_start + pq, cur_kv_len, cur_kv_len);+ const auto ncausal = get_ncausal(q_token_start + pq, cur_kv_len, cur_kv_len);float* score = _weight.ptr<float>(ithr, h - hq_beg, pq);OPENVINO_DEBUG_ASSERT(score != nullptr, "PagedAttention: _weight buffer must be allocated");float* alibi_lookup = nullptr;@@ -1211,13 +1233,9 @@ struct MHAHelper {sink = &sinks.at<float>({0, h, 0, 0}, true);}if (_sliding_window) {- size_t start_idx = 0;- size_t new_causal = ncausal;+ const auto start_idx = get_sliding_start_idx(q_token_start + pq, cur_kv_len);+ const size_t new_causal = ncausal - start_idx;float* sw_alibi_lookup = nullptr;- if (ncausal > _sliding_window) {- start_idx = ncausal - _sliding_window;- new_causal = _sliding_window;- }attn_softmax_kernel<float>(score + start_idx,score + start_idx,_d_scale,@@ -1408,7 +1426,7 @@ struct MHAHelper {auto loop_softmax = [&](size_t b, size_t h, size_t pq) {auto cur_kv_len = static_cast<size_t>(past_lens.ptr<int32_t>()[b]) + 1;auto q_token_start = static_cast<size_t>(subsequence_begins.ptr<int32_t>()[b]);- auto ncausal = get_ncausal(q_token_start + pq, cur_kv_len, cur_kv_len);+ const auto ncausal = get_ncausal(q_token_start + pq, cur_kv_len, cur_kv_len);// apply attention mask & sofmaxfloat* score = _weight_bhl.ptr<float>(b, h, pq);OPENVINO_DEBUG_ASSERT(score != nullptr, "PagedAttention: _weight_bhl buffer must be allocated");@@ -1423,13 +1441,9 @@ struct MHAHelper {sink = &sinks.at<float>({0, h, 0, 0}, true);}if (_sliding_window) {- size_t start_idx = 0;- size_t new_causal = ncausal;+ const auto start_idx = get_sliding_start_idx(q_token_start + pq, cur_kv_len);+ const size_t new_causal = ncausal - start_idx;float* sw_alibi_lookup = nullptr;- if (ncausal > _sliding_window) {- start_idx = ncausal - _sliding_window;- new_causal = _sliding_window;- }attn_softmax_kernel<float>(score + start_idx,score + start_idx,_d_scale,@@ -2381,8 +2395,7 @@ struct AttentionExecutor : public PagedAttentionExecutor {if (token_type_ids) {_helper.set_token_type(token_type_ids, subsequence_begins, past_lens);} else {- _helper._token_type = PlainTensor();- _helper._image_group_end.clear();+ _helper.clear_token_type();}if (rotated_block_indices) {diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_token_type.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_token_type.cppindex 6eb795f7a30..02ff13505fc 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_token_type.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_token_type.cpp@@ -72,7 +72,8 @@ public:std::shared_ptr<ov::Model> get_pa_model(ov::element::Type data_type,ov::Dimension::value_type head_size,- ov::Dimension::value_type head_num) {+ ov::Dimension::value_type head_num,+ int32_t sliding_window_size = 0) {auto q = make_param(PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic()}, data_type, "q");auto k = make_param(PartialShape{ov::Dimension::dynamic(), head_num * head_size}, data_type, "k");auto v = make_param(PartialShape{ov::Dimension::dynamic(), head_num * head_size}, data_type, "v");@@ -87,7 +88,7 @@ public:float scale_value = 1.0f / std::sqrt(static_cast<float>(head_size));auto scale = std::make_shared<v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale_value});- auto sliding_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto sliding_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{sliding_window_size});auto alibi_slopes = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});auto max_context_len = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{1024});auto score_aggregation_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});@@ -269,18 +270,10 @@ TEST_P(PagedAttnTokenTypeTest, AllTextIsCausal) {// First prefix_len positions of the full run should match the prefix run exactlysize_t hidden_dim = head_num * head_size;- auto* full_data = result_full.output.data<float>();- auto* prefix_data = result_prefix.output.data<float>();-- for (size_t pos = 0; pos < prefix_len; pos++) {- for (size_t d = 0; d < hidden_dim; d++) {- float diff = std::abs(full_data[pos * hidden_dim + d] - prefix_data[pos * hidden_dim + d]);- EXPECT_LT(diff, 1e-5f)- << "Causal masking violated: position " << pos << " dim " << d- << " differs between seq_len=" << full_len << " and seq_len=" << prefix_len- << ", diff=" << diff;- }- }+ ov::Tensor full_prefix_view(result_full.output.get_element_type(),+ ov::Shape{prefix_len, hidden_dim},+ result_full.output.data<float>());+ ov::test::utils::compare(full_prefix_view, result_prefix.output, 1e-5);}@@ -344,21 +337,20 @@ TEST_P(PagedAttnTokenTypeTest, TextTokensUnaffected) {// Text tokens BEFORE the first image group should have identical outputsize_t hidden_dim = head_num * head_size;- auto* bidir_data = result_bidir.output.data<float>();- auto* causal_data = result_causal.output.data<float>();size_t first_image_pos = seq_len;for (size_t i = 0; i < seq_len; i++) {if (pattern.types[i] == 1) { first_image_pos = i; break; }}- for (size_t pos = 0; pos < first_image_pos; pos++) {- for (size_t d = 0; d < hidden_dim; d++) {- float diff = std::abs(bidir_data[pos * hidden_dim + d] - causal_data[pos * hidden_dim + d]);- EXPECT_LT(diff, 1e-5f)- << "Text token at position " << pos << " dim " << d- << " should be unaffected by token_type_ids, but diff=" << diff;- }+ if (first_image_pos > 0) {+ ov::Tensor bidir_text(result_bidir.output.get_element_type(),+ ov::Shape{first_image_pos, hidden_dim},+ result_bidir.output.data<float>());+ ov::Tensor causal_text(result_causal.output.get_element_type(),+ ov::Shape{first_image_pos, hidden_dim},+ result_causal.output.data<float>());+ ov::test::utils::compare(causal_text, bidir_text, 1e-5);}}@@ -393,13 +385,72 @@ TEST_P(PagedAttnTokenTypeTest, PostImageTextIsCausal) {// Text tokens after the last image group should match causal baselinefor (size_t pos = last_image_pos + 1; pos < seq_len; pos++) {ASSERT_EQ(pattern.types[pos], 0) << "Expected text token at position " << pos;- for (size_t d = 0; d < hidden_dim; d++) {+ }+ if (last_image_pos + 1 < seq_len) {+ size_t post_len = seq_len - last_image_pos - 1;+ ov::Tensor bidir_post(result_bidir.output.get_element_type(),+ ov::Shape{post_len, hidden_dim},+ bidir_data + (last_image_pos + 1) * hidden_dim);+ ov::Tensor causal_post(result_causal.output.get_element_type(),+ ov::Shape{post_len, hidden_dim},+ causal_data + (last_image_pos + 1) * hidden_dim);+ ov::test::utils::compare(causal_post, bidir_post, 1e-5);+ }+}+++// Verify that bidirectional image attention interacts correctly with sliding window+TEST_P(PagedAttnTokenTypeTest, ImageTokensWithSlidingWindowDifferFromCausal) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();+ const auto& [inType, head_size, head_num, pattern] = this->GetParam();+ if (inType == ElementType::bf16 && !ov::with_cpu_x86_bfloat16())+ GTEST_SKIP();++ targetDevice = ov::test::utils::DEVICE_CPU;++ const size_t seq_len = pattern.types.size();++ int first_image = -1;+ int last_image = -1;+ for (size_t i = 0; i < seq_len; ++i) {+ if (pattern.types[i] == 1) {+ if (first_image == -1)+ first_image = static_cast<int>(i);+ if (last_image != -1 && pattern.types[last_image] == 1 && static_cast<int>(i) > last_image + 1)+ break;+ last_image = static_cast<int>(i);+ }+ }++ const int group_size = last_image - first_image + 1;+ const int32_t sw = group_size - 1;++ auto model_bidir = get_pa_model(inType, head_size, head_num, sw);+ auto result_bidir = run_pa_with_token_types(model_bidir, inType, seq_len, head_size, head_num, pattern.types);++ std::vector<int32_t> all_text(seq_len, 0);+ auto model_causal = get_pa_model(inType, head_size, head_num, sw);+ auto result_causal = run_pa_with_token_types(model_causal, inType, seq_len, head_size, head_num, all_text);++ const size_t hidden_dim = head_num * head_size;+ const auto* bidir_data = result_bidir.output.data<float>();+ const auto* causal_data = result_causal.output.data<float>();++ bool any_image_differs = false;+ for (int pos = first_image; pos <= last_image && !any_image_differs; ++pos) {+ for (size_t d = 0; d < hidden_dim; ++d) {float diff = std::abs(bidir_data[pos * hidden_dim + d] - causal_data[pos * hidden_dim + d]);- EXPECT_LT(diff, 1e-5f)- << "Post-image text token at position " << pos << " dim " << d- << " should match causal baseline, but diff=" << diff;+ if (diff > 1e-5f) {+ any_image_differs = true;+ break;+ }}}+ EXPECT_TRUE(any_image_differs)+ << "Pattern '" << pattern.name << "' with sliding_window=" << sw+ << ": expected image tokens (bidir) to differ from causal baseline, but they were identical.\n"+ << "This indicates the sliding window is incorrectly clipping the image group "+ << "[" << first_image << ", " << last_image << "].\n";}namespace {