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
Add XAttention inputs to the PagedAttention OP (#31384)
Vasily Shamporov879ff5893a54
diff --git a/src/bindings/python/src/pyopenvino/core/offline_transformations.cpp b/src/bindings/python/src/pyopenvino/core/offline_transformations.cppindex 8b994708828..7afcb0bcdd6 100644--- a/src/bindings/python/src/pyopenvino/core/offline_transformations.cpp+++ b/src/bindings/python/src/pyopenvino/core/offline_transformations.cpp@@ -147,20 +147,23 @@ void regmodule_offline_transformations(py::module m) {bool use_block_indices_inputs,bool use_score_outputs,bool allow_score_aggregation,- bool allow_cache_rotation) {+ bool allow_cache_rotation,+ bool allow_xattention) {const auto model = Common::utils::convert_to_model(ie_api_model);ov::pass::Manager manager;manager.register_pass<ov::pass::SDPAToPagedAttention>(use_block_indices_inputs,use_score_outputs,allow_score_aggregation,- allow_cache_rotation);+ allow_cache_rotation,+ allow_xattention);manager.run_passes(model);},py::arg("model"),py::arg("use_block_indices_inputs") = false,py::arg("use_score_outputs") = false,py::arg("allow_score_aggregation") = false,- py::arg("allow_cache_rotation") = false);+ py::arg("allow_cache_rotation") = false,+ py::arg("allow_xattention") = false);m_offline_transformations.def("stateful_to_stateless_transformation",diff --git a/src/common/transformations/include/transformations/sdpa_to_paged_attention/state_management_pattern.hpp b/src/common/transformations/include/transformations/sdpa_to_paged_attention/state_management_pattern.hppindex 0e353ff83a5..f86ce8dff97 100644--- a/src/common/transformations/include/transformations/sdpa_to_paged_attention/state_management_pattern.hpp+++ b/src/common/transformations/include/transformations/sdpa_to_paged_attention/state_management_pattern.hpp@@ -29,8 +29,9 @@ public:bool use_score_outputs,bool allow_cache_rotation,bool allow_score_aggregation,+ bool allow_xattention,ParameterVector& rotated_block_indices_inputs_for_each_layer,ParameterVector& rotation_deltas_inputs_for_each_layer,- std::shared_ptr<op::v0::Parameter> model_rotation_trig_lut,+ ParameterVector& xattention_threshold_inputs_for_each_layer,const std::map<std::string, std::shared_ptr<op::v0::Parameter>>& optional_model_wide_params);};diff --git a/src/common/transformations/src/transformations/common_optimizations/convert_pagedattn_inputs.cpp b/src/common/transformations/src/transformations/common_optimizations/convert_pagedattn_inputs.cppindex c4f9b3aad38..636c20ed609 100644--- a/src/common/transformations/src/transformations/common_optimizations/convert_pagedattn_inputs.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/convert_pagedattn_inputs.cpp@@ -41,44 +41,30 @@ ov::pass::ConvertPagedAttnInputs::ConvertPagedAttnInputs(const KVCacheConfig& coauto rotated_block_indices = pattern::any_input(pattern::has_static_rank());auto rotation_deltas = pattern::any_input(pattern::has_static_rank());auto rotation_trig_lut = pattern::any_input(pattern::has_static_rank());+ auto xattention_threshold = pattern::any_input(pattern::has_static_rank());+ auto xattention_block_size = pattern::any_input(pattern::has_static_rank());+ auto xattention_stride = pattern::any_input(pattern::has_static_rank());- auto pa_1 = pattern::wrap_type<op::PagedAttentionExtension>({- Q,- K,- V,- key_cache_0,- value_cache_0,- past_lens,- subsequence_begins,- block_indices,- block_indices_begins,- scale,- sliding_window,- alibi_slopes,- max_context_len,- score_aggregation_window,- });-- auto pa_2 = pattern::wrap_type<op::PagedAttentionExtension>({- Q,- K,- V,- key_cache_0,- value_cache_0,- past_lens,- subsequence_begins,- block_indices,- block_indices_begins,- scale,- sliding_window,- alibi_slopes,- max_context_len,- score_aggregation_window,- rotated_block_indices,- rotation_deltas,- rotation_trig_lut,- });- auto result = pa_1 | pa_2;+ auto result = pattern::wrap_type<op::PagedAttentionExtension>({Q,+ K,+ V,+ key_cache_0,+ value_cache_0,+ past_lens,+ subsequence_begins,+ block_indices,+ block_indices_begins,+ scale,+ sliding_window,+ alibi_slopes,+ max_context_len,+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {const auto pa_op = m.get_match_root();auto key_cache = ov::as_type_ptr<v0::Parameter>(pa_op->get_input_node_shared_ptr(3));diff --git a/src/common/transformations/src/transformations/sdpa_to_paged_attention/state_management_pattern.cpp b/src/common/transformations/src/transformations/sdpa_to_paged_attention/state_management_pattern.cppindex ae3be3610ce..16cd159baf7 100644--- a/src/common/transformations/src/transformations/sdpa_to_paged_attention/state_management_pattern.cpp+++ b/src/common/transformations/src/transformations/sdpa_to_paged_attention/state_management_pattern.cpp@@ -241,9 +241,10 @@ ov::pass::StateManagementPattern::StateManagementPattern(bool use_score_outputs,bool allow_cache_rotation,bool allow_score_aggregation,+ bool allow_xattention,ParameterVector& rotated_block_indices_inputs_for_each_layer,ParameterVector& rotation_deltas_inputs_for_each_layer,- std::shared_ptr<op::v0::Parameter> model_rotation_trig_lut,+ ParameterVector& xattention_threshold_inputs_for_each_layer,const std::map<std::string, std::shared_ptr<op::v0::Parameter>>& optional_model_wide_params) {MATCHER_SCOPE(StateManagementPattern);@@ -353,7 +354,8 @@ ov::pass::StateManagementPattern::StateManagementPattern(&score_results,&layer_index,&rotated_block_indices_inputs_for_each_layer,- &rotation_deltas_inputs_for_each_layer](ov::pass::pattern::Matcher& m) {+ &rotation_deltas_inputs_for_each_layer,+ &xattention_threshold_inputs_for_each_layer](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();auto real_q = pattern_map.at(q);@@ -556,10 +558,13 @@ ov::pass::StateManagementPattern::StateManagementPattern(} else {pa_arguments.insert(pa_arguments.end(), v0::Constant::create(element::i32, Shape{0}, {}));}-OPENVINO_ASSERT(pa_arguments.size() == 14);if (allow_cache_rotation) {+ OPENVINO_ASSERT(+ optional_model_wide_params.find("model_rotation_trig_lut") != optional_model_wide_params.end(),+ "No model_rotation_trig_lut input found. For using cache rotation, the model have to contain "+ "an additional input (Parameter) called model_rotation_trig_lut.");auto rotated_block_indices = setName(std::make_shared<v0::Parameter>(element::i32, PartialShape{-1}),"rotated_block_indices." + std::to_string(layer_index - 1));auto rotation_deltas = setName(std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, -1}),@@ -567,12 +572,42 @@ ov::pass::StateManagementPattern::StateManagementPattern(pa_arguments.insert(pa_arguments.begin() + 14, rotated_block_indices);pa_arguments.insert(pa_arguments.begin() + 15, rotation_deltas);- pa_arguments.insert(pa_arguments.begin() + 16, model_rotation_trig_lut);+ pa_arguments.insert(pa_arguments.begin() + 16, optional_model_wide_params.at("model_rotation_trig_lut"));rotated_block_indices_inputs_for_each_layer.push_back(rotated_block_indices);rotation_deltas_inputs_for_each_layer.push_back(rotation_deltas);+ } else {+ auto rotated_block_indices = v0::Constant::create(element::i32, Shape{0}, {});+ auto rotation_deltas = v0::Constant::create(element::i32, Shape{0}, {});+ pa_arguments.insert(pa_arguments.begin() + 14, rotated_block_indices);+ pa_arguments.insert(pa_arguments.begin() + 15, rotation_deltas);+ pa_arguments.insert(pa_arguments.begin() + 16, v0::Constant::create(element::f32, Shape{0}, {}));}+ OPENVINO_ASSERT(pa_arguments.size() == 17);+ if (allow_xattention) {+ OPENVINO_ASSERT(+ optional_model_wide_params.find("xattention_block_size") != optional_model_wide_params.end(),+ "No xattention_block_size input found. For using XAttention, the model have to contain "+ "an additional input (Parameter) called xattention_block_size.");+ OPENVINO_ASSERT(optional_model_wide_params.find("xattention_stride") != optional_model_wide_params.end(),+ "No xattention_stride input found. For using XAttention, the model have to contain "+ "an additional input (Parameter) called xattention_stride.");+ auto xattention_threshold = setName(std::make_shared<v0::Parameter>(element::f32, PartialShape{-1}),+ "xattention_threshold." + std::to_string(layer_index - 1));+ pa_arguments.insert(pa_arguments.begin() + 17, xattention_threshold);+ pa_arguments.insert(pa_arguments.begin() + 18, optional_model_wide_params.at("xattention_block_size"));+ pa_arguments.insert(pa_arguments.begin() + 19, optional_model_wide_params.at("xattention_stride"));+ xattention_threshold_inputs_for_each_layer.push_back(xattention_threshold);+ } else {+ auto xattention_threshold = v0::Constant::create(element::f32, Shape{0}, {});+ pa_arguments.insert(pa_arguments.begin() + 17, xattention_threshold);+ pa_arguments.insert(pa_arguments.begin() + 18, v0::Constant::create(element::i32, Shape{}, {0}));+ pa_arguments.insert(pa_arguments.begin() + 19, v0::Constant::create(element::i32, Shape{}, {0}));+ }++ OPENVINO_ASSERT(pa_arguments.size() == 20);+auto paged_attention = std::make_shared<ov::op::PagedAttentionExtension>(pa_arguments);// The output shape of PagedAttention will be converted to [batch, 1, head_num, head_size_v], the head_size_vdiff --git a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cppindex aed4457a8ae..be0915fa2c7 100644--- a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp+++ b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp@@ -106,6 +106,12 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {auto sliding_window = std::make_shared<v0::Constant>(element::i32, Shape{}, 0);auto alibi_slopes = std::make_shared<v0::Constant>(element::f32, Shape{0});auto score_aggregation_window = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotated_block_indices = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotation_deltas = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotation_trig_lut = std::make_shared<v0::Parameter>(ov::element::f32, PartialShape{DYN});+ auto xattention_threshold = std::make_shared<v0::Parameter>(ov::element::f32, PartialShape{DYN});+ auto xattention_block_size = std::make_shared<v0::Parameter>(ov::element::i32, Shape{});+ auto xattention_stride = std::make_shared<v0::Parameter>(ov::element::i32, Shape{});auto pa = std::make_shared<op::PagedAttentionExtension>(OutputVector{Q,K,@@ -120,7 +126,13 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {sliding_window,alibi_slopes,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});pa->get_rt_info()["num_k_heads"] = numKeyHeads;pa->get_rt_info()["k_head_size"] = keyHeadSize;pa->get_rt_info()["num_v_heads"] = numValueHeads;@@ -137,7 +149,13 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {block_indices,block_indices_begins,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});if (isIRKVCacheF16) {model->set_rt_info("f16", "runtime_options", ov::hint::kv_cache_precision.name());}@@ -203,6 +221,12 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {auto sliding_window = std::make_shared<v0::Constant>(element::i32, Shape{}, 0);auto alibi_slopes = std::make_shared<v0::Constant>(element::f32, Shape{0});auto score_aggregation_window = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotated_block_indices = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotation_deltas = std::make_shared<v0::Parameter>(ov::element::i32, PartialShape{DYN});+ auto rotation_trig_lut = std::make_shared<v0::Parameter>(ov::element::f32, PartialShape{DYN});+ auto xattention_threshold = std::make_shared<v0::Parameter>(ov::element::f32, PartialShape{DYN});+ auto xattention_block_size = std::make_shared<v0::Parameter>(ov::element::i32, Shape{});+ auto xattention_stride = std::make_shared<v0::Parameter>(ov::element::i32, Shape{});auto pa = std::make_shared<op::PagedAttentionExtension>(OutputVector{Q,K,@@ -217,7 +241,13 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {sliding_window,alibi_slopes,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});pa->get_rt_info()["num_k_heads"] = numKeyHeads;pa->get_rt_info()["k_head_size"] = keyHeadSize;pa->get_rt_info()["num_v_heads"] = numValueHeads;@@ -234,7 +264,13 @@ TEST_P(ConvertPagedAttnInputsTest, checkPrecisionAndShape) {block_indices,block_indices_begins,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});}ov::pass::ConvertPagedAttnInputs::KVCacheConfig cacheConfig;cacheConfig.keyCacheBlockSize = blockSize[0];diff --git a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cppindex 320fdb222fa..eafa3e1c462 100644--- a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp+++ b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp@@ -536,6 +536,14 @@ TEST_P(SDPAToPATest, SDPAToPA_Qwen7bChat_General) {auto input_ids = makeOP<v0::Parameter>({}, {{"shape", PartialShape{DYN}}, el_type_i64});auto position_ids = makeOP<v0::Parameter>({}, {{"shape", PartialShape{DYN}}, el_type_i64});auto score_aggregation_window = makeOP<v0::Parameter>({}, {{"shape", PartialShape{DYN}}, el_type_i32});++ auto rotated_block_indices = makeConst(element::i32, ov::Shape({0}), {0});+ auto rotation_deltas = makeConst(element::i32, ov::Shape{0}, {0});+ auto rotation_trig_lut = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_threshold = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_block_size = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+ auto xattention_stride = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+auto params = nodes_to_params({score_aggregation_window,max_context_len,block_indices_begins,@@ -599,7 +607,13 @@ TEST_P(SDPAToPATest, SDPAToPA_Qwen7bChat_General) {sliding_window,alibi_slopes,max_context_len,- score_aggregation_window_const});+ score_aggregation_window_const,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});pa->set_out_type(0, element::i64);auto pa_aligned = Qwen7bChatPA::align_pa_layout(pa, head_size_2);auto res = makeOP<v0::Result>({pa_aligned});@@ -884,6 +898,12 @@ TEST_F(SDPAToPATest, SDPAToPA_Baichuan2_13b_General) {auto key_cache_0 = make_param(PartialShape{DYN, 40, 128}, element::f32, "key_cache.0");auto input_ids = make_param(PartialShape{DYN}, element::i64, "input_ids");auto score_aggregation_window = makeConst(element::i32, ov::Shape({0}), MOCK_VALUE);+ auto rotated_block_indices = makeConst(element::i32, ov::Shape({0}), {0});+ auto rotation_deltas = makeConst(element::i32, ov::Shape{0}, {0});+ auto rotation_trig_lut = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_threshold = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_block_size = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+ auto xattention_stride = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);ParameterVector params = nodes_to_params({max_context_len,block_indices_begins,@@ -967,7 +987,13 @@ TEST_F(SDPAToPATest, SDPAToPA_Baichuan2_13b_General) {c2,Reshape166,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});auto ShapeOf172 = makeOP<opset3::ShapeOf>({Transpose154}, {{"output_type", "i64"}});auto Gather175 = makeOP<opset8::Gather>({ShapeOf172, -1, 0}, {{"batch_dims", 0}});auto Unsqueeze177 = makeOP<opset1::Unsqueeze>({Gather175, 0});@@ -1187,6 +1213,12 @@ TEST_F(SDPAToPATest, SDPAToPA_nanoLLaVA_General) {auto inputs_embeds = make_param(PartialShape{DYN, DYN}, element::f32, "inputs_embeds");auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");auto score_aggregation_window = makeConst(element::i32, ov::Shape({0}), MOCK_VALUE);+ auto rotated_block_indices = makeConst(element::i32, ov::Shape({0}), {0});+ auto rotation_deltas = makeConst(element::i32, ov::Shape{0}, {0});+ auto rotation_trig_lut = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_threshold = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_block_size = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+ auto xattention_stride = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);ParameterVector params = nodes_to_params({max_context_len,block_indices_begins,@@ -1316,7 +1348,13 @@ TEST_F(SDPAToPATest, SDPAToPA_nanoLLaVA_General) {c2,c3,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});auto ShapeOf_51965 = makeOP<opset3::ShapeOf>({Transpose_51955}, {{"output_type", "i64"}});auto Gather_51966 = makeOP<opset8::Gather>({ShapeOf_51965, -1, 0}, {{"batch_dims", 0}});auto Unsqueeze_51971 = makeOP<opset1::Unsqueeze>({Gather_51966, 0});@@ -1510,6 +1548,12 @@ TEST_F(SDPAToPATest, SDPAToPA_Phi3_mini_4k_instruct) {auto inputs_ids = make_param(PartialShape{DYN}, element::i64, "inputs_ids");auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");auto score_aggregation_window = makeConst(element::i32, ov::Shape({0}), MOCK_VALUE);+ auto rotated_block_indices = makeConst(element::i32, ov::Shape({0}), {0});+ auto rotation_deltas = makeConst(element::i32, ov::Shape{0}, {0});+ auto rotation_trig_lut = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_threshold = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_block_size = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+ auto xattention_stride = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);auto params = nodes_to_params({max_context_len,block_indices_begins,@@ -1621,7 +1665,13 @@ TEST_F(SDPAToPATest, SDPAToPA_Phi3_mini_4k_instruct) {sliding_window,alibi_slopes,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});auto ShapeOf1 = makeOP<opset3::ShapeOf>({Transpose6}, {{"output_type", "i64"}});auto Gather2 = makeOP<opset8::Gather>({ShapeOf1, -1, 0}, {{"batch_dims", 0}});auto Unsqueeze5 = makeOP<opset1::Unsqueeze>({Gather2, 0});@@ -1817,7 +1867,13 @@ TEST_F(SDPAToPATest, SDPAToPA_Codegen2) {auto key_cache_0 = make_param(PartialShape{DYN, 16, 256}, element::f32, "key_cache_0");auto input_ids = make_param(PartialShape{DYN}, element::i64, "inputs_ids");auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");- auto Constant0 = makeConst(element::i32, ov::Shape({0}), MOCK_VALUE);+ auto score_aggregation_window = makeConst(element::i32, ov::Shape({0}), MOCK_VALUE);+ auto rotated_block_indices = makeConst(element::i32, ov::Shape({0}), {0});+ auto rotation_deltas = makeConst(element::i32, ov::Shape{0}, {0});+ auto rotation_trig_lut = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_threshold = makeConst(element::f32, ov::Shape({0}), {0});+ auto xattention_block_size = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);+ auto xattention_stride = makeConst(element::i32, ov::Shape({}), MOCK_VALUE);auto params = nodes_to_params({max_context_len,block_indices_begins,@@ -1945,7 +2001,13 @@ TEST_F(SDPAToPATest, SDPAToPA_Codegen2) {sliding_window,alibi_slopes_stub,max_context_len,- Constant0});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});auto ShapeOf2 = makeOP<opset3::ShapeOf>({Transpose7}, {{"output_type", "i64"}});auto Gather5 = makeOP<opset8::Gather>({ShapeOf2, -1, 0}, {{"batch_dims", 0}});auto Unsqueeze9 = makeOP<opset1::Unsqueeze>({Gather5, 0});diff --git a/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp b/src/core/include/openvino/pass/sdpa_to_paged_attention.hppindex 758bfd8492c..d5491df199b 100644--- a/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp+++ b/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp@@ -22,7 +22,8 @@ public:explicit SDPAToPagedAttention(bool use_per_layer_block_indices_inputs = false,bool use_score_outputs = false,bool allow_score_aggregation = false,- bool allow_cache_rotation = false);+ bool allow_cache_rotation = false,+ bool allow_xattention = false);bool run_on_model(const std::shared_ptr<ov::Model>& model) override;private:@@ -30,6 +31,7 @@ private:bool m_use_score_outputs;bool m_allow_score_aggregation;bool m_allow_cache_rotation;+ bool m_allow_xattention;};} // namespace pass} // namespace ovdiff --git a/src/core/src/op/paged_attention.cpp b/src/core/src/op/paged_attention.cppindex ba923c6523d..e24f7b4f059 100644--- a/src/core/src/op/paged_attention.cpp+++ b/src/core/src/op/paged_attention.cpp@@ -79,8 +79,8 @@ void PagedAttentionExtension::validate_and_infer_types() {OV_OP_SCOPE(PagedAttentionExtension_validate_and_infer_types);NODE_VALIDATION_CHECK(this,- get_input_size() == 14 || get_input_size() == 17,- "PagedAttensionExtension expects 14 or 17 inputs, but it has ",+ get_input_size() == 20,+ "PagedAttensionExtension expects 20 inputs, but it has ",get_input_size());// format: Node*, input_idx, name, {rank_list}, {type_list}@@ -98,11 +98,12 @@ void PagedAttentionExtension::validate_and_infer_types() {input_check(this, 11, "alibi_slopes", {1}, get_real_types());input_check(this, 12, "max_context_len", {0}, {element::i32});input_check(this, 13, "score_aggregation_window", {0, 1}, {element::i32});- if (get_input_size() == 17) {- input_check(this, 14, "rotated_block_indices", {1}, {element::i32});- input_check(this, 15, "rotation_deltas", {2}, {element::i32});- input_check(this, 16, "rotation_trig_lut", {2}, {element::f16, element::f32});- }+ input_check(this, 14, "rotated_block_indices", {1}, {element::i32});+ input_check(this, 15, "rotation_deltas", {1, 2}, {element::i32});+ input_check(this, 16, "rotation_trig_lut", {1, 2}, {element::f16, element::f32});+ input_check(this, 17, "xattention_threshold", {1}, {element::f32});+ input_check(this, 18, "xattention_block_size", {0}, {element::i32});+ input_check(this, 19, "xattention_stride", {0}, {element::i32});// value head_size may be not same with keyauto out_ps = get_input_partial_shape(0);diff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cppindex 5a563dd52b6..f53625a4482 100644--- a/src/core/src/pass/sdpa_to_paged_attention.cpp+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp@@ -23,11 +23,13 @@ using namespace ov::op;ov::pass::SDPAToPagedAttention::SDPAToPagedAttention(bool use_per_layer_block_indices_inputs,bool use_score_outputs,bool allow_score_aggregation,- bool allow_cache_rotation)+ bool allow_cache_rotation,+ bool allow_xattention): m_use_per_layer_block_indices_inputs(use_per_layer_block_indices_inputs),m_use_score_outputs(use_score_outputs),m_allow_score_aggregation(use_score_outputs),- m_allow_cache_rotation(allow_cache_rotation) {}+ m_allow_cache_rotation(allow_cache_rotation),+ m_allow_xattention(allow_xattention) {}static std::shared_ptr<v0::Parameter> setName(std::shared_ptr<v0::Parameter> node, const char* name) {// Set name for both node and output tensor (should be only one tensor, and any other names will be overriden by a@@ -62,13 +64,18 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::ModesetName(std::make_shared<v0::Parameter>(element::i32, PartialShape{-1}), "score_aggregation_window");}- std::shared_ptr<v0::Parameter> model_rotation_trig_lut;-if (m_allow_cache_rotation) {- model_rotation_trig_lut =+ optional_model_wide_params["model_rotation_trig_lut"] =setName(std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, -1}), "rotation_trig_lut");}+ if (m_allow_xattention) {+ optional_model_wide_params["xattention_block_size"] =+ setName(std::make_shared<v0::Parameter>(element::i32, PartialShape{}), "xattention_block_size");+ optional_model_wide_params["xattention_stride"] =+ setName(std::make_shared<v0::Parameter>(element::i32, PartialShape{}), "xattention_stride");+ }+auto get_parameter = [=](const std::shared_ptr<ov::Model>& model,const std::string& name) -> std::shared_ptr<v0::Parameter> {for (const auto& param : model->inputs()) {@@ -115,6 +122,7 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::ModeParameterVector block_indices_inputs_for_each_layer;ParameterVector rotated_block_indices_inputs_for_each_layer;ParameterVector rotation_deltas_inputs_for_each_layer;+ ParameterVector xattention_threshold_inputs_for_each_layer;ResultVector score_results;@@ -149,9 +157,10 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Modem_use_score_outputs,m_allow_cache_rotation,m_allow_score_aggregation,+ m_allow_xattention,rotated_block_indices_inputs_for_each_layer,rotation_deltas_inputs_for_each_layer,- model_rotation_trig_lut,+ xattention_threshold_inputs_for_each_layer,optional_model_wide_params);manager.register_pass<PrevSequenceLengthPattern>(processed_input_ids, max_context_len, position_ids);manager.register_pass<TotalSequenceLengthPattern>(max_context_len);@@ -219,7 +228,13 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Modeif (m_allow_cache_rotation) {model->add_parameters(rotated_block_indices_inputs_for_each_layer);model->add_parameters(rotation_deltas_inputs_for_each_layer);- model->add_parameters({std::move(model_rotation_trig_lut)});+ model->add_parameters({optional_model_wide_params["model_rotation_trig_lut"]});+ }++ if (m_allow_xattention) {+ model->add_parameters(xattention_threshold_inputs_for_each_layer);+ model->add_parameters({optional_model_wide_params["xattention_block_size"]});+ model->add_parameters({optional_model_wide_params["xattention_stride"]});}model->add_parameters(kv_parameters);diff --git a/src/core/tests/type_prop/paged_attention.cpp b/src/core/tests/type_prop/paged_attention.cppindex 92a1e98ca00..dff66d69972 100644--- a/src/core/tests/type_prop/paged_attention.cpp+++ b/src/core/tests/type_prop/paged_attention.cpp@@ -11,43 +11,7 @@namespace ov {namespace testing {-TEST(type_prop, paged_attention_static_14_inputs) {- const auto query = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});- const auto key = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});- const auto value = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});- const auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{6, 2, 5, 4});- const auto value_cache = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{6, 2, 5, 4});- const auto past_lens = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{5});- const auto subsequence_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{5});- const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{15});- const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{8});- const auto scale = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{});- const auto sliding_window = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});- const auto alibi_slopes = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{9});- const auto max_context_len = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});- const auto score_aggregation_window = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});-- ov::OutputVector args = {query,- key,- value,- key_cache,- value_cache,- past_lens,- subsequence_begins,- block_indices,- block_indices_begins,- scale,- sliding_window,- alibi_slopes,- max_context_len,- score_aggregation_window};-- const auto op = std::make_shared<op::PagedAttentionExtension>(args);- EXPECT_EQ(op->get_output_element_type(0), element::f32);- EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 4}));-}--TEST(type_prop, paged_attention_static_17_inputs_eviction_per_block) {+TEST(type_prop, paged_attention_static_eviction_per_block) {const auto query = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});const auto key = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});const auto value = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});@@ -67,6 +31,10 @@ TEST(type_prop, paged_attention_static_17_inputs_eviction_per_block) {const auto rotation_deltas = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{12, 1});const auto rotation_trig_lut = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{256, 4});+ const auto xattention_threshold = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{5});+ const auto xattention_block_size = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});+ const auto xattention_stride = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});+ov::OutputVector args = {query,key,value,@@ -83,14 +51,17 @@ TEST(type_prop, paged_attention_static_17_inputs_eviction_per_block) {score_aggregation_window,rotated_block_indices,rotation_deltas,- rotation_trig_lut};+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride};const auto op = std::make_shared<op::PagedAttentionExtension>(args);EXPECT_EQ(op->get_output_element_type(0), element::f32);EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 4}));}-TEST(type_prop, paged_attention_static_17_inputs_eviction_per_token) {+TEST(type_prop, paged_attention_static_eviction_per_token) {const auto query = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});const auto key = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});const auto value = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});@@ -110,6 +81,10 @@ TEST(type_prop, paged_attention_static_17_inputs_eviction_per_token) {const auto rotation_deltas = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{12, 5});const auto rotation_trig_lut = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{256, 4});+ const auto xattention_threshold = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{5});+ const auto xattention_block_size = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});+ const auto xattention_stride = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});+ov::OutputVector args = {query,key,value,@@ -126,7 +101,10 @@ TEST(type_prop, paged_attention_static_17_inputs_eviction_per_token) {score_aggregation_window,rotated_block_indices,rotation_deltas,- rotation_trig_lut};+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride};const auto op = std::make_shared<op::PagedAttentionExtension>(args);EXPECT_EQ(op->get_output_element_type(0), element::f32);@@ -152,6 +130,14 @@ TEST(type_prop, paged_attention_dynamic_ranks_and_types) {const auto max_context_len = std::make_shared<v0::Parameter>(element::dynamic, dyn);const auto score_aggregation_window = std::make_shared<v0::Parameter>(element::dynamic, dyn);+ const auto rotated_block_indices = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);+ const auto rotation_deltas = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);+ const auto rotation_trig_lut = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);++ const auto xattention_threshold = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);+ const auto xattention_block_size = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);+ const auto xattention_stride = std::make_shared<op::v0::Parameter>(element::dynamic, dyn);+ov::OutputVector args = {query,key,value,@@ -165,7 +151,13 @@ TEST(type_prop, paged_attention_dynamic_ranks_and_types) {sliding_window,alibi_slopes,max_context_len,- score_aggregation_window};+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride};EXPECT_NO_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args));}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 723ae9ab2b1..1fea94eacf3 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@@ -1867,6 +1867,9 @@ struct AttentionExecutor : public PagedAttentionExecutor {PlainTensor& rotated_block_indices,PlainTensor& rotation_deltas,PlainTensor& rotation_trig_lut,+ PlainTensor& xattention_threshold,+ int32_t& xattention_block_size,+ int32_t& xattention_stride,PlainTensor& output_emb,PlainTensor& output_score) {q.reset(inputs[ID_Q]); // [B_token, H * S]@@ -1890,19 +1893,23 @@ struct AttentionExecutor : public PagedAttentionExecutor {}size_t inputs_size = inputs.size();- if (inputs_size > ID_ROTATED_BLOCK_INDICES) {- OPENVINO_ASSERT(inputs_size >= ID_ROTATION_TRIG_LUT);- if (!inputs[ID_ROTATED_BLOCK_INDICES]->getShape().hasZeroDims()) {- rotated_block_indices.reset(inputs[ID_ROTATED_BLOCK_INDICES]); // [num_blocks]- }- if (!inputs[ID_ROTATION_DELTAS]->getShape().hasZeroDims()) {- rotation_deltas.reset(inputs[ID_ROTATION_DELTAS]); // [num_blocks, block_size (32) || 1]- }- if (!inputs[ID_ROTATION_TRIG_LUT]->getShape().hasZeroDims()) {- rotation_trig_lut.reset(- inputs[ID_ROTATION_TRIG_LUT]); // [max_context_len * embedding_size], row-major layout- }+ OPENVINO_ASSERT(inputs_size == 20);+ if (!inputs[ID_ROTATED_BLOCK_INDICES]->getShape().hasZeroDims()) {+ rotated_block_indices.reset(inputs[ID_ROTATED_BLOCK_INDICES]); // [num_blocks]+ }+ if (!inputs[ID_ROTATION_DELTAS]->getShape().hasZeroDims()) {+ rotation_deltas.reset(inputs[ID_ROTATION_DELTAS]); // [num_blocks, block_size (32) || 1]+ }+ if (!inputs[ID_ROTATION_TRIG_LUT]->getShape().hasZeroDims()) {+ rotation_trig_lut.reset(+ inputs[ID_ROTATION_TRIG_LUT]); // [max_context_len * embedding_size], row-major layout+ }++ if (!inputs[ID_XATTENTION_THRESHOLD]->getShape().hasZeroDims()) {+ xattention_threshold.reset(inputs[ID_XATTENTION_THRESHOLD]); // [B_seq]}+ xattention_stride = *inputs[ID_XATTENTION_STRIDE]->getDataAs<int32_t>();+ xattention_block_size = *inputs[ID_XATTENTION_BLOCK_SIZE]->getDataAs<int32_t>();output_emb.reset(outputs[0]);if (outputs.size() == 2) {@@ -2038,6 +2045,14 @@ struct AttentionExecutor : public PagedAttentionExecutor {rotation_trig_lut.assert_dims({0, S}, /* special_zero = */ true);init_rotation_coefficient_scratch = true;}+ if (xattention_threshold) {+ xattention_threshold.assert_dims({B_seq});+ OPENVINO_ASSERT(xattention_block_size > 0);+ OPENVINO_ASSERT(xattention_stride > 0);+ // TODO: add assertions on the block size and stride limitations as defined by the+ // block sparse operation and importance score computation impls+ }+output_emb.assert_dims({B_token, H * SV});output_emb = output_emb.reshape({B_token, 1, H * SV});@@ -2123,10 +2138,15 @@ struct AttentionExecutor : public PagedAttentionExecutor {size_t sliding_window = 0;PlainTensor alibi_slopes;size_t max_context_len = 0;+ PlainTensor score_aggregation_window;+PlainTensor rotated_block_indices;PlainTensor rotation_deltas;PlainTensor rotation_trig_lut;- PlainTensor score_aggregation_window;++ PlainTensor xattention_threshold;+ int32_t xattention_block_size = 0;+ int32_t xattention_stride = 0;PlainTensor output_emb;PlainTensor output_score;@@ -2150,6 +2170,9 @@ struct AttentionExecutor : public PagedAttentionExecutor {rotated_block_indices,rotation_deltas,rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride,output_emb,output_score);diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa_common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa_common.hppindex 71791ac7174..456de4cbf6a 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa_common.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa_common.hpp@@ -38,6 +38,9 @@ struct PagedAttentionExecutor {static const size_t ID_ROTATED_BLOCK_INDICES = 14; // [num_rotated_blocks || 0], int32static const size_t ID_ROTATION_DELTAS = 15; // [num_rotated_blocks * block_size || 0], int32static const size_t ID_ROTATION_TRIG_LUT = 16; // [max_context_length * S || 0], f32+ static const size_t ID_XATTENTION_THRESHOLD = 17; // [B_seq, H], f32+ static const size_t ID_XATTENTION_BLOCK_SIZE = 18; // [], int32+ static const size_t ID_XATTENTION_STRIDE = 19; // [], int32virtual void execute(const std::vector<ov::intel_cpu::MemoryPtr>& inputs,std::vector<ov::intel_cpu::MemoryPtr> outputs) = 0;virtual ~PagedAttentionExecutor() = default;diff --git a/src/plugins/intel_cpu/src/nodes/paged_attn.cpp b/src/plugins/intel_cpu/src/nodes/paged_attn.cppindex b2e17fc4544..44a669e3832 100644--- a/src/plugins/intel_cpu/src/nodes/paged_attn.cpp+++ b/src/plugins/intel_cpu/src/nodes/paged_attn.cpp@@ -92,7 +92,7 @@ void PagedAttention::initSupportedPrimitiveDescriptors() {creatorsMap.at(LayoutType::ncsp)->createSharedDesc(rtPrecision, getInputShapeAtPort(PagedAttentionExecutor::ID_V)));- CPU_NODE_ASSERT(any_of(orgInputNumber, 14U, 17U), "The input number of PagedAttention should be 14 or 17.");+ CPU_NODE_ASSERT(orgInputNumber == 20U, "The input number of PagedAttention should be 20.");// kvcache, float, []auto past_key_input_mem_precision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_KCACHE);auto past_value_input_mem_precision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_VCACHE);@@ -145,23 +145,33 @@ void PagedAttention::initSupportedPrimitiveDescriptors() {creatorsMap.at(LayoutType::ncsp)->createSharedDesc(ov::element::i32,getInputShapeAtPort(PagedAttentionExecutor::ID_SCORE_AGGREGATION_WINDOW)));-- if (orgInputNumber == 17) {- // rotated_block_indices, int, [num_rotated_blocks || 0]- config.inConfs[PagedAttentionExecutor::ID_ROTATED_BLOCK_INDICES].setMemDesc(- creatorsMap.at(LayoutType::ncsp)- ->createSharedDesc(ov::element::i32,- getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATED_BLOCK_INDICES)));- // rotation_deltas, int, [num_rotated_blocks, block_size || 1] || [0]- config.inConfs[PagedAttentionExecutor::ID_ROTATION_DELTAS].setMemDesc(- creatorsMap.at(LayoutType::ncsp)- ->createSharedDesc(ov::element::i32, getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATION_DELTAS)));- // rotation_trig_lut, float, [max_context_len, embedding_size (aka S) || 0]- config.inConfs[PagedAttentionExecutor::ID_ROTATION_TRIG_LUT].setMemDesc(- creatorsMap.at(LayoutType::ncsp)- ->createSharedDesc(ov::element::f32,- getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATION_TRIG_LUT)));- }+ // rotated_block_indices, int, [num_rotated_blocks || 0]+ config.inConfs[PagedAttentionExecutor::ID_ROTATED_BLOCK_INDICES].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::i32,+ getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATED_BLOCK_INDICES)));+ // rotation_deltas, int, [num_rotated_blocks, block_size || 1] || [0]+ config.inConfs[PagedAttentionExecutor::ID_ROTATION_DELTAS].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::i32, getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATION_DELTAS)));+ // rotation_trig_lut, float, [max_context_len, embedding_size (aka S) || 0]+ config.inConfs[PagedAttentionExecutor::ID_ROTATION_TRIG_LUT].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::f32, getInputShapeAtPort(PagedAttentionExecutor::ID_ROTATION_TRIG_LUT)));+ // xattention_threshold, float, [B_seq]+ config.inConfs[PagedAttentionExecutor::ID_XATTENTION_THRESHOLD].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::f32, getInputShapeAtPort(PagedAttentionExecutor::ID_XATTENTION_THRESHOLD)));+ // xattention_block_size, float, []+ config.inConfs[PagedAttentionExecutor::ID_XATTENTION_BLOCK_SIZE].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::i32,+ getInputShapeAtPort(PagedAttentionExecutor::ID_XATTENTION_BLOCK_SIZE)));+ // xattention_stride, int, []+ config.inConfs[PagedAttentionExecutor::ID_XATTENTION_STRIDE].setMemDesc(+ creatorsMap.at(LayoutType::ncsp)+ ->createSharedDesc(ov::element::i32,+ getInputShapeAtPort(PagedAttentionExecutor::ID_XATTENTION_BLOCK_SIZE)));supportedPrimitiveDescriptors.emplace_back(config, impl_desc_type::ref_any);}diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cppindex 24192c8f0e3..54abcd67cac 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp@@ -115,6 +115,18 @@ public:std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<float>{128});auto score_aggregation_window =std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto rotated_block_indices =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto rotation_deltas =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto rotation_trig_lut =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});+ auto xattention_threshold =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});+ auto xattention_block_size =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto xattention_stride =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});ParameterVector params ={q, k, v, key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins};auto paged_attn = std::make_shared<op::PagedAttentionExtension>(OutputVector{q,@@ -130,7 +142,13 @@ public:silding_windows,alibi_slopes,max_context_len,- score_aggregation_window});+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});paged_attn->get_rt_info()["num_k_heads"] = head_num;paged_attn->get_rt_info()["k_head_size"] = head_size;paged_attn->get_rt_info()["num_v_heads"] = head_num;diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_score.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_score.cppindex bdd8809cea1..44058d039a2 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_score.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_score.cpp@@ -120,6 +120,18 @@ public:std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<float>{128});auto score_aggregation_window_node =std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<uint32_t>{score_aggregation_window});+ auto rotated_block_indices =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{0}, std::vector<uint32_t>{});+ auto rotation_deltas =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{0}, std::vector<uint32_t>{});+ auto rotation_trig_lut =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});+ auto xattention_threshold =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});+ auto xattention_block_size =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<uint32_t>{0});+ auto xattention_stride =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<uint32_t>{0});ParameterVector params ={q, k, v, key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins};auto paged_attn = std::make_shared<op::PagedAttentionExtension>(OutputVector{q,@@ -135,7 +147,13 @@ public:silding_windows,alibi_slopes,max_context_len,- score_aggregation_window_node});+ score_aggregation_window_node,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride});paged_attn->get_rt_info()["num_k_heads"] = head_num;paged_attn->get_rt_info()["k_head_size"] = head_size;paged_attn->get_rt_info()["num_v_heads"] = head_num;diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hppindex 1c33dcd27f6..d8c417d6119 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp@@ -31,6 +31,9 @@ struct paged_attention : public primitive_base<paged_attention> {ROTATED_BLOCK_INDICES = 14,ROTATION_DELTAS = 15,ROTATION_TRIG_LUT = 16,+ XATTENTION_THRESHOLD = 17,+ XATTENTION_BLOCK_SIZE = 18,+ XATTENTION_STRIDE = 19,};static constexpr size_t block_size = 16;@@ -40,7 +43,7 @@ struct paged_attention : public primitive_base<paged_attention> {paged_attention(const primitive_id& id,const std::vector<input_info>& inputs): primitive_base(id, inputs) {- OPENVINO_ASSERT((inputs.size() == 14) || (inputs.size() == 17),+ OPENVINO_ASSERT((inputs.size() == 20),"[GPU] Unexpected inputs number for PagedAttention primitive: ",inputs.size());}@@ -77,6 +80,7 @@ struct paged_attention : public primitive_base<paged_attention> {ob << has_rotated_blocks;ob << sliding_window;ob << has_score_aggregation;+ ob << has_xattention;if (scale_val.has_value()) {ob << true;@@ -98,6 +102,7 @@ struct paged_attention : public primitive_base<paged_attention> {ib >> has_rotated_blocks;ib >> sliding_window;ib >> has_score_aggregation;+ ib >> has_xattention;bool has_scale;ib >> has_scale;@@ -120,6 +125,7 @@ struct paged_attention : public primitive_base<paged_attention> {bool has_alibi = false;bool has_rotated_blocks = false;bool has_score_aggregation = false;+ bool has_xattention = false;bool is_key_by_channel = false;};} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.hindex af3b1da301c..b635c45d08a 100644--- a/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h+++ b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h@@ -68,6 +68,9 @@ public:memory::ptr rotated_block_indices_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::ROTATED_BLOCK_INDICES); }memory::ptr rotation_deltas_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::ROTATION_DELTAS); }memory::ptr rotation_trig_lut_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::ROTATION_TRIG_LUT); }+ memory::ptr xattention_threshold_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::XATTENTION_THRESHOLD); }+ memory::ptr xattention_block_size_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::XATTENTION_BLOCK_SIZE); }+ memory::ptr xattention_stride_memory_ptr() const { return input_memory_ptr(PagedAttentionInputIdx::XATTENTION_STRIDE); }};using paged_attention_inst = typed_primitive_inst<paged_attention>;diff --git a/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cppindex 113238527dd..61bbb016c65 100644--- a/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp@@ -21,7 +21,7 @@ using PagedAttentionExtension = ov::op::PagedAttentionExtension;namespace ov::intel_gpu {static void CreatePagedAttentionExtensionOp(ProgramBuilder& p, const std::shared_ptr<ov::op::PagedAttentionExtension>& op) {- validate_inputs_count(op, {14, 17});+ validate_inputs_count(op, {20});auto inputs = p.GetInputInfo(op);auto prim = cldnn::paged_attention(layer_type_name_ID(op), inputs);@@ -85,7 +85,19 @@ static void CreatePagedAttentionExtensionOp(ProgramBuilder& p, const std::sharedprim.has_score_aggregation = true;}- prim.has_rotated_blocks = op->get_input_size() > cldnn::paged_attention::PagedAttentionInputIdx::ROTATION_TRIG_LUT;+ const size_t rotated_block_indices_idx = cldnn::paged_attention::PagedAttentionInputIdx::ROTATED_BLOCK_INDICES;+ auto rotated_block_indices_input = ov::as_type_ptr<ov::op::v0::Parameter>(op->get_input_node_shared_ptr(rotated_block_indices_idx));+ if (rotated_block_indices_input && rotated_block_indices_input->get_output_partial_shape(0).is_dynamic()) {+ prim.has_rotated_blocks = true;+ }++ const size_t xattention_threshold_idx = cldnn::paged_attention::PagedAttentionInputIdx::XATTENTION_THRESHOLD;+ auto xattention_threshold_input = ov::as_type_ptr<ov::op::v0::Parameter>(op->get_input_node_shared_ptr(xattention_threshold_idx));+ if (xattention_threshold_input && xattention_threshold_input->get_output_partial_shape(0).is_dynamic()) {+ prim.has_xattention = true;+ }++prim.is_key_by_channel = p.get_config().get_key_cache_quant_mode() == ov::internal::CacheQuantMode::BY_CHANNEL;prim.num_outputs = 1;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 3c1e7f78929..7dcd90baa24 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@@ -138,9 +138,29 @@ TEST(update_shape_test, max_context_len_shapeof_subgraph) {auto sliding_window_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};auto alibi_layout = layout{ov::PartialShape{0}, data_types::f16, format::bfyx};auto max_context_len_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};+auto score_aggregation_window_layout = layout{ov::PartialShape{0}, data_types::i32, format::bfyx};auto score_aggregation_window_mem = engine.allocate_memory(score_aggregation_window_layout);+ auto rotated_block_indices_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};+ auto rotated_block_indices_mem = engine.allocate_memory(rotated_block_indices_layout);++ auto rotation_deltas_layout = layout{ov::PartialShape{1, 1}, data_types::i32, format::bfyx};+ auto rotation_deltas_mem = engine.allocate_memory(rotation_deltas_layout);++ auto rotation_trig_lut_layout = layout{ov::PartialShape{1, 1}, data_types::f32, format::bfyx};+ auto rotation_trig_lut_mem = engine.allocate_memory(rotation_trig_lut_layout);++ auto xattention_threshold_layout = layout{ov::PartialShape{1}, data_types::f32, format::bfyx};+ auto xattention_threshold_mem = engine.allocate_memory(xattention_threshold_layout);++ auto xattention_block_size_layout = layout{ov::PartialShape{}, data_types::i32, format::bfyx};+ auto xattention_block_size_mem = engine.allocate_memory(xattention_block_size_layout);++ auto xattention_stride_layout = layout{ov::PartialShape{}, data_types::i32, format::bfyx};;+ auto xattention_stride_mem = engine.allocate_memory(xattention_stride_layout);++std::vector<input_info> pa_inputs = {input_info("query"),input_info("key"),input_info("value"),@@ -154,7 +174,13 @@ TEST(update_shape_test, max_context_len_shapeof_subgraph) {input_info("sliding_window"),input_info("alibi"),input_info("max_context_len"),- input_info("score_aggregation_window")};+ input_info("score_aggregation_window"),+ input_info("rotated_block_indices"),+ input_info("rotation_deltas"),+ input_info("rotation_trig_lut"),+ input_info("xattention_threshold"),+ input_info("xattention_block_size"),+ input_info("xattention_stride")};auto pa_prim = paged_attention("paged_attention", pa_inputs);pa_prim.k_head_size = 64;@@ -182,6 +208,12 @@ TEST(update_shape_test, max_context_len_shapeof_subgraph) {topology.add(input_layout("alibi", alibi_layout));topology.add(input_layout("max_context_len", max_context_len_layout));topology.add(input_layout("score_aggregation_window", score_aggregation_window_layout));+ topology.add(input_layout("rotated_block_indices", rotated_block_indices_layout));+ topology.add(input_layout("rotation_deltas", rotation_deltas_layout));+ topology.add(input_layout("rotation_trig_lut", rotation_trig_lut_layout));+ topology.add(input_layout("xattention_threshold", xattention_threshold_layout));+ topology.add(input_layout("xattention_block_size", xattention_block_size_layout));+ topology.add(input_layout("xattention_stride", xattention_stride_layout));topology.add(data("const_one", const_one_mem));topology.add(shape_of("shape_of", input_info("input_data"), data_types::i32));topology.add(gather("gather", input_info("shape_of"), input_info("const_one"), 0, 1, ov::Shape{}));@@ -207,6 +239,12 @@ TEST(update_shape_test, max_context_len_shapeof_subgraph) {network.set_input_data("sliding_window", sliding_window_mem);network.set_input_data("alibi", alibi_mem);network.set_input_data("score_aggregation_window", score_aggregation_window_mem);+ network.set_input_data("rotated_block_indices", rotated_block_indices_mem);+ network.set_input_data("rotation_deltas", rotation_deltas_mem);+ network.set_input_data("rotation_trig_lut", rotation_trig_lut_mem);+ network.set_input_data("xattention_threshold", xattention_threshold_mem);+ network.set_input_data("xattention_block_size", xattention_block_size_mem);+ network.set_input_data("xattention_stride", xattention_stride_mem);// Set original max_context_len valueauto max_context_len_mem_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};@@ -239,6 +277,12 @@ TEST(update_shape_test, max_context_len_shapeof_subgraph) {network.set_input_data("sliding_window", sliding_window_mem);network.set_input_data("alibi", alibi_mem);network.set_input_data("score_aggregation_window", score_aggregation_window_mem);+ network.set_input_data("rotated_block_indices", rotated_block_indices_mem);+ network.set_input_data("rotation_deltas", rotation_deltas_mem);+ network.set_input_data("rotation_trig_lut", rotation_trig_lut_mem);+ network.set_input_data("xattention_threshold", xattention_threshold_mem);+ network.set_input_data("xattention_block_size", xattention_block_size_mem);+ network.set_input_data("xattention_stride", xattention_stride_mem);// Update max_context_len value, which should be taken into account in shape recalculation for broadcastset_values(max_context_len_mem, {8});diff --git a/src/plugins/intel_gpu/tests/unit/passes/mark_shape_of_subgraphs_test.cpp b/src/plugins/intel_gpu/tests/unit/passes/mark_shape_of_subgraphs_test.cppindex e60566dd520..e04cb8545cd 100644--- a/src/plugins/intel_gpu/tests/unit/passes/mark_shape_of_subgraphs_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/passes/mark_shape_of_subgraphs_test.cpp@@ -456,8 +456,14 @@ TEST(mark_shape_of_subgraphs, paged_attention_max_context_len_input) {auto scale_layout = layout{ov::PartialShape{1}, data_types::f32, format::bfyx};auto sliding_window_layout = layout{ov::PartialShape{}, data_types::i32, format::bfyx};auto alibi_layout = layout{ov::PartialShape{}, data_types::f32, format::bfyx};- auto max_context_len_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};;+ auto max_context_len_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};auto score_aggregation_window_layout = dynamic_i32_layout;+ auto rotated_block_indices_layout = layout{ov::PartialShape{1}, data_types::i32, format::bfyx};+ auto rotation_deltas_layout = layout{ov::PartialShape{1, 1}, data_types::i32, format::bfyx};+ auto rotation_trig_lut_layout = layout{ov::PartialShape{1, 1}, data_types::f32, format::bfyx};+ auto xattention_threshold_layout = layout{ov::PartialShape{1}, data_types::f32, format::bfyx};+ auto xattention_block_size_layout = layout{ov::PartialShape{}, data_types::i32, format::bfyx};+ auto xattention_stride_layout = layout{ov::PartialShape{}, data_types::i32, format::bfyx};;std::vector<input_info> pa_inputs = {input_info("query"),input_info("key"),@@ -472,7 +478,14 @@ TEST(mark_shape_of_subgraphs, paged_attention_max_context_len_input) {input_info("sliding_window"),input_info("alibi"),input_info("max_context_len"),- input_info("score_aggregation_window")};+ input_info("score_aggregation_window"),+ input_info("rotated_block_indices"),+ input_info("rotation_deltas"),+ input_info("rotation_trig_lut"),+ input_info("xattention_threshold"),+ input_info("xattention_block_size"),+ input_info("xattention_stride"),+ };auto pa_prim = paged_attention("paged_attention", pa_inputs);pa_prim.k_head_size = 64;@@ -499,6 +512,12 @@ TEST(mark_shape_of_subgraphs, paged_attention_max_context_len_input) {topology.add(input_layout("alibi", alibi_layout));topology.add(input_layout("max_context_len", max_context_len_layout));topology.add(input_layout("score_aggregation_window", score_aggregation_window_layout));+ topology.add(input_layout("rotated_block_indices", rotated_block_indices_layout));+ topology.add(input_layout("rotation_deltas", rotation_deltas_layout));+ topology.add(input_layout("rotation_trig_lut", rotation_trig_lut_layout));+ topology.add(input_layout("xattention_threshold", xattention_threshold_layout));+ topology.add(input_layout("xattention_block_size", xattention_block_size_layout));+ topology.add(input_layout("xattention_stride", xattention_stride_layout));topology.add(input_layout("input", input_layout_dynamic));topology.add(data("target_shape", target_shape));topology.add(data("subtract_one", subtract_one));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.cppindex 933da9f8d04..3675d481b93 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@@ -106,6 +106,10 @@ struct PagedAttentionManager {std::vector<int> rotation_deltas;std::vector<ov::float16> rotation_trig_lut;+ std::vector<ov::float16> xattention_threshold;+ std::vector<int> xattention_block_size;+ std::vector<int> xattention_stride;+cldnn::engine& test_engine;cldnn::stream& test_stream;tests::random_generator& rg;@@ -436,6 +440,28 @@ struct PagedAttentionManager {return test_engine.reinterpret_buffer(*mem, layout);}+ memory::ptr get_xattention_threshold_memory() {+ auto mem = get_memory_from_vec(xattention_threshold);+ auto layout = mem->get_layout();+ layout.set_partial_shape(ov::PartialShape{ 1 });++ if (xattention_threshold.empty()) {+ auto empty_layout = mem->get_layout();+ empty_layout.set_partial_shape(ov::PartialShape{ 0 });+ return test_engine.reinterpret_buffer(*mem, empty_layout);+ }++ return test_engine.reinterpret_buffer(*mem, layout);+ }++ memory::ptr get_xattention_block_size_memory() {+ return get_memory_from_vec(xattention_block_size);+ }++ memory::ptr get_xattention_stride_memory() {+ return get_memory_from_vec(xattention_stride);+ }+float get_default_scale() {return static_cast<float>(1.f / std::sqrt(k_head_size));}@@ -911,6 +937,10 @@ public:auto rotation_deltas_mem = pam.get_rotation_deltas_memory();auto rotation_trig_lut_mem = pam.get_rotation_trig_lut_memory();+ auto xattention_threshold_mem = pam.get_xattention_threshold_memory();+ auto xattention_block_size_mem = pam.get_xattention_block_size_memory();+ auto xattention_stride_mem = pam.get_xattention_stride_memory();+auto query_layout = query_mem->get_layout();auto key_layout = key_mem->get_layout();auto value_layout = value_mem->get_layout();@@ -928,6 +958,9 @@ public:auto rotated_block_indices_layout = rotated_block_indices_mem->get_layout();auto rotation_deltas_layout = rotation_deltas_mem->get_layout();auto rotation_trig_lut_layout = rotation_trig_lut_mem->get_layout();+ auto xattention_threshold_layout = xattention_threshold_mem->get_layout();+ auto xattention_block_size_layout = xattention_block_size_mem->get_layout();+ auto xattention_stride_layout = xattention_stride_mem->get_layout();// make layouts dynamicquery_layout.set_partial_shape(ov::PartialShape{ -1, p.num_heads * p.k_head_size });@@ -943,6 +976,7 @@ public:rotated_block_indices_layout.set_partial_shape(ov::PartialShape{ -1 });rotation_deltas_layout.set_partial_shape(ov::PartialShape{ -1, -1 });rotation_trig_lut_layout.set_partial_shape(ov::PartialShape{ -1, p.k_head_size });+ xattention_threshold_layout.set_partial_shape(ov::PartialShape{ -1 });if (p.dynamic_paddings) {const auto padding_axis = 1;@@ -989,13 +1023,14 @@ public:input_info("sliding_window"),input_info("alibi"),input_info("max_context_len"),- input_info("score_aggregation_window") };-- if (p.rotation_config.apply_rotation) {- pa_inputs.push_back(input_info("rotated_block_indices"));- pa_inputs.push_back(input_info("rotation_deltas"));- pa_inputs.push_back(input_info("rotation_trig_lut_modified"));- }+ input_info("score_aggregation_window"),+ input_info("rotated_block_indices"),+ input_info("rotation_deltas"),+ input_info("rotation_trig_lut_modified"),+ input_info("xattention_threshold"),+ input_info("xattention_block_size"),+ input_info("xattention_stride"),+ };auto pa_prim = paged_attention("paged_attention", pa_inputs);@@ -1036,13 +1071,17 @@ public:topology.add(reorder("output_scores", input_info("paged_attention", 1), format::bfyx, data_types::f16));}- if (p.rotation_config.apply_rotation) {+ {topology.add(input_layout("rotated_block_indices", rotated_block_indices_layout));topology.add(input_layout("rotation_deltas", rotation_deltas_layout));topology.add(input_layout("rotation_trig_lut", rotation_trig_lut_layout));// add dummy activation operation to simulate an empty PA `rotation_trig_lut` buffer for shapes like [0, k_head_size]topology.add(activation("rotation_trig_lut_modified", input_info("rotation_trig_lut"), activation_func::none));++ topology.add(input_layout("xattention_threshold", xattention_threshold_layout));+ topology.add(input_layout("xattention_block_size", xattention_block_size_layout));+ topology.add(input_layout("xattention_stride", xattention_stride_layout));}ExecutionConfig config = get_test_default_config(get_test_engine());@@ -1066,12 +1105,13 @@ public:network->set_input_data("alibi", alibi_mem);network->set_input_data("max_context_len", max_context_len_mem);network->set_input_data("score_aggregation_window", score_aggregation_mem);+ network->set_input_data("rotated_block_indices", rotated_block_indices_mem);+ network->set_input_data("rotation_deltas", rotation_deltas_mem);+ network->set_input_data("rotation_trig_lut", rotation_trig_lut_mem);+ network->set_input_data("xattention_threshold", xattention_threshold_mem);+ network->set_input_data("xattention_block_size", xattention_block_size_mem);+ network->set_input_data("xattention_stride", xattention_stride_mem);- if (p.rotation_config.apply_rotation) {- network->set_input_data("rotated_block_indices", rotated_block_indices_mem);- network->set_input_data("rotation_deltas", rotation_deltas_mem);- network->set_input_data("rotation_trig_lut", rotation_trig_lut_mem);- }auto outputs = network->execute();cldnn::memory::ptr output_data_mem = nullptr;diff --git a/tests/model_hub_tests/transformation_tests/generate_ref_diffs.py b/tests/model_hub_tests/transformation_tests/generate_ref_diffs.pyindex 2912b2a961a..055f55af44e 100644--- a/tests/model_hub_tests/transformation_tests/generate_ref_diffs.py+++ b/tests/model_hub_tests/transformation_tests/generate_ref_diffs.py@@ -5,7 +5,7 @@Use this script if you need to regenerate reference diffs for each modelto test SDPAToPA transformation.-The script will produce sdpa2pa_ref_diff.txt (or sdpa2pa_ref_diff_cache_eviction.txt+The script will produce sdpa2pa_ref_diff.txt (or sdpa2pa_ref_diff_optimizations.txtif using cache-eviction) containing a map in thefollowing format with nodes number changes for each model:@@ -74,11 +74,11 @@ def get_models_list_type(file_name: str, cls: Union[type[OVModelForCausalLM], tyreturn modelsdef main():- use_cache_eviction = False+ use_optimizations = Falseif len(sys.argv) >= 2:- use_cache_eviction = sys.argv[1].lower() in 'true'+ use_optimizations = sys.argv[1].lower() in 'true'- OUTPUT_FILE = Path(os.path.join(os.path.dirname(__file__)), 'sdpa2pa_ref_diff' + ('_cache_eviction.txt' if use_cache_eviction else '.txt'))+ OUTPUT_FILE = Path(os.path.join(os.path.dirname(__file__)), 'sdpa2pa_ref_diff' + ('_optimizations.txt' if use_optimizations else '.txt'))if OUTPUT_FILE.exists() and OUTPUT_FILE.is_file():OUTPUT_FILE.unlink()@@ -87,7 +87,7 @@ def main():model_list = get_models_list_type(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-models-precommit"), OVModelForCausalLM)model_list.extend(get_models_list_type(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-vl-models-precommit"), OVModelForVisualCausalLM))print(OUTPUT_FILE)- print('ref_diff_map_cache_eviction = {' if use_cache_eviction else 'ref_diff_map = {', file=file)+ print('ref_diff_map_optimizations = {' if use_optimizations else 'ref_diff_map = {', file=file)for model_id, _, _, _, cls in model_list:# wrapping in try/catch block to continue printing models even if one has failed@@ -106,7 +106,7 @@ def main():# wrapping in try/catch block to continue printing models even if one has failedtry:- paged_attention_transformation(ov_model, use_block_indices_inputs=use_cache_eviction, use_score_outputs=use_cache_eviction, allow_score_aggregation=use_cache_eviction, allow_cache_rotation=use_cache_eviction)+ paged_attention_transformation(ov_model, use_block_indices_inputs=use_optimizations, use_score_outputs=use_optimizations, allow_score_aggregation=use_optimizations, allow_cache_rotation=use_optimizations, allow_xattention=use_optimizations)except:print(f"Couldn't run SDPAToPA transformation on {model_id} and generate diffs.")continuediff --git a/tests/model_hub_tests/transformation_tests/sdpa2pa_ref_diff.py b/tests/model_hub_tests/transformation_tests/sdpa2pa_ref_diff.pyindex 66f7cab6c6a..4aafe7a610a 100644--- a/tests/model_hub_tests/transformation_tests/sdpa2pa_ref_diff.py+++ b/tests/model_hub_tests/transformation_tests/sdpa2pa_ref_diff.py@@ -335,333 +335,333 @@ ref_diff_map = {}}-ref_diff_map_cache_eviction = {+ref_diff_map_optimizations = {"hf-internal-testing/tiny-random-LlamaForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-CohereForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-GPTJForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-GPTNeoForCausalLM" : {"Assign" : -8,"PagedAttentionExtension" : 4,- "Parameter" : 24,+ "Parameter" : 30,"ReadValue" : -8,"ScaledDotProductAttention" : -4,},"hf-internal-testing/tiny-random-GPTNeoXForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-MistralForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-CodeGenForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/Mixtral-tiny" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-GPTBigCodeForCausalLM" : {"Assign" : -5,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -5,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-Starcoder2ForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-BloomForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 30,+ "Parameter" : 37,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-gpt2" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-BlenderbotForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 15,+ "Parameter" : 19,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-PegasusForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 15,+ "Parameter" : 19,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-PhiForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-MptForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 30,+ "Parameter" : 37,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"hf-internal-testing/tiny-random-StableLmForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-PersimmonForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-internal-testing/tiny-random-FalconForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"hf-tiny-model-private/tiny-random-OPTForCausalLM" : {"Assign" : -10,"PagedAttentionExtension" : 5,- "Parameter" : 29,+ "Parameter" : 36,"ReadValue" : -10,"ScaledDotProductAttention" : -5,},"katuni4ka/tiny-random-xverse" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-baichuan2-13b" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-qwen" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-aquilachat" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-aquila2" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-qwen1.5-moe" : {"Assign" : -8,"PagedAttentionExtension" : 4,- "Parameter" : 24,+ "Parameter" : 30,"ReadValue" : -8,"ScaledDotProductAttention" : -4,},"katuni4ka/tiny-random-codegen2" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-olmo-hf" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-baichuan2" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-jais" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-internlm" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-internlm2" : {"Assign" : -8,"PagedAttentionExtension" : 4,- "Parameter" : 24,+ "Parameter" : 30,"ReadValue" : -8,"ScaledDotProductAttention" : -4,},"katuni4ka/tiny-random-minicpm" : {"Assign" : -8,"PagedAttentionExtension" : 4,- "Parameter" : 24,+ "Parameter" : 30,"ReadValue" : -8,"ScaledDotProductAttention" : -4,},"katuni4ka/tiny-random-falcon-40b" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-dbrx" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"fxmarty/tiny-random-GemmaForCausalLM" : {"Assign" : -2,"PagedAttentionExtension" : 1,- "Parameter" : 9,+ "Parameter" : 12,"ReadValue" : -2,"ScaledDotProductAttention" : -1,},"fxmarty/tiny-dummy-qwen2" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"fxmarty/really-tiny-falcon-testing" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"Xenova/tiny-random-Phi3ForCausalLM" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"facebook/opt-125m" : {"Assign" : -24,"PagedAttentionExtension" : 12,- "Parameter" : 64,+ "Parameter" : 78,"ReadValue" : -24,"ScaledDotProductAttention" : -12,},"facebook/opt-350m" : {"Assign" : -48,"PagedAttentionExtension" : 24,- "Parameter" : 124,+ "Parameter" : 150,"ReadValue" : -48,"ScaledDotProductAttention" : -24,},"katuni4ka/tiny-random-chatglm2" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-glm4" : {"Assign" : -12,"PagedAttentionExtension" : 6,- "Parameter" : 34,+ "Parameter" : 42,"ReadValue" : -12,"ScaledDotProductAttention" : -6,},"katuni4ka/tiny-random-llava-next" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-minicpmv-2_6" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-llava" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},"katuni4ka/tiny-random-nanollava" : {"Assign" : -4,"PagedAttentionExtension" : 2,- "Parameter" : 14,+ "Parameter" : 18,"ReadValue" : -4,"ScaledDotProductAttention" : -2,},diff --git a/tests/model_hub_tests/transformation_tests/test_pa_transformation.py b/tests/model_hub_tests/transformation_tests/test_pa_transformation.pyindex ce6f9be75f1..39a82342885 100644--- a/tests/model_hub_tests/transformation_tests/test_pa_transformation.py+++ b/tests/model_hub_tests/transformation_tests/test_pa_transformation.py@@ -9,7 +9,7 @@ from typing import Unionimport openvino as ovfrom models_hub_common.utils import retryimport models_hub_common.utils as utils-from sdpa2pa_ref_diff import ref_diff_map, ref_diff_map_cache_eviction, nodes_to_compare+from sdpa2pa_ref_diff import ref_diff_map, ref_diff_map_optimizations, nodes_to_compareimport pytestimport osimport re@@ -20,13 +20,14 @@ def apply_transformation_and_compare_diffs(ov_model: ov.Model,use_score_outputs: bool,allow_score_aggregation: bool,allow_cache_rotation: bool,+ allow_xattention: bool,ie_device: str):before_map = {}for op in ov_model.get_ordered_ops():if op.get_type_name() in nodes_to_compare:before_map[op.get_type_name()] = before_map.get(op.get_type_name(), 0) + 1- paged_attention_transformation(ov_model, use_block_indices_inputs, use_score_outputs, allow_score_aggregation, allow_cache_rotation)+ paged_attention_transformation(ov_model, use_block_indices_inputs, use_score_outputs, allow_score_aggregation, allow_cache_rotation, allow_xattention)ov.Core().compile_model(ov_model, ie_device)after_map = {}@@ -41,7 +42,7 @@ def apply_transformation_and_compare_diffs(ov_model: ov.Model,resulting_map[op] = after_map.get(op, 0) - before_map.get(op, 0)use_cache_eviction = use_block_indices_inputs and use_score_outputs and allow_cache_rotation- reference_map = ref_diff_map_cache_eviction[model_id] if use_cache_eviction else ref_diff_map[model_id]+ reference_map = ref_diff_map_optimizations[model_id] if use_cache_eviction else ref_diff_map[model_id]assert reference_map == resulting_map@@ -74,6 +75,11 @@ def apply_transformation_and_compare_diffs(ov_model: ov.Model,interesting_input_patterns["rotation_deltas"] = r'^rotation_deltas\.[0-9]+';interesting_input_patterns["rotation_trig_lut"] = r'rotation_trig_lut';+ if (allow_xattention):+ interesting_input_patterns["xattention_threshold"] = r'^xattention_threshold\.[0-9]+';+ interesting_input_patterns["xattention_block_size"] = r'^xattention_block_size$';+ interesting_input_patterns["xattention_stride"] = r'^xattention_stride$';+input_counters = {k: 0 for k in interesting_input_patterns}output_counters = {k: 0 for k in interesting_output_patterns}@@ -95,6 +101,12 @@ def apply_transformation_and_compare_diffs(ov_model: ov.Model,assert input_counters["score_aggregation_window"] == 1input_counters.pop("score_aggregation_window")+ if allow_xattention:+ assert input_counters["xattention_block_size"] == 1+ input_counters.pop("xattention_block_size")+ assert input_counters["xattention_stride"] == 1+ input_counters.pop("xattention_stride")+for input_id, count in input_counters.items():assert count == resulting_map["PagedAttentionExtension"], \f"The number of {input_id} inputs doesn't correspond to the expected value. Expected {resulting_map['PagedAttentionExtension']}, received {count}"@@ -113,52 +125,51 @@ def run_pa(tmp_path,use_score_outputs,allow_score_aggregation,allow_cache_rotation,+ allow_xattention,ie_device):model = cls.from_pretrained(model_id, export=True, trust_remote_code=True)ov_model = model.model if cls is OVModelForCausalLM else model.lm_model- apply_transformation_and_compare_diffs(ov_model, model_id, use_block_indices_inputs, use_score_outputs, allow_score_aggregation, allow_cache_rotation, ie_device)+ apply_transformation_and_compare_diffs(ov_model, model_id, use_block_indices_inputs, use_score_outputs, allow_score_aggregation, allow_cache_rotation, allow_xattention, ie_device)[email protected]("model_name, model_link, mark, reason", utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-models-precommit")))-def test_pa_precommit(tmp_path, model_name, model_link, mark, reason, ie_device):- assert mark is None or mark == 'skip' or mark == 'xfail', \- "Incorrect test case: {}, {}".format(model_name, model_link)- if mark == 'skip':- pytest.skip(reason)- elif mark == 'xfail':- pytest.xfail(reason)- run_pa(tmp_path, model_name, model_link, OVModelForCausalLM, False, False, False, False, ie_device)+PA_PRECOMMIT_TEST_CASES = [ (OVModelForCausalLM, *model_info_tuple) for model_info_tuple in utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-models-precommit")) ] + [ (OVModelForVisualCausalLM, *model_info_tuple) for model_info_tuple in utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-vl-models-precommit")) ][email protected]("model_name, model_link, mark, reason", utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-models-precommit")))-def test_pa_precommit_use_cache_eviction(tmp_path, model_name, model_link, mark, reason, ie_device):- assert mark is None or mark == 'skip' or mark == 'xfail', \- "Incorrect test case: {}, {}".format(model_name, model_link)- if mark == 'skip':- pytest.skip(reason)- elif mark == 'xfail':- pytest.xfail(reason)- run_pa(tmp_path, model_name, model_link, OVModelForCausalLM, True, True, True, True, ie_device)+def pa_test_idfn(entry):+ retval = ""+ if entry[0] is OVModelForCausalLM:+ retval += "text-"+ elif entry[0] is OVModelForVisualCausalLM:+ retval += "vlm-"+ else:+ raise ValueError(f"Unknown model class {entry[0]}")+ retval += entry[1]+ return retval[email protected]("model_name, model_link, mark, reason", utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-vl-models-precommit")))-def test_pa_vlm(tmp_path, model_name, model_link, mark, reason, ie_device):- assert mark is None or mark == 'skip' or mark == 'xfail', \- "Incorrect test case: {}, {}".format(model_name, model_link)- if mark == 'skip':- pytest.skip(reason)- elif mark == 'xfail':- pytest.xfail(reason)- run_pa(tmp_path, model_name, model_link, OVModelForVisualCausalLM, False, False, False, False, ie_device)@pytest.mark.precommit[email protected]("model_name, model_link, mark, reason", utils.get_models_list(os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-vl-models-precommit")))-def test_pa_vlm_use_cache_eviction(tmp_path, model_name, model_link, mark, reason, ie_device):[email protected]("model_info_tuple", PA_PRECOMMIT_TEST_CASES, ids=pa_test_idfn)[email protected]("use_optimizations", [False, True], ids=["no_opt", "with_opt"])+def test_pa_precommit(tmp_path, model_info_tuple, ie_device, use_optimizations):+ model_class, model_name, model_link, mark, reason = model_info_tupleassert mark is None or mark == 'skip' or mark == 'xfail', \"Incorrect test case: {}, {}".format(model_name, model_link)if mark == 'skip':pytest.skip(reason)elif mark == 'xfail':pytest.xfail(reason)- run_pa(tmp_path, model_name, model_link, OVModelForVisualCausalLM, True, True, True, True, ie_device)+ if use_optimizations:+ run_pa(tmp_path, model_name, model_link, model_class,+ use_block_indices_inputs=True,+ use_score_outputs=True,+ allow_score_aggregation=True,+ allow_cache_rotation=True,+ allow_xattention=True,+ ie_device=ie_device)+ else:+ run_pa(tmp_path, model_name, model_link, model_class,+ use_block_indices_inputs=False,+ use_score_outputs=False,+ allow_score_aggregation=False,+ allow_cache_rotation=False,+ allow_xattention=False,+ ie_device=ie_device)