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
[LPT] FP8 KV-Cache Static Quantization (#31557)
Vladislav Golubev5ce28dcf83fd
diff --git a/src/common/low_precision_transformations/include/low_precision/kv_cache_concat.hpp b/src/common/low_precision_transformations/include/low_precision/kv_cache_concat.hppnew file mode 100644index 00000000000..dab745a6e43--- /dev/null+++ b/src/common/low_precision_transformations/include/low_precision/kv_cache_concat.hpp@@ -0,0 +1,33 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <algorithm>+#include <functional>+#include <memory>+#include <string>+#include <vector>++#include "lpt_visibility.hpp"+#include "openvino/pass/matcher_pass.hpp"++namespace ov::pass::low_precision {+/**+ * @brief Optimizes stateful KV cache by eliminating quantization-dequantization pairs on ReadValue-Assign paths.+ *+ * This transformation identifies KV concatenation patterns where both cache and new KV data+ * undergo identical quantization (downconvert) followed by dequantization (upconvert). It optimizes+ * the pattern by:+ * 1. Storing the cache variable in low precision fp8 format+ * 2. Removing downconvert subgraphs from the cache branch+ * 3. Connecting the Assign operation directly to the low-precision concat output (so upconvert subgraph is also removed)+ */+class LP_TRANSFORMATIONS_API KVCacheConcat : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("KVCacheConcat");+ KVCacheConcat(const std::shared_ptr<ov::Model>& model);+};++} // namespace ov::pass::low_precisiondiff --git a/src/common/low_precision_transformations/include/low_precision/move_fake_convert_up_through_kv_cache_concat.hpp b/src/common/low_precision_transformations/include/low_precision/move_fake_convert_up_through_kv_cache_concat.hppnew file mode 100644index 00000000000..af1579e6343--- /dev/null+++ b/src/common/low_precision_transformations/include/low_precision/move_fake_convert_up_through_kv_cache_concat.hpp@@ -0,0 +1,27 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "lpt_visibility.hpp"+#include "openvino/core/model.hpp"+#include "openvino/pass/matcher_pass.hpp"++namespace ov::pass::low_precision {+/**+ * @brief Moves FakeConvert operations from after concat to before concat in KV cache patterns.+ *+ * This transformation is a prerequisite for KV cache quantization optimization. It identifies+ * patterns where FakeConvert operations are applied to the output of KV cache concatenation+ * and moves them to the individual concat inputs instead.+ */+class LP_TRANSFORMATIONS_API MoveFakeConvertUpThroughKVCacheConcat : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("MoveFakeConvertUpThroughKVCacheConcat");+ MoveFakeConvertUpThroughKVCacheConcat();+};++} // namespace ov::pass::low_precisiondiff --git a/src/common/low_precision_transformations/src/kv_cache_concat.cpp b/src/common/low_precision_transformations/src/kv_cache_concat.cppnew file mode 100644index 00000000000..5a40226a3e3--- /dev/null+++ b/src/common/low_precision_transformations/src/kv_cache_concat.cpp@@ -0,0 +1,165 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "low_precision/kv_cache_concat.hpp"++#include <algorithm>+#include <memory>+#include <string>+#include <vector>++#include "itt.hpp"+#include "low_precision/network_helper.hpp"+#include "openvino/op/assign.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/equal.hpp"+#include "openvino/op/fake_convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/read_value.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"++namespace ov::pass::low_precision {+using namespace ov;++KVCacheConcat::KVCacheConcat(const std::shared_ptr<Model>& model) {+ MATCHER_SCOPE(KVCacheConcat);+ using namespace ov::pass::pattern;+ using namespace ov::op;++ auto read_value_m = wrap_type<v6::ReadValue>({});+ auto gather_m = wrap_type<v8::Gather>({read_value_m, any_input(), any_input()});++ auto match_downconvert_subgraph = [](const Output<Node>& input) {+ auto scale = wrap_type<v0::Constant>(rank_equals(0));+ auto mul = wrap_type<v1::Multiply>({input, scale});++ auto shift = wrap_type<v0::Constant>(rank_equals(0));+ auto sub = optional<v1::Subtract>({mul, shift});++ auto clamp = wrap_type<v0::Clamp>({sub});+ auto downconvert = wrap_type<v0::Convert>({clamp}, type_matches_any({element::f8e4m3, element::f8e5m2}));+ return std::make_tuple(scale, shift, downconvert);+ };++ auto cache_patterns = match_downconvert_subgraph(gather_m);+ auto down_scale_cache = std::get<0>(cache_patterns);+ auto down_shift_cache = std::get<1>(cache_patterns);+ auto downconvert_cache = std::get<2>(cache_patterns);++ auto kv_patterns = match_downconvert_subgraph(any_input());+ auto down_scale_kv = std::get<0>(kv_patterns);+ auto down_shift_kv = std::get<1>(kv_patterns);+ auto downconvert_kv = std::get<2>(kv_patterns);+ auto kv_concat = wrap_type<v0::Concat>({downconvert_cache, downconvert_kv});++ auto upconvert = wrap_type<v0::Convert>({kv_concat});+ auto up_shift = wrap_type<v0::Constant>();+ auto up_sub = optional<v1::Subtract>({upconvert, up_shift});+ auto up_scale = wrap_type<v0::Constant>();+ auto up_mul = wrap_type<v1::Multiply>({up_sub, up_scale});++ auto kv_assign = wrap_type<v6::Assign>({up_mul});++ graph_rewrite_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {+ if (transformation_callback(m.get_match_root())) {+ return false;+ }+ const auto& pattern_map = m.get_pattern_value_map();+ auto check_dequantization_pairs = [&pattern_map](const std::shared_ptr<Node>& const_cache,+ const std::shared_ptr<Node>& const_kv) {+ if (pattern_map.count(const_cache) != pattern_map.count(const_kv)) {+ return false;+ }+ if (pattern_map.count(const_cache) == 0) {+ return true;+ }+ const auto cache_node = pattern_map.at(const_cache).get_node_shared_ptr();+ const auto kv_node = pattern_map.at(const_kv).get_node_shared_ptr();+ const auto equal_node = ov::as_type_ptr<v0::Constant>(fold<v1::Equal>(cache_node, kv_node));+ OPENVINO_ASSERT(equal_node != nullptr, "Downconvert scaleshift must be constant.");+ const auto equal_res = equal_node->get_vector<bool>();+ // Note: the optimization can be applied only if quantization scales and shifts on both+ // concat branches are equal.+ return std::all_of(equal_res.begin(), equal_res.end(), [](bool x) {+ return x;+ });+ };++ if (!check_dequantization_pairs(down_scale_cache, down_scale_kv) ||+ !check_dequantization_pairs(down_shift_cache, down_shift_kv)) {+ return false;+ }+ const auto assign = ov::as_type_ptr<v6::Assign>(pattern_map.at(kv_assign).get_node_shared_ptr());+ const auto read_value = ov::as_type_ptr<v6::ReadValue>(pattern_map.at(read_value_m).get_node_shared_ptr());+ OPENVINO_ASSERT(assign != nullptr && read_value != nullptr, "Assign node must be found in the pattern map.");+ if (assign->get_control_dependencies().size() != 1 || assign->get_control_dependencies()[0] != read_value) {+ return false;+ }++ // Note: this dependency must be removed before read value update.+ assign->remove_control_dependency(read_value);+ const auto original_var = read_value->get_variable();+ const auto var_info = original_var->get_info();+ const auto& down_convert_prc = pattern_map.at(downconvert_cache).get_element_type();+ // set new precision for original_var to update precision in new read value+ original_var->update({var_info.data_shape, down_convert_prc, var_info.variable_id});+ const auto read_value_convert = std::make_shared<v0::Convert>(read_value->input_value(0), down_convert_prc);+ const auto new_read_value = read_value->copy_with_new_inputs({read_value_convert});+ OPENVINO_ASSERT(replace_node_update_name(read_value, new_read_value), "Failed to update ReadValue node.");+ copy_runtime_info(read_value, read_value_convert);++ // Manual gather validation is called in order to propagate low precision through it+ const auto gather_node = pattern_map.at(gather_m).get_node_shared_ptr();+ gather_node->validate_and_infer_types();++ auto build_reverse_fake_convert = [&](ov::Output<ov::Node> input) {+ auto clone_constant = [&](const std::shared_ptr<Node>& node) {+ return pattern_map.at(node).get_node_shared_ptr()->clone_with_new_inputs({});+ };++ auto upconvert_node = pattern_map.at(upconvert).get_node_shared_ptr()->clone_with_new_inputs({input});+ std::shared_ptr<ov::Node> up_sub_node = upconvert_node;+ if (pattern_map.count(up_shift)) {+ up_sub_node = std::make_shared<v1::Subtract>(upconvert_node, clone_constant(up_shift));+ }+ auto up_mul_node = std::make_shared<v1::Multiply>(up_sub_node, clone_constant(up_scale));+ auto down_mul_node = std::make_shared<v1::Multiply>(up_mul_node, clone_constant(down_scale_cache));+ std::shared_ptr<ov::Node> down_sub_node = down_mul_node;+ if (pattern_map.count(down_shift_cache)) {+ down_sub_node = std::make_shared<v1::Subtract>(down_mul_node, clone_constant(down_shift_cache));+ }+ auto downconvert_node =+ pattern_map.at(downconvert_cache).get_node_shared_ptr()->clone_with_new_inputs({down_sub_node});+ copy_runtime_info(+ input.get_node_shared_ptr(),+ {upconvert_node, up_sub_node, up_mul_node, down_mul_node, down_sub_node, downconvert_node});+ return downconvert_node;+ };++ // Note: we create "reverse" fake convert here (low precision on input-output, high precision (e.g. f32) inside)+ // in order to keep quantization parameters on concat inputs and output+ auto reverse_fc_before_concat = build_reverse_fake_convert(gather_node);+ auto reverse_fc_after_concat = build_reverse_fake_convert(pattern_map.at(kv_concat));+ OPENVINO_ASSERT(replace_output_update_name(pattern_map.at(downconvert_cache), reverse_fc_before_concat),+ "Failed to replace downconvert subgraph from kv cache branch.");++ // Assign is reconnected to the reverse fake convert output+ const auto new_assign = assign->copy_with_new_inputs({reverse_fc_after_concat});+ model->remove_sink(as_type_ptr<Sink>(assign));+ model->add_sinks({as_type_ptr<Sink>(new_assign)});++ OPENVINO_ASSERT(replace_node_update_name(assign, new_assign), "Failed to update Assign node.");+ new_assign->add_control_dependency(new_read_value);+ return true;+ };++ auto matcher = std::make_shared<Matcher>(kv_assign, matcher_name);++ register_matcher(matcher, callback);+}+} // namespace ov::pass::low_precisiondiff --git a/src/common/low_precision_transformations/src/move_fake_convert_up_through_kv_cache_concat.cpp b/src/common/low_precision_transformations/src/move_fake_convert_up_through_kv_cache_concat.cppnew file mode 100644index 00000000000..83ed76db1d6--- /dev/null+++ b/src/common/low_precision_transformations/src/move_fake_convert_up_through_kv_cache_concat.cpp@@ -0,0 +1,108 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "low_precision/move_fake_convert_up_through_kv_cache_concat.hpp"++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/op/assign.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/fake_convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/read_value.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::pass::low_precision {+MoveFakeConvertUpThroughKVCacheConcat::MoveFakeConvertUpThroughKVCacheConcat() {+ MATCHER_SCOPE(MoveFakeConvertUpThroughKVCacheConcat);+ using namespace ov::pass::pattern;++ auto match_kv_cache = []() {+ auto past_k = wrap_type<ov::op::v6::ReadValue>({});+ auto convert_kv = optional<ov::op::v0::Convert>({past_k});+ auto gather_input_k = wrap_type<ov::op::v8::Gather>({convert_kv, any_input(), any_input()});+ auto cache_input = wrap_type<ov::op::v0::Parameter>() | gather_input_k;+ auto cur_kv = any_input();+ auto kv_concat = wrap_type<ov::op::v0::Concat>({cache_input, cur_kv});++ // Note: SDPA can be quantized only with scalar scale and shift.+ auto fc_scale = wrap_type<ov::op::v0::Constant>(rank_equals(0));+ auto fc_shift = wrap_type<ov::op::v0::Constant>(rank_equals(0));+ auto fake_convert = wrap_type<ov::op::v13::FakeConvert>({kv_concat, fc_scale}) |+ wrap_type<ov::op::v13::FakeConvert>({kv_concat, fc_scale, fc_shift});++ auto [kv, reshape_kv, unsqueeze_kv, computed_bcst_kv, multiply_kv, computed_bcst3_kv] =+ ov::op::util::match_multi_query_bcst(fake_convert);+ return std::make_tuple(kv_concat, fake_convert, kv);+ };++ auto k_cache_result = match_kv_cache();+ auto k_concat = std::get<0>(k_cache_result);+ auto k_fc = std::get<1>(k_cache_result);+ auto key = std::get<2>(k_cache_result);++ auto v_cache_result = match_kv_cache();+ auto v_concat = std::get<0>(v_cache_result);+ auto v_fc = std::get<1>(v_cache_result);+ auto value = std::get<2>(v_cache_result);++#define ANY any_input()+ auto sdpa_m = wrap_type<ov::op::v13::ScaledDotProductAttention>({ANY, key, value}) |+ wrap_type<ov::op::v13::ScaledDotProductAttention>({ANY, key, value, ANY}) |+ wrap_type<ov::op::v13::ScaledDotProductAttention>({ANY, key, value, ANY, ANY});+#undef ANY++ matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ if (transformation_callback(m.get_match_root())) {+ return false;+ }+ bool res = false;+ const auto& pattern_map = m.get_pattern_value_map();+ for (const auto& pattern : {std::make_pair(k_concat, k_fc), std::make_pair(v_concat, v_fc)}) {+ const auto& [concat_m, fake_convert_m] = pattern;+ const auto concat = pattern_map.at(concat_m).get_node_shared_ptr();+ const auto concat_consumers = concat->get_users();+ if (std::any_of(concat_consumers.begin(),+ concat_consumers.end(),+ [](const std::shared_ptr<ov::Node>& consumer) {+ return !ov::is_type_any_of<ov::op::v13::FakeConvert,+ ov::op::v0::Result,+ ov::op::v6::Assign,+ ov::op::v3::ShapeOf>(consumer);+ })) {+ continue;+ }++ const auto fake_convert = pattern_map.at(fake_convert_m).get_node_shared_ptr();+ ov::replace_output_update_name(fake_convert->output(0), fake_convert->input_value(0));++ auto form_new_fc_inputs = [fake_convert](const ov::Output<ov::Node>& new_input) {+ auto new_inputs = fake_convert->input_values();+ new_inputs[0] = new_input;+ return new_inputs;+ };++ auto fc_cache = fake_convert->clone_with_new_inputs(form_new_fc_inputs(concat->input_value(0)));+ auto fc_kv = fake_convert->clone_with_new_inputs(form_new_fc_inputs(concat->input_value(1)));+ fc_cache->set_friendly_name(fake_convert->get_friendly_name() + "_1");+ fc_kv->set_friendly_name(fake_convert->get_friendly_name() + "_2");+ ov::copy_runtime_info(fake_convert, {fc_cache, fc_kv});++ auto new_concat = concat->clone_with_new_inputs({fc_cache->output(0), fc_kv->output(0)});+ new_concat->set_friendly_name(concat->get_friendly_name());+ ov::copy_runtime_info(concat, new_concat);+ ov::replace_node(concat, new_concat);+ res = true;+ }+ return res;+ };++ auto m = std::make_shared<Matcher>(sdpa_m, matcher_name);+ register_matcher(m, callback);+}+} // namespace ov::pass::low_precisiondiff --git a/src/common/low_precision_transformations/tests/kv_cache_static_quantization.cpp b/src/common/low_precision_transformations/tests/kv_cache_static_quantization.cppnew file mode 100644index 00000000000..b191b27d7f2--- /dev/null+++ b/src/common/low_precision_transformations/tests/kv_cache_static_quantization.cpp@@ -0,0 +1,362 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include "common_test_utils/ov_test_utils.hpp"+#include "common_test_utils/subgraph_builders/llm_builders.hpp"+#include "low_precision/concat.hpp"+#include "low_precision/kv_cache_concat.hpp"+#include "low_precision/move_fake_convert_up_through_kv_cache_concat.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/fake_convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/pass/graph_rewrite.hpp"+#include "transformations/op_conversions/fake_convert_decomposition.hpp"++using namespace ov;+using namespace ov::op;+using namespace testing;+using namespace ov::test::utils;++enum class SDPAType {+ Standard,+ WithMask,+ WithMaskAndScale,+};++using KVCacheStaticQuantizationParams = std::tuple<ov::element::Type, // original precision+ ov::element::Type, // low precision+ SDPAType,+ size_t, // num_groups+ bool, // stateful+ float, // scale+ float>; // shift++class KVCacheStaticQuantization : public TransformationTestsF,+ public WithParamInterface<KVCacheStaticQuantizationParams> {+public:+ KVCacheStaticQuantization() : TransformationTestsF() {+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+ }++ static std::string getTestCaseName(const testing::TestParamInfo<KVCacheStaticQuantizationParams>& obj) {+ auto [original_precision, low_precision, sdpa_type, num_groups, stateful, scale, shift] = obj.param;+ std::ostringstream result;+ result << "original_precision=" << original_precision << "_"+ << "low_precision=" << low_precision << "_"+ << "sdpa_type=" << static_cast<int>(sdpa_type) << "_"+ << "num_groups=" << num_groups << "_"+ << "stateful=" << stateful << "_"+ << "scale=" << scale << "_"+ << "shift=" << shift;+ return result.str();+ }++protected:+ std::shared_ptr<ov::Model> get_model(ov::element::Type original_precision,+ ov::element::Type low_precision,+ SDPAType sdpa_type,+ size_t num_groups,+ bool stateful,+ float scale,+ float shift);++ std::shared_ptr<ov::Model> get_model_ref(ov::element::Type original_precision,+ ov::element::Type low_precision,+ SDPAType sdpa_type,+ size_t num_groups,+ bool stateful,+ float scale,+ float shift);++ void SetUp() override {+ TransformationTestsF::SetUp();+ auto [original_precision, low_precision, sdpa_type, num_groups, stateful, scale, shift] = GetParam();+ model = get_model(original_precision, low_precision, sdpa_type, num_groups, stateful, scale, shift);+ model_ref = get_model_ref(original_precision, low_precision, sdpa_type, num_groups, stateful, scale, shift);++ using namespace ov::pass::low_precision;+ // Note: below is provided the minimal set of transformations required for kv cache static quantization.+ LayerTransformation::Params params;+ params.defaultPrecisions = {low_precision};+ manager.register_pass<MoveFakeConvertUpThroughKVCacheConcat>();+ auto graph_rewrite = manager.register_pass<ov::pass::GraphRewrite>();+ graph_rewrite->add_matcher<ov::pass::FakeConvertDecomposition>();+ graph_rewrite->add_matcher<ConcatTransformation>(params);+ // This transformation works only for stateful model+ graph_rewrite->add_matcher<KVCacheConcat>(model);+ }++private:+ // these params don't affect transformations behavior, so constant values can be used+ const ov::Dimension batch = 1, n_heads = 15, k_features = 64, v_features = 64;+ const std::vector<int64_t> qkv_order{0, 1, 2, 3};+};++TEST_P(KVCacheStaticQuantization, CompareWithRefImpl) {}++inline std::shared_ptr<ov::Node> create_sdpa(SDPAType sdpa_type,+ std::shared_ptr<ov::Node> q,+ std::shared_ptr<ov::Node> k,+ std::shared_ptr<ov::Node> v,+ ov::element::Type original_precision,+ ov::Dimension k_features,+ const std::vector<int64_t>& qkv_order) {+ std::shared_ptr<ov::Node> sdpa = nullptr;+ if (sdpa_type == SDPAType::WithMaskAndScale) {+ auto mask = make_attention_mask(q, k, original_precision, qkv_order);+ auto scale =+ v0::Constant::create(original_precision, ov::Shape{}, {1.0f / std::sqrt(k_features.get_max_length())});+ sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, mask, scale, true);+ } else if (sdpa_type == SDPAType::WithMask) {+ auto mask = make_attention_mask(q, k, original_precision, qkv_order);+ sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, mask, true);+ } else {+ OPENVINO_ASSERT(sdpa_type == SDPAType::Standard, "Unsupported SDPA type: ", static_cast<int>(sdpa_type));+ sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, true);+ }+ sdpa->set_friendly_name("sdpa");+ return sdpa;+}++std::shared_ptr<ov::Model> KVCacheStaticQuantization::get_model(ov::element::Type original_precision,+ ov::element::Type low_precision,+ SDPAType sdpa_type,+ size_t num_groups,+ bool stateful,+ float scale,+ float shift) {+ auto params = form_sdpa_params(batch,+ n_heads,+ k_features,+ v_features,+ original_precision,+ original_precision,+ qkv_order,+ num_groups);++ std::shared_ptr<ov::Node> concat_k_input = params[1];+ std::shared_ptr<ov::Node> concat_v_input = params[2];+ if (stateful) {+ auto in_beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{batch});+ in_beam_idx->set_friendly_name("beam_idx");+ params.push_back(in_beam_idx);++ concat_k_input = make_kv_rearrange(concat_k_input, in_beam_idx, qkv_order[0]);+ concat_v_input = make_kv_rearrange(concat_v_input, in_beam_idx, qkv_order[0]);+ }++ int64_t concat_axis = qkv_order[2];+ auto concat_k = std::make_shared<v0::Concat>(ov::OutputVector{concat_k_input, params[3]}, concat_axis);+ auto concat_v = std::make_shared<v0::Concat>(ov::OutputVector{concat_v_input, params[4]}, concat_axis);++ auto present_k = std::make_shared<v0::Result>(concat_k);+ present_k->set_friendly_name("present_k");++ auto present_v = std::make_shared<v0::Result>(concat_v);+ present_v->set_friendly_name("present_v");++ auto form_fake_convert = [&](std::shared_ptr<ov::Node> input) {+ auto fake_convert_scale = v0::Constant::create(original_precision, ov::Shape{}, {scale});+ auto fake_convert_shift = v0::Constant::create(original_precision, ov::Shape{}, {shift});+ return std::make_shared<v13::FakeConvert>(input, fake_convert_scale, fake_convert_shift, low_precision);+ };+ std::shared_ptr<ov::Node> q = params[0];+ std::shared_ptr<ov::Node> k = form_fake_convert(concat_k);+ std::shared_ptr<ov::Node> v = form_fake_convert(concat_v);++ if (num_groups > 1) {+ k = make_gqa(k, num_groups, n_heads, k_features, qkv_order);+ v = make_gqa(v, num_groups, n_heads, v_features, qkv_order);+ }++ auto sdpa = create_sdpa(sdpa_type, q, k, v, original_precision, k_features, qkv_order);+ auto sdpa_out = std::make_shared<v0::Result>(sdpa);+ sdpa_out->set_friendly_name("sdpa_out");++ ov::ResultVector results{sdpa_out, present_k, present_v};+ auto model = std::make_shared<ov::Model>(results, params, "LLM-KV-Cache-SDPA");++ if (stateful) {+ make_sdpa_model_stateful(model,+ params,+ present_k,+ present_v,+ original_precision,+ k_features,+ v_features,+ qkv_order);+ model->validate_nodes_and_infer_types();+ }+ return model;+}++std::shared_ptr<ov::Model> KVCacheStaticQuantization::get_model_ref(ov::element::Type original_precision,+ ov::element::Type low_precision,+ SDPAType sdpa_type,+ size_t num_groups,+ bool stateful,+ float scale,+ float shift) {+ auto params = form_sdpa_params(batch,+ n_heads,+ k_features,+ v_features,+ original_precision,+ stateful ? low_precision : original_precision,+ qkv_order,+ num_groups);+ auto fake_convert_downconvert = [&](const ov::Output<ov::Node>& input,+ float scale,+ float shift,+ bool skip_clamp = false) {+ auto downconvert = input;+ auto fake_convert_scale = v0::Constant::create(original_precision, ov::Shape{}, {scale});+ downconvert = std::make_shared<v1::Multiply>(input, fake_convert_scale);+ if (shift != 0.f) {+ auto fake_convert_shift = v0::Constant::create(original_precision, ov::Shape{}, {shift});+ downconvert = std::make_shared<v1::Subtract>(downconvert, fake_convert_shift);+ }+ if (!skip_clamp) {+ const auto [lower_bound, upper_bound] = [&]() {+ switch (low_precision) {+ case ov::element::f8e4m3:+ return std::make_pair(static_cast<double>(std::numeric_limits<ov::float8_e4m3>::lowest()),+ static_cast<double>(std::numeric_limits<ov::float8_e4m3>::max()));+ case ov::element::f8e5m2:+ return std::make_pair(static_cast<double>(std::numeric_limits<ov::float8_e5m2>::lowest()),+ static_cast<double>(std::numeric_limits<ov::float8_e5m2>::max()));+ default:+ OPENVINO_THROW("Unsupported destination element type: ", low_precision);+ }+ }();+ downconvert = std::make_shared<v0::Clamp>(downconvert, lower_bound, upper_bound);+ }+ return std::make_shared<v0::Convert>(downconvert, low_precision);+ };++ auto fake_convert_upconvert = [original_precision](const ov::Output<ov::Node>& input, float scale, float shift) {+ auto upconvert = input;+ upconvert = std::make_shared<v0::Convert>(input, original_precision);+ if (shift != 0.f) {+ auto fake_convert_shift = v0::Constant::create(original_precision, ov::Shape{}, {shift});+ upconvert = std::make_shared<v1::Subtract>(upconvert, fake_convert_shift);+ }+ auto fake_convert_scale = v0::Constant::create(original_precision, ov::Shape{}, {scale});+ return std::make_shared<v1::Multiply>(upconvert, fake_convert_scale);+ };++ // Create upconvert→downconvert ("reverse" fake convert: low precision on input-output, fp32 inside)+ auto create_reverse_build_convert = [&](std::shared_ptr<ov::Node> rearranged_input) {+ auto upconvert_result = fake_convert_upconvert(rearranged_input, 1.0f / scale, -shift);+ return fake_convert_downconvert(upconvert_result, scale, shift, true);+ };++ int64_t concat_axis = qkv_order[2];+ ov::OutputVector concat_k_inputs, concat_v_inputs;+ if (stateful) {+ auto in_beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{batch});+ in_beam_idx->set_friendly_name("beam_idx");+ params.push_back(in_beam_idx);++ auto rearranged_k = make_kv_rearrange(params[1], in_beam_idx, qkv_order[0]);+ auto rearranged_v = make_kv_rearrange(params[2], in_beam_idx, qkv_order[0]);++ auto concat_k_input = create_reverse_build_convert(rearranged_k);+ auto concat_v_input = create_reverse_build_convert(rearranged_v);+ // In case of stateful model, the whole KV cache subgraph has low precision after LPT,+ // so no fownconvert subgraph is needed.+ concat_k_inputs = {concat_k_input, fake_convert_downconvert(params[3], scale, shift)};+ concat_v_inputs = {concat_v_input, fake_convert_downconvert(params[4], scale, shift)};+ } else {+ concat_k_inputs = {fake_convert_downconvert(params[1], scale, shift),+ fake_convert_downconvert(params[3], scale, shift)};+ concat_v_inputs = {fake_convert_downconvert(params[2], scale, shift),+ fake_convert_downconvert(params[4], scale, shift)};+ }++ auto concat_k = std::make_shared<v0::Concat>(concat_k_inputs, concat_axis);+ auto concat_v = std::make_shared<v0::Concat>(concat_v_inputs, concat_axis);++ std::shared_ptr<ov::Node> result_input_k = concat_k;+ std::shared_ptr<ov::Node> result_input_v = concat_v;+ if (stateful) {+ // Add reverse fake convert before assign+ result_input_k = create_reverse_build_convert(concat_k);+ result_input_v = create_reverse_build_convert(concat_v);+ }++ // Note: upconvert part contains opposite scale and shift+ auto upconvert_k = fake_convert_upconvert(result_input_k, 1.f / scale, -shift);+ auto upconvert_v = fake_convert_upconvert(result_input_v, 1.f / scale, -shift);++ auto present_k = std::make_shared<v0::Result>(stateful ? result_input_k : upconvert_k);+ present_k->set_friendly_name("present_k");++ auto present_v = std::make_shared<v0::Result>(stateful ? result_input_v : upconvert_v);+ present_v->set_friendly_name("present_v");++ std::shared_ptr<ov::Node> q = params[0];+ std::shared_ptr<ov::Node> k = upconvert_k;+ std::shared_ptr<ov::Node> v = upconvert_v;++ if (num_groups > 1) {+ k = make_gqa(k, num_groups, n_heads, k_features, qkv_order);+ v = make_gqa(v, num_groups, n_heads, v_features, qkv_order);+ }++ auto sdpa = create_sdpa(sdpa_type, q, k, v, original_precision, k_features, qkv_order);+ auto sdpa_out = std::make_shared<v0::Result>(sdpa);+ sdpa_out->set_friendly_name("sdpa_out");++ ov::ResultVector results{sdpa_out, present_k, present_v};+ auto model = std::make_shared<ov::Model>(results, params, "LLM-KV-Cache-SDPA");++ if (stateful) {+ make_sdpa_model_stateful(model,+ params,+ present_k,+ present_v,+ original_precision,+ k_features,+ v_features,+ qkv_order);+ model->validate_nodes_and_infer_types();+ }+ return model;+}++namespace {+const ov::element::TypeVector low_precision_types = {+ ov::element::f8e4m3,+ ov::element::f8e5m2,+};++const std::vector<SDPAType> sdpa_types = {+ SDPAType::Standard,+ SDPAType::WithMask,+ SDPAType::WithMaskAndScale,+};++const std::vector<float> scales = {4.f};+const std::vector<float> shifts = {0.f, 12.f};++INSTANTIATE_TEST_SUITE_P(smoke_KVCacheStaticQuantization,+ KVCacheStaticQuantization,+ ::testing::Combine(::testing::Values(ov::element::f32),+ ::testing::ValuesIn(low_precision_types),+ ::testing::ValuesIn(sdpa_types),+ ::testing::Values(3),+ ::testing::Values(true, false),+ ::testing::ValuesIn(scales),+ ::testing::ValuesIn(shifts)),+ KVCacheStaticQuantization::getTestCaseName);+} // namespace\ No newline at end of filediff --git a/src/common/transformations/include/transformations/utils/utils.hpp b/src/common/transformations/include/transformations/utils/utils.hppindex b8533ac3967..a911db150ab 100644--- a/src/common/transformations/include/transformations/utils/utils.hpp+++ b/src/common/transformations/include/transformations/utils/utils.hpp@@ -9,6 +9,7 @@#include <functional>#include <limits>#include <memory>+#include <tuple>#include <variant>#include <vector>@@ -290,6 +291,14 @@ TRANSFORMATIONS_API bool is_on_constant_path(const ov::Output<ov::Node>& output)TRANSFORMATIONS_API bool process_subgraph(ov::pass::ModelPass& model_pass, const std::shared_ptr<Node>& node);+TRANSFORMATIONS_API std::tuple<std::shared_ptr<ov::Node>, // result+ std::shared_ptr<ov::Node>, // reshape_kv+ std::shared_ptr<ov::Node>, // unsqueeze_kv+ std::shared_ptr<ov::Node>, // computed_bcst+ std::shared_ptr<ov::Node>, // multiply_kv+ std::shared_ptr<ov::Node>> // computed_bcst3+match_multi_query_bcst(const std::shared_ptr<ov::Node>& kv);+template <typename T>ov::pass::pattern::op::Predicate constant_predicate(std::function<bool(const std::vector<T>&)> predicate) {return ov::pass::pattern::op::Predicate([=](std::shared_ptr<Node> n) -> bool {diff --git a/src/common/transformations/src/transformations/utils/utils.cpp b/src/common/transformations/src/transformations/utils/utils.cppindex 746991697e2..9dbd011f24d 100644--- a/src/common/transformations/src/transformations/utils/utils.cpp+++ b/src/common/transformations/src/transformations/utils/utils.cpp@@ -8,6 +8,7 @@#include <functional>#include <memory>+#include <tuple>#include <vector>#include "openvino/core/validation_util.hpp"@@ -31,6 +32,7 @@#include "openvino/op/strided_slice.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/tanh.hpp"+#include "openvino/op/unsqueeze.hpp"#include "openvino/op/util/multi_subgraph_base.hpp"#include "openvino/op/util/shape_of_base.hpp"#include "openvino/pass/pattern/op/optional.hpp"@@ -635,6 +637,41 @@ std::shared_ptr<ov::Node> NewGenSlice(const std::shared_ptr<ov::Node>& data,return opt1 | opt2;}+std::tuple<std::shared_ptr<ov::Node>,+ std::shared_ptr<ov::Node>,+ std::shared_ptr<ov::Node>,+ std::shared_ptr<ov::Node>,+ std::shared_ptr<ov::Node>,+ std::shared_ptr<ov::Node>>+match_multi_query_bcst(const std::shared_ptr<ov::Node>& kv) {+ using namespace ov::pass;+ using namespace ov::pass::pattern;++ auto reshape_kv = wrap_type<ov::op::v1::Reshape>({kv, any_input()});+ auto unsqueeze_kv = wrap_type<ov::op::v0::Unsqueeze>({kv, any_input()});++ auto check_one = [](const Output<Node>& output) -> bool {+ auto node = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());+ if (!node) {+ return false;+ }+ const auto& bcst_arg = node->cast_vector<float>();+ return std::all_of(bcst_arg.begin(), bcst_arg.end(), [](float i) {+ return i == 1.0F;+ });+ };+ auto constant_bcst = wrap_type<ov::op::v0::Constant>(check_one);++ auto computed_bcst =+ wrap_type<ov::op::v1::Broadcast>({constant_bcst, any_input(), any_input()}, {{"mode", "numpy"}});++ auto multiply_kv = wrap_type<ov::op::v1::Multiply>({reshape_kv | unsqueeze_kv, constant_bcst | computed_bcst});+ auto computed_bcst3 = wrap_type<ov::op::v3::Broadcast>({unsqueeze_kv, any_input()}, {{"mode", "bidirectional"}});++ auto result = wrap_type<ov::op::v1::Reshape>({multiply_kv | computed_bcst3, any_input()});+ return std::make_tuple(result, reshape_kv, unsqueeze_kv, computed_bcst, multiply_kv, computed_bcst3);+}+} // namespace util} // namespace op} // namespace ovdiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cppindex f8a1c59be9d..9f3c2df7fb8 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp@@ -25,18 +25,14 @@#include "openvino/core/node_vector.hpp"#include "openvino/core/type.hpp"#include "openvino/op/assign.hpp"-#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/gather.hpp"-#include "openvino/op/multiply.hpp"#include "openvino/op/read_value.hpp"-#include "openvino/op/reshape.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/transpose.hpp"-#include "openvino/op/unsqueeze.hpp"#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/matcher.hpp"#include "openvino/pass/pattern/op/label.hpp"@@ -44,6 +40,7 @@#include "transformations/cpu_opset/common/op/sdpa.hpp"#include "transformations/defs.hpp"#include "transformations/transpose_sinking/ts_shape_of.hpp"+#include "transformations/utils/utils.hpp"#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)# include "transformations/cpu_opset/x64/pass/sdpa_fuse_transpose_reshape.hpp"@@ -81,48 +78,12 @@ StatefulSDPAFusion::StatefulSDPAFusion() {auto concat_k = makePattern<ov::op::v0::Concat>({gather_input_k, cur_k}, {{"axis", axis_seq_len}});auto concat_v = makePattern<ov::op::v0::Concat>({gather_input_v, cur_v}, {{"axis", axis_seq_len}});- std::shared_ptr<Node> reshape_k;- std::shared_ptr<Node> reshape_v;- std::shared_ptr<Node> unsqueeze_k;- std::shared_ptr<Node> unsqueeze_v;- std::shared_ptr<Node> computed_bcst_k;- std::shared_ptr<Node> computed_bcst_v;- std::shared_ptr<Node> multiply_k;- std::shared_ptr<Node> multiply_v;- std::shared_ptr<Node> mq_reshape_k;- std::shared_ptr<Node> mq_reshape_v;- std::shared_ptr<Node> computed_bcst3_k;- std::shared_ptr<Node> computed_bcst3_v;- auto multi_query_bcst = [](const std::shared_ptr<Node>& kv) {- auto reshape_kv = makePattern<ov::op::v1::Reshape>({kv, any_input()});- auto unsqueeze_kv = makePattern<ov::op::v0::Unsqueeze>({kv, any_input()});-- auto check_one = [](const Output<Node>& output) -> bool {- auto node = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());- const auto& bcst_arg = node->cast_vector<float>();- return std::all_of(bcst_arg.begin(), bcst_arg.end(), [](float i) {- return i == 1.0F;- });- };- auto constant_bcst = wrap_type<ov::op::v0::Constant>(check_one);-- auto computed_bcst =- makePattern<ov::op::v1::Broadcast>({wrap_type<ov::op::v0::Constant>(check_one), any_input(), any_input()},- {{"mode", "numpy"}});-- auto multiply_kv =- makePattern<ov::op::v1::Multiply>({reshape_kv | unsqueeze_kv, constant_bcst | computed_bcst});- auto computed_bcst3 =- makePattern<ov::op::v3::Broadcast>({unsqueeze_kv, any_input()}, {{"mode", "bidirectional"}});-- auto result = makePattern<ov::op::v1::Reshape>({multiply_kv | computed_bcst3, any_input()});- return std::make_tuple(result, reshape_kv, unsqueeze_kv, computed_bcst, multiply_kv, computed_bcst3);- };-+ std::shared_ptr<Node> mq_reshape_k, reshape_k, unsqueeze_k, computed_bcst_k, multiply_k, computed_bcst3_k;std::tie(mq_reshape_k, reshape_k, unsqueeze_k, computed_bcst_k, multiply_k, computed_bcst3_k) =- multi_query_bcst(concat_k);+ ov::op::util::match_multi_query_bcst(concat_k);+ std::shared_ptr<Node> mq_reshape_v, reshape_v, unsqueeze_v, computed_bcst_v, multiply_v, computed_bcst3_v;std::tie(mq_reshape_v, reshape_v, unsqueeze_v, computed_bcst_v, multiply_v, computed_bcst3_v) =- multi_query_bcst(concat_v);+ ov::op::util::match_multi_query_bcst(concat_v);auto present_k = concat_k | mq_reshape_k;auto present_v = concat_v | mq_reshape_v;diff --git a/src/tests/test_utils/common_test_utils/include/common_test_utils/subgraph_builders/llm_builders.hpp b/src/tests/test_utils/common_test_utils/include/common_test_utils/subgraph_builders/llm_builders.hppindex 03c56f24dbf..fc3abfbb2e2 100644--- a/src/tests/test_utils/common_test_utils/include/common_test_utils/subgraph_builders/llm_builders.hpp+++ b/src/tests/test_utils/common_test_utils/include/common_test_utils/subgraph_builders/llm_builders.hpp@@ -44,14 +44,16 @@ std::shared_ptr<ov::Node> make_attention_mask(ov::Output<ov::Node> q,* @brief Creates a Grouped Query Attention (GQA)* @param kv Key or Value tensor* @param num_groups Number of groups for GQA- * @param target_shape_v Target shape vector* @param n_heads Number of heads+ * @param features Number of features (key or value features)+ * @param qkv_order Order of QKV dimensions for shape transformation* @return Shared pointer to the created GQA*/std::shared_ptr<ov::Node> make_gqa(ov::Output<ov::Node> kv,size_t num_groups,- std::vector<int32_t> target_shape_v,- int32_t n_heads);+ ov::Dimension n_heads,+ ov::Dimension features,+ std::vector<int64_t> qkv_order = {0, 1, 2, 3});/*** @brief Creates a transpose operation for QKV tensors@@ -70,7 +72,49 @@ std::shared_ptr<ov::Node> make_qkv_transpose(ov::Output<ov::Node> qkv, std::vect*/std::shared_ptr<ov::Node> make_kv_rearrange(ov::Output<ov::Node> kv_past,ov::Output<ov::Node> beam_idx,- int axis_val = 0);+ int64_t axis_val = 0);++/**+ * @brief Makes a model stateful by setting up KV cache state management+ * @param model The model to make stateful+ * @param params Parameter vector containing the model parameters.+ * Note: params must be in the following order: {q, past_k, past_v, in_k_token, in_v_token}+ * @param present_k Result node for present K cache+ * @param present_v Result node for present V cache+ * @param element_type Element type for state initializers+ * @param k_features K features dimension+ * @param v_features V features dimension+ * @param qkv_order Order of QKV dimensions+ */+void make_sdpa_model_stateful(std::shared_ptr<ov::Model> model,+ const ov::ParameterVector& params,+ std::shared_ptr<ov::op::v0::Result> present_k,+ std::shared_ptr<ov::op::v0::Result> present_v,+ ov::element::Type_t element_type,+ ov::Dimension k_features,+ ov::Dimension v_features,+ std::vector<int64_t> qkv_order);++/**+ * @brief Creates parameters for SDPA pattern model+ * @param batch Batch dimension+ * @param n_heads Number of heads dimension+ * @param k_features Key features dimension+ * @param v_features Value features dimension+ * @param qkv_precision Element type for QKV tensors+ * @param past_kv_precision Element type for past KV cache+ * @param qkv_order Order of QKV dimensions+ * @param num_groups Number of groups for GQA+ * @return Parameter vector containing {q, past_k, past_v, in_k_token, in_v_token}+ */+ov::ParameterVector form_sdpa_params(ov::Dimension batch,+ ov::Dimension n_heads,+ ov::Dimension k_features,+ ov::Dimension v_features,+ ov::element::Type_t qkv_precision,+ ov::element::Type_t past_kv_precision,+ std::vector<int64_t> qkv_order,+ size_t num_groups);/*** @brief Creates an LLM KV cache pattern modeldiff --git a/src/tests/test_utils/common_test_utils/src/subgraph_builders/llm_builders.cpp b/src/tests/test_utils/common_test_utils/src/subgraph_builders/llm_builders.cppindex 6e5b2e96e59..58951f31da8 100644--- a/src/tests/test_utils/common_test_utils/src/subgraph_builders/llm_builders.cpp+++ b/src/tests/test_utils/common_test_utils/src/subgraph_builders/llm_builders.cpp@@ -104,22 +104,34 @@ std::shared_ptr<ov::Node> make_attention_mask(ov::Output<ov::Node> q,std::shared_ptr<ov::Node> make_gqa(ov::Output<ov::Node> kv,size_t num_groups,- std::vector<int32_t> target_shape_v,- int32_t n_heads) {+ ov::Dimension n_heads,+ ov::Dimension features,+ std::vector<int64_t> qkv_order) {+ // Form the target shape: {0, n_heads, -1, features}+ auto nh = static_cast<int32_t>(n_heads.get_length());+ auto fs = static_cast<int32_t>(features.get_length());+ std::vector<int32_t> target_shape_original = {0, nh, -1, fs};++ // Apply qkv_order transformation to target_shape+ std::vector<int32_t> target_shape(target_shape_original.size());+ for (size_t i = 0; i < target_shape_original.size(); i++) {+ target_shape[qkv_order[i]] = target_shape_original[i];+ }+int32_t num_heads_idx =- std::distance(target_shape_v.begin(), std::find(target_shape_v.begin(), target_shape_v.end(), n_heads)) + 1;+ std::distance(target_shape.begin(), std::find(target_shape.begin(), target_shape.end(), nh)) + 1;auto unsqueeze_axis = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{1}, num_heads_idx);auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(kv, unsqueeze_axis);- const size_t extended_rank = target_shape_v.size() + 1;+ const size_t extended_rank = target_shape.size() + 1;std::vector<int32_t> shape_vec(extended_rank, 1);shape_vec[num_heads_idx] = static_cast<int32_t>(num_groups);auto broadcast_shape = ov::op::v0::Constant::create(ov::element::i32, {extended_rank}, shape_vec);auto broadcast =std::make_shared<ov::op::v3::Broadcast>(unsqueeze, broadcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);- auto target_shape = ov::op::v0::Constant::create(ov::element::i32, {4}, target_shape_v);- auto reshape = std::make_shared<ov::op::v1::Reshape>(broadcast, target_shape, true);+ auto target_shape_const = ov::op::v0::Constant::create(ov::element::i32, {4}, target_shape);+ auto reshape = std::make_shared<ov::op::v1::Reshape>(broadcast, target_shape_const, true);return reshape;}@@ -129,11 +141,89 @@ std::shared_ptr<ov::Node> make_qkv_transpose(ov::Output<ov::Node> qkv, std::vectreturn std::make_shared<ov::op::v1::Transpose>(qkv, transpose_const);}-std::shared_ptr<ov::Node> make_kv_rearrange(ov::Output<ov::Node> kv_past, ov::Output<ov::Node> beam_idx, int axis_val) {+std::shared_ptr<ov::Node> make_kv_rearrange(ov::Output<ov::Node> kv_past,+ ov::Output<ov::Node> beam_idx,+ int64_t axis_val) {auto axis = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, axis_val);return std::make_shared<ov::op::v8::Gather>(kv_past, beam_idx, axis, 0);}+void make_sdpa_model_stateful(std::shared_ptr<ov::Model> model,+ const ov::ParameterVector& params,+ std::shared_ptr<ov::op::v0::Result> present_k,+ std::shared_ptr<ov::op::v0::Result> present_v,+ ov::element::Type_t element_type,+ ov::Dimension k_features,+ ov::Dimension v_features,+ std::vector<int64_t> qkv_order) {+ ov::pass::MakeStateful({{params[1], present_k}, {params[2], present_v}}).run_on_model(model);+ auto k_state_initializer =+ make_state_initializer(params[3], element_type, params[1]->get_partial_shape(), qkv_order);+ auto v_state_initializer =+ make_state_initializer(params[4], element_type, params[2]->get_partial_shape(), qkv_order);++ if (k_state_initializer->get_output_element_type(0) != params[1]->get_element_type())+ k_state_initializer = std::make_shared<ov::op::v0::Convert>(k_state_initializer, params[1]->get_element_type());+ if (v_state_initializer->get_output_element_type(0) != params[2]->get_element_type())+ v_state_initializer = std::make_shared<ov::op::v0::Convert>(v_state_initializer, params[2]->get_element_type());++ for (auto op : model->get_ops()) {+ if (auto read_value = ov::as_type_ptr<ov::op::v6::ReadValue>(op)) {+ auto shape = op->get_output_partial_shape(0);+ if (shape[3] == k_features)+ read_value->set_arguments(ov::OutputVector{k_state_initializer});+ else if (shape[3] == v_features)+ read_value->set_arguments(ov::OutputVector{v_state_initializer});+ }+ }+}++ov::ParameterVector form_sdpa_params(ov::Dimension batch,+ ov::Dimension n_heads,+ ov::Dimension k_features,+ ov::Dimension v_features,+ ov::element::Type_t qkv_precision,+ ov::element::Type_t past_kv_precision,+ std::vector<int64_t> qkv_order,+ size_t num_groups) {+ ov::PartialShape k_cache_size_def = {batch, n_heads / num_groups, -1, k_features};+ ov::PartialShape v_cache_size_def = {batch, n_heads / num_groups, -1, v_features};+ ov::PartialShape new_k_token_size_def = {batch, n_heads / num_groups, -1, k_features};+ ov::PartialShape new_v_token_size_def = {batch, n_heads / num_groups, -1, v_features};+ ov::PartialShape q_size_def = {batch, n_heads, -1, k_features};++ ov::PartialShape k_cache_size = ov::PartialShape::dynamic(4);+ ov::PartialShape v_cache_size = ov::PartialShape::dynamic(4);+ ov::PartialShape new_k_token_size = ov::PartialShape::dynamic(4);+ ov::PartialShape new_v_token_size = ov::PartialShape::dynamic(4);+ ov::PartialShape q_size = ov::PartialShape::dynamic(4);++ for (size_t i = 0; i < k_cache_size_def.size(); i++) {+ k_cache_size[qkv_order[i]] = k_cache_size_def[i];+ v_cache_size[qkv_order[i]] = v_cache_size_def[i];+ new_k_token_size[qkv_order[i]] = new_k_token_size_def[i];+ new_v_token_size[qkv_order[i]] = new_v_token_size_def[i];+ q_size[qkv_order[i]] = q_size_def[i];+ }++ auto past_k = std::make_shared<ov::op::v0::Parameter>(past_kv_precision, k_cache_size);+ past_k->set_friendly_name("past_k");++ auto past_v = std::make_shared<ov::op::v0::Parameter>(past_kv_precision, v_cache_size);+ past_v->set_friendly_name("past_v");++ auto in_k_token = std::make_shared<ov::op::v0::Parameter>(qkv_precision, new_k_token_size);+ in_k_token->set_friendly_name("new_k_token");++ auto in_v_token = std::make_shared<ov::op::v0::Parameter>(qkv_precision, new_v_token_size);+ in_v_token->set_friendly_name("new_v_token");++ auto in_q = std::make_shared<ov::op::v0::Parameter>(qkv_precision, q_size);+ in_q->set_friendly_name("in_q");++ return {in_q, past_k, past_v, in_k_token, in_v_token};+}+std::shared_ptr<ov::Model> make_llm_kv_cache_pattern(ov::Dimension batch,ov::Dimension n_heads,ov::Dimension n_features,@@ -172,10 +262,7 @@ std::shared_ptr<ov::Model> make_llm_kv_cache_pattern(ov::Dimension batch,std::shared_ptr<ov::Node> kv_input = concat;if (num_groups > 1) {- auto nh = static_cast<int32_t>(n_heads.get_length());- auto hs = static_cast<int32_t>(n_features.get_length());- std::vector<int32_t> target_shape = {0, nh, -1, hs};- kv_input = make_gqa(kv_input, num_groups, target_shape, nh);+ kv_input = make_gqa(kv_input, num_groups, n_heads, n_features);}auto matmul = std::make_shared<ov::op::v0::MatMul>(in_matmul, kv_input, false, false);@@ -213,44 +300,16 @@ std::shared_ptr<ov::Model> make_llm_kv_cache_sdpa_pattern(ov::Dimension batch,bool stateful,bool fuse_cache_reorder,size_t num_groups) {- ov::PartialShape k_cache_size_def = {batch, n_heads / num_groups, -1, k_features};- ov::PartialShape v_cache_size_def = {batch, n_heads / num_groups, -1, v_features};- ov::PartialShape new_k_token_size_def = {batch, n_heads / num_groups, -1, k_features};- ov::PartialShape new_v_token_size_def = {batch, n_heads / num_groups, -1, v_features};- ov::PartialShape q_size_def = {batch, n_heads, -1, k_features};-- ov::PartialShape k_cache_size = ov::PartialShape::dynamic(4);- ov::PartialShape v_cache_size = ov::PartialShape::dynamic(4);- ov::PartialShape new_k_token_size = ov::PartialShape::dynamic(4);- ov::PartialShape new_v_token_size = ov::PartialShape::dynamic(4);- ov::PartialShape q_size = ov::PartialShape::dynamic(4);-- for (size_t i = 0; i < k_cache_size_def.size(); i++) {- k_cache_size[qkv_order[i]] = k_cache_size_def[i];- v_cache_size[qkv_order[i]] = v_cache_size_def[i];- new_k_token_size[qkv_order[i]] = new_k_token_size_def[i];- new_v_token_size[qkv_order[i]] = new_v_token_size_def[i];- q_size[qkv_order[i]] = q_size_def[i];- }+ auto params =+ form_sdpa_params(batch, n_heads, k_features, v_features, element_type, element_type, qkv_order, num_groups);+ auto in_q = params[0];+ auto past_k = params[1];+ auto past_v = params[2];+ auto in_k_token = params[3];+ auto in_v_token = params[4];int64_t concat_axis = qkv_order[2];- auto past_k = std::make_shared<ov::op::v0::Parameter>(element_type, k_cache_size);- past_k->set_friendly_name("past_k");-- auto past_v = std::make_shared<ov::op::v0::Parameter>(element_type, v_cache_size);- past_v->set_friendly_name("past_v");-- auto in_k_token = std::make_shared<ov::op::v0::Parameter>(element_type, new_k_token_size);- in_k_token->set_friendly_name("new_k_token");-- auto in_v_token = std::make_shared<ov::op::v0::Parameter>(element_type, new_v_token_size);- in_v_token->set_friendly_name("new_v_token");-- auto in_q = std::make_shared<ov::op::v0::Parameter>(element_type, q_size);- in_q->set_friendly_name("in_q");-- ov::ParameterVector params{in_q, past_k, past_v, in_k_token, in_v_token};std::shared_ptr<ov::Node> concat_k_input = past_k;std::shared_ptr<ov::Node> concat_v_input = past_v;if (fuse_cache_reorder) {@@ -290,21 +349,8 @@ std::shared_ptr<ov::Model> make_llm_kv_cache_sdpa_pattern(ov::Dimension batch,}if (num_groups > 1) {- auto nh = static_cast<int32_t>(n_heads.get_length());- auto vs = static_cast<int32_t>(v_features.get_length());- auto ks = static_cast<int32_t>(k_features.get_length());- std::vector<int32_t> v_target_shape = {0, nh, -1, vs};- std::vector<int32_t> v_target_shape_transposed(v_target_shape.size());- std::vector<int32_t> k_target_shape = {0, nh, -1, ks};- std::vector<int32_t> k_target_shape_transposed(k_target_shape.size());-- for (size_t i = 0; i < v_target_shape.size(); i++) {- k_target_shape_transposed[qkv_order[i]] = k_target_shape[i];- v_target_shape_transposed[qkv_order[i]] = v_target_shape[i];- }-- k = make_gqa(k, num_groups, k_target_shape_transposed, nh);- v = make_gqa(v, num_groups, v_target_shape_transposed, nh);+ k = make_gqa(k, num_groups, n_heads, k_features, qkv_order);+ v = make_gqa(v, num_groups, n_heads, v_features, qkv_order);}if (qkv_order != std::vector<int64_t>{0, 1, 2, 3}) {@@ -330,18 +376,7 @@ std::shared_ptr<ov::Model> make_llm_kv_cache_sdpa_pattern(ov::Dimension batch,auto model = std::make_shared<ov::Model>(results, params, "LLM-KV-Cache-SDPA");if (stateful) {- ov::pass::MakeStateful({{past_k, present_k}, {past_v, present_v}}).run_on_model(model);- auto k_state_initializer = make_state_initializer(in_k_token, element_type, k_cache_size, qkv_order);- auto v_state_initializer = make_state_initializer(in_v_token, element_type, v_cache_size, qkv_order);- for (auto op : model->get_ops()) {- if (auto read_value = ov::as_type_ptr<ov::op::v6::ReadValue>(op)) {- auto shape = op->get_output_partial_shape(0);- if (shape[3] == k_features)- read_value->set_arguments(ov::OutputVector{k_state_initializer});- else if (shape[3] == v_features)- read_value->set_arguments(ov::OutputVector{v_state_initializer});- }- }+ make_sdpa_model_stateful(model, params, present_k, present_v, element_type, k_features, v_features, qkv_order);}model->validate_nodes_and_infer_types();