Skip to content

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

NPUW: Dynamic GQA Dispatch (#38304)

Dmitry Matveevd302464e8cb9
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
index 2f48af68d06..dd6c797212b 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
@@ -74,6 +74,8 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE, uint64_t, 256, ov:
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS, uint64_t, 128, ov::intel_npu::npuw::llm, prefix_caching_max_num_blocks, "NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_CONTINUOUS_PREFILL, bool, true, ov::intel_npu::npuw::llm, enable_continuous_prefill, "NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, ov::intel_npu::npuw::llm, cache_rope, "NPUW_LLM_CACHE_ROPE", LLM, EXPOSED, CACHED, ALL)
+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_MAX_CONTEXT_LEN, uint32_t, 8192, ov::intel_npu::npuw::llm, max_context_len, "NPUW_LLM_MAX_CONTEXT_LEN", LLM, EXPOSED, CACHED, ALL)
+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_SWA_LEN, uint32_t, 0, ov::intel_npu::npuw::llm, swa_len, "NPUW_LLM_SWA_LEN", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, bool, false, ov::intel_npu::npuw::llm, enable_block_based_kv_cache, "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK, bool, false, ov::intel_npu::npuw::llm, enable_swa_kv_cache_shrink, "NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_PREFILL_MOE_HINT, ::intel_npu::npuw::llm::MoEHint, MoEHintOptionTraits, ov::intel_npu::npuw::llm, prefill_moe_hint, "NPUW_LLM_PREFILL_MOE_HINT", LLM, EXPOSED, CACHED, ALL)
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
index 9e10cfb4124..8c02c89d13d 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -324,13 +324,25 @@ std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::ICompiledModel::create(
auto config = properties;
config.erase(ov::cache_dir.name());
- if (properties.count(use_flux2_key) && properties.at(use_flux2_key).as<bool>() == true) {
+ const bool flux2_requested = properties.count(use_flux2_key) && properties.at(use_flux2_key).as<bool>() == true;
+ const bool llm_requested = properties.count(use_llm_key) && properties.at(use_llm_key).as<bool>() == true;
+ const bool pa_requested = properties.count(use_pa_key) && properties.at(use_pa_key).as<bool>() == true;
+ const bool kokoro_requested = properties.count(use_kokoro_key) && properties.at(use_kokoro_key).as<bool>() == true;
+
+ const bool gqa_explicitly_set = properties.count(use_gqa_key) > 0;
+ const bool gqa_explicitly_disabled = gqa_explicitly_set && properties.at(use_gqa_key).as<bool>() == false;
+ const bool gqa_requested = gqa_explicitly_set && properties.at(use_gqa_key).as<bool>() == true;
+ // Auto-detect GQA models unless NPUW_GQA=NO or another front-end was explicitly requested.
+ const bool gqa_detected = !gqa_explicitly_disabled && !flux2_requested && !llm_requested && !pa_requested &&
+ !kokoro_requested && ov::npuw::GQACompiledModel::supports(model);
+
+ if (flux2_requested) {
LOG_INFO("ov::npuw::Flux2CompiledModel will be created.");
compiled_model = std::make_shared<ov::npuw::Flux2CompiledModel>(model, plugin, config);
- } else if (properties.count(use_gqa_key) && properties.at(use_gqa_key).as<bool>() == true) {
+ } else if (gqa_requested || gqa_detected) {
LOG_INFO("ov::npuw::GQACompiledModel will be created.");
compiled_model = std::make_shared<ov::npuw::GQACompiledModel>(model, plugin, config);
- } else if (properties.count(use_llm_key) && properties.at(use_llm_key).as<bool>() == true) {
+ } else if (llm_requested) {
LOG_INFO("ov::npuw::LLMCompiledModel will be created.");
auto llm_compiled_model = std::make_shared<ov::npuw::LLMCompiledModel>(model, plugin, config);
const auto scoring_tags = ov::npuw::batched::scoring_tags(config);
@@ -345,10 +357,10 @@ std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::ICompiledModel::create(
} else {
compiled_model = llm_compiled_model;
}
- } else if (properties.count(use_pa_key) && properties.at(use_pa_key).as<bool>() == true) {
+ } else if (pa_requested) {
LOG_INFO("ov::npuw::PACompiledModel will be created.");
compiled_model = std::make_shared<ov::npuw::PACompiledModel>(model, plugin, config);
- } else if (properties.count(use_kokoro_key) && properties.at(use_kokoro_key).as<bool>() == true) {
+ } else if (kokoro_requested) {
LOG_INFO("ov::npuw::KokoroCompiledModel will be created.");
compiled_model = std::make_shared<ov::npuw::KokoroCompiledModel>(model, plugin, config);
} else {
@@ -2439,6 +2451,12 @@ ov::SoPtr<ov::ICompiledModel> ov::npuw::CompiledModel::compile_submodel(const st
device_config["NPU_RUN_INFERENCES_SEQUENTIALLY"] = "YES";
}
+ if (ov::npuw::util::starts_with(device, "NPU")) {
+ // Internal submodel recompilation; prevent re-entering NPUW auto-detect
+ // (e.g. on an un-decomposed GroupQueryAttention op).
+ device_config[ov::intel_npu::use_npuw.name()] = false;
+ }
+
const auto& cache_dir = m_cfg.get<::intel_npu::NPUW_CACHE_DIR>();
if (!cache_dir.empty()) {
LOG_INFO("NPUW will try to utilize CACHE_DIR for " << submodel->get_friendly_name() << " submodel.");
diff --git a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp
index 8b8d85eea29..ea1558a31e9 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp
@@ -5,21 +5,107 @@
#include "gqa_compiled_model.hpp"
#include <algorithm>
+#include <array>
+#include <atomic>
#include <cctype>
+#include <cstdlib>
+#include <cstring>
+#include <iostream>
+#include <optional>
+#include <sstream>
+#include <typeinfo>
+#include <unordered_set>
#include <utility>
+#include "infer_request_utils.hpp"
#include "intel_npu/config/npuw.hpp"
#include "logging.hpp"
#include "npuw_transformations/collapse_unqdq.hpp"
#include "npuw_transformations/conv_to_matmul.hpp"
#include "npuw_transformations/drop_zp_subtract.hpp"
+#include "npuw_transformations/reshape_to_static_gqa.hpp"
#include "npuw_transformations/untangle_dq_scale.hpp"
+#include "openvino/core/descriptor/tensor.hpp"
+#include "openvino/core/node_vector.hpp"
#include "openvino/core/version.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/group_query_attention.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/util/op_types.hpp"
+#include "openvino/runtime/make_tensor.hpp"
#include "openvino/runtime/properties.hpp"
#include "serialization.hpp"
+#include "util.hpp"
namespace {
+// Reads an NPUW option from a raw properties AnyMap, falling back to its default.
+template <typename T>
+auto cfg_get(const ov::AnyMap& properties) -> typename T::ValueType {
+ const auto& opt_name = std::string(T::key());
+ if (properties.count(opt_name)) {
+ return properties.at(opt_name).as<typename T::ValueType>();
+ }
+ return T::defaultValue();
+}
+
+// Enables "[GQA-TRACE]" diagnostic logging via OPENVINO_NPUW_GQA_LOG=1 (developer builds only).
+bool gqa_trace_enabled() {
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ static const bool enabled = [] {
+ const char* value = std::getenv("OPENVINO_NPUW_GQA_LOG");
+ return value != nullptr && std::string(value) == "1";
+ }();
+ return enabled;
+#else
+ return false;
+#endif
+}
+
+// Strictly parses env var `env_name` as a positive integer; throws on malformed values.
+std::optional<size_t> parse_positive_size_env_var(const char* env_name) {
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ const char* raw = std::getenv(env_name);
+ if (raw == nullptr) {
+ return std::nullopt;
+ }
+ const std::string str(raw);
+ auto parsed = ov::npuw::util::parse_positive_int_env_var(str);
+ if (!parsed) {
+ OPENVINO_THROW(env_name, " must be a positive integer, got: '", str, "'");
+ }
+ return static_cast<size_t>(*parsed);
+#else
+ (void)env_name;
+ return std::nullopt;
+#endif
+}
+
+// OPENVINO_NPUW_GQA_CTX_LEN env override for the static KV-cache reshape target; takes
+// priority over NPUW_LLM_MAX_CONTEXT_LEN.
+std::optional<size_t> gqa_ctx_len_env_override() {
+ static const std::optional<size_t> value = parse_positive_size_env_var("OPENVINO_NPUW_GQA_CTX_LEN");
+ return value;
+}
+
+// OPENVINO_NPUW_GQA_SLIDING_LEN env override: best-effort default sliding-window capacity
+// when a layer has no rt_info/op-attribute signal. Lower priority than NPUW_LLM_SWA_LEN.
+std::optional<size_t> gqa_default_sliding_window_len_env_override() {
+ static const std::optional<size_t> value = parse_positive_size_env_var("OPENVINO_NPUW_GQA_SLIDING_LEN");
+ return value;
+}
+
+// Resolves the sliding-window fallback capacity: NPUW_LLM_SWA_LEN property (if set), else
+// the env override, else nullopt. Never overrides rt_info or the op's own attribute.
+std::optional<size_t> resolve_default_sliding_window_capacity(const ov::AnyMap& properties) {
+ const uint32_t configured = cfg_get<::intel_npu::NPUW_LLM_SWA_LEN>(properties);
+ if (configured != 0) {
+ return static_cast<size_t>(configured);
+ }
+ return gqa_default_sliding_window_len_env_override();
+}
+
void merge_config_with(ov::AnyMap& lhs, const ov::AnyMap& rhs) {
for (const auto& [key, value] : rhs) {
if (auto it = lhs.find(key); it != lhs.end()) {
@@ -36,6 +122,16 @@ enum class GQAModelStage {
GENERATE,
};
+// V2 models ship weights as 2-bit group-quantized (u2) Parameters, unlike V0/V1's u4/u8.
+bool has_2bit_group_quantized_weights(const std::shared_ptr<const ov::Model>& model) {
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_element_type() == ov::element::u2) {
+ return true;
+ }
+ }
+ return false;
+}
+
std::pair<ov::AnyMap, GQAModelStage> with_gqa_defaults(const std::shared_ptr<ov::Model>& model,
const ov::AnyMap& properties) {
const auto detect_gqa_model_stage = [&]() {
@@ -122,12 +218,16 @@ std::pair<ov::AnyMap, GQAModelStage> with_gqa_defaults(const std::shared_ptr<ov:
return false;
};
- ov::AnyMap config = {
- {"NPUW_ONLINE_PIPELINE", "REP"},
- {std::string(::intel_npu::NPUW_DEVICES::key()), "NPU"},
- {ov::cache_mode.name(), ov::CacheMode::OPTIMIZE_SPEED},
- {std::string(::intel_npu::NPUW_UNQDQ::key()), "YES"},
- };
+ // V0/V1 are pre-assembled GQA graphs that online partitioning would only get in the way
+ // of. V2 (2-bit group-quantized weights) still benefits from online partitioning, so it
+ // keeps the default pipeline (REG) instead of being forced to NONE.
+ ov::AnyMap config = {{"NPU_COMPILER_DYNAMIC_QUANTIZATION", "YES"},
+ {std::string(::intel_npu::NPUW_DEVICES::key()), "NPU"},
+ {ov::cache_mode.name(), ov::CacheMode::OPTIMIZE_SPEED},
+ {std::string(::intel_npu::NPUW_UNQDQ::key()), "YES"}};
+ if (!has_2bit_group_quantized_weights(model)) {
+ config.emplace("NPUW_ONLINE_PIPELINE", "NONE");
+ }
const auto stage = detect_gqa_model_stage();
if (stage == GQAModelStage::PREFILL) {
@@ -159,19 +259,38 @@ std::pair<ov::AnyMap, GQAModelStage> with_gqa_defaults(const std::shared_ptr<ov:
LOG_INFO("GQA model stage unknown; FOLD disabled");
}
merge_config_with(config, properties);
+ // LLM-only option; the inner CompiledModel only registers ROOT options.
+ config.erase(std::string(::intel_npu::NPUW_LLM_MAX_CONTEXT_LEN::key()));
+ config.erase(std::string(::intel_npu::NPUW_LLM_SWA_LEN::key()));
return {config, stage};
}
} // namespace
+// Prints a "[GQA-TRACE]" line when OPENVINO_NPUW_GQA_LOG=1 is set; no-op otherwise.
+// `msg` is a chain of `<<`-streamed expressions. Developer builds only.
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+# define GQA_TRACE(msg) \
+ do { \
+ if (gqa_trace_enabled()) { \
+ std::cout << "[GQA-TRACE] " << msg << std::endl; \
+ } \
+ } while (0)
+#else
+# define GQA_TRACE(msg)
+#endif
+
ov::npuw::GQACompiledModel::PreparedState ov::npuw::GQACompiledModel::prepare(const std::shared_ptr<ov::Model>& model,
const ov::AnyMap& properties) {
auto [prepared_properties, stage] = with_gqa_defaults(model, properties);
+ static std::atomic<std::size_t> mcount{0u};
+
model->set_friendly_name(model->get_friendly_name() + "_gqa_" +
(stage == GQAModelStage::PREFILL ? "prefill"
: stage == GQAModelStage::GENERATE ? "generate"
- : "unknown"));
+ : "unknown") +
+ std::to_string(mcount++));
// Untangle shared scale constants so every DequantizeLinear Multiply
// gets its own copy. Some exporters reuse a single scale node across
@@ -191,7 +310,29 @@ ov::npuw::GQACompiledModel::PreparedState ov::npuw::GQACompiledModel::prepare(co
ov::npuw::CollapseUNQDQ collapse_unqdq;
collapse_unqdq.run_on_model(model);
}
- return {model, std::move(prepared_properties)};
+
+ // Reshape kv-cache to static, if any
+ std::shared_ptr<ov::Model> compiled_model = model;
+ std::unordered_map<std::string, size_t> dynamic_kv_cache_axes;
+ uint32_t effective_max_context_len = cfg_get<::intel_npu::NPUW_LLM_MAX_CONTEXT_LEN>(properties);
+ uint32_t effective_sliding_window_capacity = 0;
+ if (has_dynamic_max_seq_len(model)) {
+ const size_t max_seq_len = gqa_ctx_len_env_override().value_or(effective_max_context_len);
+ effective_max_context_len = static_cast<uint32_t>(max_seq_len);
+ compiled_model = model->clone();
+ const auto default_sliding_window_capacity = resolve_default_sliding_window_capacity(properties);
+ effective_sliding_window_capacity = static_cast<uint32_t>(default_sliding_window_capacity.value_or(0));
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(max_seq_len, default_sliding_window_capacity);
+ reshape_to_static_gqa.run_on_model(compiled_model);
+ dynamic_kv_cache_axes = reshape_to_static_gqa.dynamic_kv_cache_axes();
+ }
+
+ return {model,
+ compiled_model,
+ std::move(prepared_properties),
+ std::move(dynamic_kv_cache_axes),
+ effective_max_context_len,
+ effective_sliding_window_capacity};
}
std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::GQACompiledModel::make_compiled_model(
@@ -201,6 +342,211 @@ std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::GQACompiledModel::make_compi
return std::make_shared<ov::npuw::CompiledModel>(model, plugin, properties);
}
+namespace {
+
+// Resolves the Parameter feeding the GQA op's TOTAL_SEQUENCE_LENGTH input, used to
+// compute an accurate present_key/present_value length at infer() time.
+std::optional<std::string> find_total_sequence_length_param_name(const std::shared_ptr<const ov::Model>& model) {
+ using ov::op::internal::GroupQueryAttention;
+ using ov::op::internal::GroupQueryAttentionInputs;
+ constexpr size_t total_seq_len_idx = static_cast<size_t>(GroupQueryAttentionInputs::TOTAL_SEQUENCE_LENGTH);
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (!gqa || gqa->get_input_size() <= total_seq_len_idx) {
+ continue;
+ }
+ if (auto param =
+ ov::npuw::util::trace_back_to_parameter(gqa->input_value(total_seq_len_idx).get_node_shared_ptr())) {
+ return param->get_friendly_name();
+ }
+ }
+ return std::nullopt;
+}
+
+// Detects present_key/present_value names (underscore and HF-ONNX dot style). Shared by
+// identify_case() and find_dynamic_kv_cache_output_axes() so both agree on a match.
+bool is_present_kv_cache_output_name(const std::string& name) {
+ return ov::npuw::util::contains_ignore_case(name, "present_key") ||
+ ov::npuw::util::contains_ignore_case(name, "present_value") ||
+ ov::npuw::util::contains_ignore_case(name, "present.");
+}
+
+// True if `gqa` is well-formed enough to count as real GQA evidence. Shared by
+// find_valid_gqa_op() and find_all_valid_gqa_ops().
+bool is_valid_gqa_op(const ov::op::internal::GroupQueryAttention& gqa) {
+ using ov::op::internal::GroupQueryAttentionInputs;
+ constexpr size_t mandatory_inputs = static_cast<size_t>(GroupQueryAttentionInputs::TOTAL_SEQUENCE_LENGTH) + 1;
+
+ const auto num_heads = gqa.get_num_heads();
+ const auto kv_num_heads = gqa.get_kv_num_heads();
+ if (num_heads <= 0 || kv_num_heads <= 0 || num_heads % kv_num_heads != 0 ||
+ gqa.get_input_size() < mandatory_inputs) {
+ return false; // malformed instance, doesn't count as evidence
+ }
+ if (gqa.get_do_rotary() && gqa.get_input_size() <= static_cast<size_t>(GroupQueryAttentionInputs::SIN_CACHE)) {
+ return false; // rotary requires the cos/sin cache inputs
+ }
+ return true;
+}
+
+std::vector<std::shared_ptr<ov::op::internal::GroupQueryAttention>> find_all_valid_gqa_ops(
+ const std::shared_ptr<const ov::Model>& model) {
+ using ov::op::internal::GroupQueryAttention;
+ std::vector<std::shared_ptr<GroupQueryAttention>> result;
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (gqa && is_valid_gqa_op(*gqa)) {
+ result.push_back(std::move(gqa));
+ }
+ }
+ return result;
+}
+
+std::shared_ptr<ov::op::internal::GroupQueryAttention> find_valid_gqa_op(
+ const std::shared_ptr<const ov::Model>& model) {
+ using ov::op::internal::GroupQueryAttention;
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (gqa && is_valid_gqa_op(*gqa)) {
+ return gqa;
+ }
+ }
+ return nullptr;
+}
+
+} // namespace
+
+bool ov::npuw::GQACompiledModel::supports(const std::shared_ptr<const ov::Model>& model) {
+ // identify_case() classifies GQA family regardless of dynamic shapes; this wrapper is
+ // only needed when max_seq_len is actually dynamic.
+ return identify_case(model) != Case::Unknown && has_dynamic_max_seq_len(model);
+}
+
+ov::npuw::GQACompiledModel::Case ov::npuw::GQACompiledModel::identify_case(
+ const std::shared_ptr<const ov::Model>& model) {
+ auto gqa = find_valid_gqa_op(model);
+ if (!gqa) {
+ return Case::Unknown;
+ }
+
+ // Each matched name must also be forward-reachable to the GQA op (not just same-named).
+ const auto* gqa_node = gqa.get();
+
+ // V1 uses `position_ids` for RoPE; V0/V2 use `past_seq_len`/`total_seq_len` instead.
+ // V2 is further distinguished by 2-bit group-quantized (u2) weights.
+ bool has_activation_input = false;
+ bool has_position_ids = false;
+ bool has_seq_len_signal = false;
+ bool has_past_kv_cache = false;
+ for (const auto& parameter : model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (!ov::npuw::util::reaches(parameter.get(), gqa_node)) {
+ continue;
+ }
+ has_activation_input = has_activation_input || (name == "input_hidden_states" || name == "input_ids");
+ has_position_ids = has_position_ids || (name == "position_ids");
+ has_seq_len_signal = has_seq_len_signal || (name == "past_seq_len") || (name == "total_seq_len");
+ has_past_kv_cache = has_past_kv_cache || util::contains_ignore_case(name, "past_key") ||
+ util::contains_ignore_case(name, "past_value");
+ }
+ if (!has_activation_input || !has_past_kv_cache || (!has_position_ids && !has_seq_len_signal)) {
+ return Case::Unknown;
+ }
+
+ bool has_present_kv_cache = false;
+ for (const auto& result : model->get_results()) {
+ const auto& name = result->get_friendly_name();
+ if (is_present_kv_cache_output_name(name) && ov::npuw::util::reaches(gqa_node, result.get())) {
+ has_present_kv_cache = true;
+ break;
+ }
+ }
+ if (!has_present_kv_cache) {
+ return Case::Unknown;
+ }
+
+ if (has_position_ids) {
+ return Case::V1;
+ }
+ return has_2bit_group_quantized_weights(model) ? Case::V2 : Case::V0;
+}
+
+bool ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(const std::shared_ptr<const ov::Model>& model) {
+ using ov::op::internal::GroupQueryAttention;
+ using ov::op::internal::GroupQueryAttentionInputs;
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (!gqa) {
+ continue;
+ }
+ for (auto kv_input : {GroupQueryAttentionInputs::PAST_KEY, GroupQueryAttentionInputs::PAST_VALUE}) {
+ const auto& shape = gqa->input_value(static_cast<size_t>(kv_input)).get_partial_shape();
+ if (auto axis = util::find_single_dynamic_axis(shape);
+ axis && util::is_supported_kv_cache_capacity_axis(*axis, shape.size())) {
+ return true;
+ }
+ }
+ // Attention bias shares the KV-cache's max_seq_len dim; capacity is the LAST axis.
+ if (gqa->get_input_size() > static_cast<size_t>(GroupQueryAttentionInputs::ATTENTION_BIAS)) {
+ const auto& bias_shape =
+ gqa->input_value(static_cast<size_t>(GroupQueryAttentionInputs::ATTENTION_BIAS)).get_partial_shape();
+ if (bias_shape.rank().is_static()) {
+ if (auto axis = util::find_single_dynamic_axis(bias_shape); axis && *axis == bias_shape.size() - 1) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+std::unordered_map<std::string, size_t> ov::npuw::GQACompiledModel::find_dynamic_kv_cache_output_axes(
+ const std::vector<ov::Output<const ov::Node>>& outer_outputs) {
+ std::unordered_map<std::string, size_t> result;
+ for (const auto& output : outer_outputs) {
+ const auto& full_name = output.get_node()->get_friendly_name();
+ // ONNX frontend appends "/sink_port_0" to Result names; match before the first '/'.
+ const auto slash_pos = full_name.find('/');
+ const auto bare_name = slash_pos == std::string::npos ? full_name : full_name.substr(0, slash_pos);
+ if (!is_present_kv_cache_output_name(bare_name)) {
+ continue;
+ }
+ auto axis = util::find_single_dynamic_axis(output.get_partial_shape());
+ if (!axis || !util::is_supported_kv_cache_capacity_axis(*axis, output.get_partial_shape().size())) {
+ // No resolvable capacity axis; get_tensor() will fall back.
+ continue;
+ }
+ result.emplace(full_name, *axis);
+ }
+ return result;
+}
+
+std::unordered_map<std::string, std::string> ov::npuw::GQACompiledModel::find_present_to_past_param_names(
+ const std::shared_ptr<const ov::Model>& model) {
+ using ov::op::internal::GroupQueryAttentionInputs;
+ std::unordered_map<std::string, std::string> result;
+ for (const auto& gqa : find_all_valid_gqa_ops(model)) {
+ // Output 1/2 are present_key/present_value, matching PAST_KEY/PAST_VALUE inputs.
+ static constexpr std::pair<size_t, GroupQueryAttentionInputs> kPresentPastPairs[] = {
+ {1, GroupQueryAttentionInputs::PAST_KEY},
+ {2, GroupQueryAttentionInputs::PAST_VALUE},
+ };
+ for (const auto& [output_idx, past_input] : kPresentPastPairs) {
+ const auto past_idx = static_cast<size_t>(past_input);
+ if (gqa->get_output_size() <= output_idx || gqa->get_input_size() <= past_idx) {
+ continue;
+ }
+ auto past_param = ov::npuw::util::trace_back_to_parameter(gqa->input_value(past_idx).get_node_shared_ptr());
+ auto present_result = ov::npuw::util::trace_forward_to_result(gqa->output(output_idx));
+ if (!past_param || !present_result) {
+ continue;
+ }
+ result.emplace(present_result->get_friendly_name(), past_param->get_friendly_name());
+ }
+ }
+ return result;
+}
+
ov::npuw::GQACompiledModel::GQACompiledModel(const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties,
@@ -211,14 +557,149 @@ ov::npuw::GQACompiledModel::GQACompiledModel(PreparedState prepared,
const std::shared_ptr<const ov::IPlugin>& plugin,
CompiledModelFactory factory)
: ov::npuw::ICompiledModel(prepared.model, plugin),
- m_compiled_model(factory(prepared.model, plugin, prepared.properties)) {
- OPENVINO_ASSERT(m_compiled_model != nullptr, "GQACompiledModel requires a valid inner compiled model");
+ m_inner_compiled_model(factory(prepared.compiled_model, plugin, prepared.properties)),
+ m_outer_model(prepared.model),
+ m_dynamic_kv_cache_axes(std::move(prepared.dynamic_kv_cache_axes)),
+ m_effective_max_context_len(prepared.effective_max_context_len),
+ m_effective_sliding_window_capacity(prepared.effective_sliding_window_capacity) {
+ OPENVINO_ASSERT(m_inner_compiled_model != nullptr, "GQACompiledModel requires a valid inner compiled model");
+ m_dynamic_kv_cache_output_axes = find_dynamic_kv_cache_output_axes(outputs());
+ m_total_seq_len_param_name = find_total_sequence_length_param_name(m_outer_model);
+ m_present_to_past_param_names = find_present_to_past_param_names(m_outer_model);
+}
+
+// Used by import_model() to wrap a deserialized inner compiled model with the rebuilt
+// outer model, so a cache hit produces a fully functional GQACompiledModel.
+ov::npuw::GQACompiledModel::GQACompiledModel(const std::shared_ptr<ov::Model>& outer_model,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ std::shared_ptr<ov::npuw::ICompiledModel> inner_compiled_model,
+ std::unordered_map<std::string, size_t> dynamic_kv_cache_axes,
+ uint32_t effective_max_context_len,
+ uint32_t effective_sliding_window_capacity,
+ std::optional<std::string> total_seq_len_param_name,
+ std::unordered_map<std::string, std::string> present_to_past_param_names)
+ : ov::npuw::ICompiledModel(outer_model, plugin),
+ m_inner_compiled_model(std::move(inner_compiled_model)),
+ m_outer_model(outer_model),
+ m_dynamic_kv_cache_axes(std::move(dynamic_kv_cache_axes)),
+ m_effective_max_context_len(effective_max_context_len),
+ m_effective_sliding_window_capacity(effective_sliding_window_capacity) {
+ OPENVINO_ASSERT(m_inner_compiled_model != nullptr, "GQACompiledModel requires a valid inner compiled model");
+ m_dynamic_kv_cache_output_axes = find_dynamic_kv_cache_output_axes(outputs());
+ // NOT re-derived via find_total_sequence_length_param_name()/find_present_to_past_param_names()
+ // here: outer_model on this (import) path is a dummy carcass with no real GQA ops, so
+ // those graph-walking helpers would silently find nothing. Use what was serialized
+ // from the original compile, where the real model was available.
+ m_total_seq_len_param_name = std::move(total_seq_len_param_name);
+ m_present_to_past_param_names = std::move(present_to_past_param_names);
+}
+
+// Hand-rolled port serialization instead of ov::pass::Serialize: the IR writer recomputes
+// a Result's shape/type from its input node, which would collapse our dummy-placeholder
+// carcass Results down to the placeholder's shape.
+void ov::npuw::GQACompiledModel::write_port_list(std::ostream& stream,
+ const std::vector<ov::Output<const ov::Node>>& ports) {
+ using namespace ov::npuw::s11n;
+ write(stream, ports.size());
+ for (const auto& port : ports) {
+ write(stream, port.get_node()->get_friendly_name());
+ write(stream, port.get_element_type().to_string());
+ write(stream, port.get_partial_shape().to_string());
+ // Preserve tensor names too: ORT/OVEP match ports by these, not friendly names.
+ write(stream, port.get_names());
+ }
+}
+
+ov::ParameterVector ov::npuw::GQACompiledModel::read_input_port_list(std::istream& stream) {
+ using namespace ov::npuw::s11n;
+ size_t count = 0;
+ read(stream, count);
+ // Guard against a corrupted blob surfacing as an opaque bad_alloc instead of a clear error.
+ OPENVINO_ASSERT(count <= 1024, "GQACompiledModel: implausible outer input port count (", count, ") on import");
+ ov::ParameterVector params;
+ params.reserve(count);
+ for (size_t i = 0; i < count; ++i) {
+ std::string name, elem_type_str, shape_str;
+ std::unordered_set<std::string> tensor_names;
+ read(stream, name);
+ read(stream, elem_type_str);
+ read(stream, shape_str);
+ read(stream, tensor_names);
+ auto param =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::Type(elem_type_str), ov::PartialShape(shape_str));
+ param->set_friendly_name(name);
+ param->output(0).get_tensor().set_names(tensor_names);
+ params.push_back(param);
+ }
+ return params;
+}
+
+ov::NodeVector ov::npuw::GQACompiledModel::read_output_port_list(std::istream& stream) {
+ using namespace ov::npuw::s11n;
+ size_t count = 0;
+ read(stream, count);
+ OPENVINO_ASSERT(count <= 1024, "GQACompiledModel: implausible outer output port count (", count, ") on import");
+ ov::NodeVector results;
+ results.reserve(count);
+ for (size_t i = 0; i < count; ++i) {
+ std::string name, elem_type_str, shape_str;
+ std::unordered_set<std::string> tensor_names;
+ read(stream, name);
+ read(stream, elem_type_str);
+ read(stream, shape_str);
+ read(stream, tensor_names);
+ const auto elem_type = ov::element::Type(elem_type_str);
+ // A dummy Constant source, purely so Result has something to wrap -- its own
+ // reported type/shape is overridden right below via a fresh descriptor::Tensor,
+ // matching the pattern used by ov::npuw::orc::serialize(shared_ptr<Node>&).
+ auto dummy_source = std::make_shared<ov::op::v0::Constant>(elem_type, ov::Shape{1});
+ auto result = std::make_shared<ov::op::v0::Result>(dummy_source);
+ result->output(0).set_tensor_ptr(
+ std::make_shared<ov::descriptor::Tensor>(elem_type, ov::PartialShape(shape_str), tensor_names));
+ result->set_friendly_name(name);
+ results.push_back(result);
+ }
+ return results;
}
void ov::npuw::GQACompiledModel::export_model(std::ostream& stream) const {
+ LOG_INFO("Exporting GQACompiledModel...");
+ LOG_BLOCK();
+ GQA_TRACE("GQACompiledModel::export_model() begin, m_dynamic_kv_cache_axes has " << m_dynamic_kv_cache_axes.size()
+ << " entries:");
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ for (const auto& [name, axis] : m_dynamic_kv_cache_axes) {
+ GQA_TRACE(" '" << name << "' -> axis " << axis);
+ }
+#endif
using namespace ov::npuw::s11n;
write_header(stream, NPUW_GQA_COMPILED_MODEL_INDICATOR);
- m_compiled_model->export_model(stream);
+
+ // Preserve the outer-facing ports and axis map so import_model() can rebuild an
+ // equivalent GQACompiledModel, not just the bare inner CompiledModel.
+ auto outer_inputs = inputs();
+ auto outer_outputs = outputs();
+ GQACompiledModel::write_port_list(stream, outer_inputs);
+ GQACompiledModel::write_port_list(stream, outer_outputs);
+ write(stream, m_dynamic_kv_cache_axes);
+ write(stream, m_effective_max_context_len);
+ write(stream, m_effective_sliding_window_capacity);
+ // Written here (from the real model, available at this point) rather than
+ // re-derived by import_model() from its dummy carcass outer_model, which has no
+ // actual GroupQueryAttention ops for the graph-walking find_*() helpers to find.
+ write(stream, m_total_seq_len_param_name);
+ write(stream, m_present_to_past_param_names);
+ GQA_TRACE("GQACompiledModel::export_model() -> wrote "
+ << outer_inputs.size() << " outer inputs, " << outer_outputs.size() << " outer outputs, "
+ << m_dynamic_kv_cache_axes.size()
+ << " dynamic-axis entries, effective_max_context_len=" << m_effective_max_context_len
+ << ", effective_sliding_window_capacity=" << m_effective_sliding_window_capacity
+ << ", total_seq_len_param_name=" << m_total_seq_len_param_name.value_or("<none>")
+ << ", present_to_past_param_names has " << m_present_to_past_param_names.size() << " entries"
+ << "; delegating to inner m_inner_compiled_model->export_model()");
+ m_inner_compiled_model->export_model(stream);
+ LOG_INFO("Done");
+ GQA_TRACE("GQACompiledModel::export_model() done");
}
std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::GQACompiledModel::import_model(
@@ -227,45 +708,127 @@ std::shared_ptr<ov::npuw::ICompiledModel> ov::npuw::GQACompiledModel::import_mod
const ov::AnyMap& properties) {
LOG_INFO("Deserializing GQACompiledModel...");
LOG_BLOCK();
+ GQA_TRACE("GQACompiledModel::import_model() begin");
using namespace ov::npuw::s11n;
read_and_check_header(stream, NPUW_GQA_COMPILED_MODEL_INDICATOR, "GQACompiledModel");
- // The rest of the stream is the inner CompiledModel ORC blob.
- // After import it is fully self-contained; no outer GQA wrapper is needed
- // because the partitioning is already baked in and port mappings are consistent.
- return ov::npuw::CompiledModel::import_model(stream, plugin, properties);
+ // Rebuild the outer-facing model (dynamic axes restored) exactly as before export.
+ ov::ParameterVector outer_parameters;
+ ov::NodeVector outer_results;
+ std::unordered_map<std::string, size_t> dynamic_kv_cache_axes;
+ uint32_t effective_max_context_len = 0;
+ uint32_t effective_sliding_window_capacity = 0;
+ std::optional<std::string> total_seq_len_param_name;
+ std::unordered_map<std::string, std::string> present_to_past_param_names;
+ outer_parameters = GQACompiledModel::read_input_port_list(stream);
+ outer_results = GQACompiledModel::read_output_port_list(stream);
+ read(stream, dynamic_kv_cache_axes);
+ read(stream, effective_max_context_len);
+ read(stream, effective_sliding_window_capacity);
+ read(stream, total_seq_len_param_name);
+ read(stream, present_to_past_param_names);
+
+ GQA_TRACE(" read " << outer_parameters.size() << " outer parameters, " << outer_results.size()
+ << " outer results, " << dynamic_kv_cache_axes.size() << " dynamic-axis entries:");
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ for (const auto& [name, axis] : dynamic_kv_cache_axes) {
+ GQA_TRACE(" '" << name << "' -> axis " << axis);
+ }
+#endif
+
+ auto outer_model =
+ std::make_shared<ov::Model>(ov::as_output_vector(outer_results), outer_parameters, "gqa_outer_model");
+
+ // The rest of the stream is the self-contained inner CompiledModel ORC blob.
+ auto inner_compiled_model = ov::npuw::CompiledModel::import_model(stream, plugin, properties);
+ NPUW_ASSERT(inner_compiled_model != nullptr);
+ GQA_TRACE(" inner CompiledModel imported @ "
+ << inner_compiled_model.get()
+ << "; wrapping it back into a GQACompiledModel so dynamic KV-cache/attention-bias reshape "
+ "survives the cache hit");
+
+ return std::shared_ptr<GQACompiledModel>(new GQACompiledModel(outer_model,
+ plugin,
+ std::move(inner_compiled_model),
+ std::move(dynamic_kv_cache_axes),
+ effective_max_context_len,
+ effective_sliding_window_capacity,
+ std::move(total_seq_len_param_name),
+ std::move(present_to_past_param_names)));
}
std::shared_ptr<const ov::Model> ov::npuw::GQACompiledModel::get_runtime_model() const {
- return m_compiled_model->get_runtime_model();
+ return m_outer_model;
}
void ov::npuw::GQACompiledModel::set_property(const ov::AnyMap& properties) {
- m_compiled_model->set_property(properties);
+ m_inner_compiled_model->set_property(properties);
}
ov::Any ov::npuw::GQACompiledModel::get_property(const std::string& name) const {
- return m_compiled_model->get_property(name);
+ // NPUW_LLM_MAX_CONTEXT_LEN/NPUW_LLM_SWA_LEN are stripped from the inner model's
+ // properties (ROOT-only options); answer them directly from the effective values
+ // actually used.
+ if (name == std::string(::intel_npu::NPUW_LLM_MAX_CONTEXT_LEN::key())) {
+ return m_effective_max_context_len;
+ }
+ if (name == std::string(::intel_npu::NPUW_LLM_SWA_LEN::key())) {
+ return m_effective_sliding_window_capacity;
+ }
+ return m_inner_compiled_model->get_property(name);
}
std::shared_ptr<ov::ISyncInferRequest> ov::npuw::GQACompiledModel::create_sync_infer_request() const {
+ GQA_TRACE("GQACompiledModel::create_sync_infer_request() called");
auto self = std::static_pointer_cast<const GQACompiledModel>(shared_from_this());
- return std::make_shared<ov::npuw::GQAInferRequest>(std::move(self));
+ auto request = std::make_shared<ov::npuw::GQAInferRequest>(std::move(self));
+ GQA_TRACE("GQACompiledModel::create_sync_infer_request() -> GQAInferRequest created @ " << request.get());
+ return request;
}
ov::npuw::GQAInferRequest::GQAInferRequest(std::shared_ptr<const GQACompiledModel> compiled_model)
: ov::ISyncInferRequest(compiled_model),
- m_compiled_model(std::move(compiled_model)) {}
+ m_compiled_model(std::move(compiled_model)) {
+ GQA_TRACE("GQAInferRequest::GQAInferRequest() ctor, dynamic-axis map has "
+ << m_compiled_model->m_dynamic_kv_cache_axes.size() << " entries");
+}
void ov::npuw::GQAInferRequest::ensure_inner_request_locked() const {
if (m_inner_request == nullptr) {
- m_inner_request = m_compiled_model->m_compiled_model->create_infer_request();
+ m_inner_request = m_compiled_model->m_inner_compiled_model->create_infer_request();
OPENVINO_ASSERT(m_inner_request != nullptr, "GQA infer request requires a valid inner request");
+ const auto& inner_model = m_compiled_model->m_inner_compiled_model;
+ GQA_TRACE("ensure_inner_request_locked(): created inner infer request @ "
+ << m_inner_request.get() << ", inner model has " << inner_model->inputs().size() << " inputs, "
+ << inner_model->outputs().size() << " outputs");
+
+ // Zero-initialize every dynamic-axis KV-cache/bias input's full capacity, once.
+ size_t zeroed_count = 0;
+ for (const auto& kv : m_compiled_model->m_dynamic_kv_cache_axes) {
+ // Pre-C++20: structured bindings can't be captured by lambdas, so use a named local.
+ const auto& name = kv.first;
+ auto input_it = std::find_if(inner_model->inputs().begin(),
+ inner_model->inputs().end(),
+ [&name](const ov::Output<const ov::Node>& input) {
+ return input.get_node()->get_friendly_name() == name;
+ });
+ if (input_it == inner_model->inputs().end()) {
+ continue;
+ }
+ auto tensor = m_inner_request->get_tensor(*input_it);
+ if (!tensor || tensor->get_byte_size() == 0) {
+ continue;
+ }
+ std::memset(tensor->data(), 0, tensor->get_byte_size());
+ ++zeroed_count;
+ }
+ GQA_TRACE("ensure_inner_request_locked(): zero-initialized " << zeroed_count << " dynamic-axis input(s)");
}
}
+// FIXME: Online search every time; a static mapping could be built once.
const ov::Output<const ov::Node>& ov::npuw::GQAInferRequest::map_port_locked(
const ov::Output<const ov::Node>& port) const {
ensure_inner_request_locked();
@@ -291,23 +854,433 @@ const ov::Output<const ov::Node>& ov::npuw::GQAInferRequest::map_port_locked(
OPENVINO_THROW("Unknown GQA infer request port: ", port.get_any_name());
}
+// Diagnostic-only: dumps every known sequence-length-style input right before infer().
+// Names are probed since exporters name/omit them differently.
+void ov::npuw::GQAInferRequest::trace_sequence_length_inputs_locked() const {
+ if (!gqa_trace_enabled()) {
+ return;
+ }
+ static constexpr std::array<const char*, 3> kCandidateNames{"seqlens_k", "past_seq_len", "total_seq_len"};
+ const auto& outer_inputs = m_compiled_model->inputs();
+ for (const auto* candidate : kCandidateNames) {
+ auto it = std::find_if(outer_inputs.begin(), outer_inputs.end(), [&](const auto& input) {
+ return input.get_node()->get_friendly_name() == candidate;
+ });
+ if (it == outer_inputs.end()) {
+ continue;
+ }
+ const auto& tensor = m_inner_request->get_tensor(map_port_locked(*it));
+ [[maybe_unused]] const auto value = ov::npuw::read_scalar_int_tensor(tensor);
+ GQA_TRACE("pre-infer sequence-length input '" << candidate << "' shape=" << tensor->get_shape() << " value="
+ << (value ? std::to_string(*value) : std::string("<n/a>")));
+ }
+}
+
+// Diagnostic-only: dumps a min/max/non-zero-count summary for every dynamic-axis input
+// that isn't a KV-cache tensor (i.e. the attention bias/mask).
+void ov::npuw::GQAInferRequest::trace_attention_mask_stats_locked() const {
+ if (!gqa_trace_enabled()) {
+ return;
+ }
+ const auto& outer_inputs = m_compiled_model->inputs();
+ for (const auto& kv : m_compiled_model->m_dynamic_kv_cache_axes) {
+ // Pre-C++20: structured bindings can't be captured by lambdas, so use named locals.
+ const auto& name = kv.first;
+ [[maybe_unused]] const auto axis = kv.second; // only referenced by GQA_TRACE below
+ if (ov::npuw::util::contains_ignore_case(name, "past_key") ||
+ ov::npuw::util::contains_ignore_case(name, "past_value")) {
+ continue; // KV-cache tensor, not the mask/bias -- already traced/handled elsewhere
+ }
+ auto it = std::find_if(outer_inputs.begin(), outer_inputs.end(), [&name](const auto& input) {
+ return input.get_node()->get_friendly_name() == name;
+ });
+ if (it == outer_inputs.end()) {
+ continue;
+ }
+ const auto& tensor = m_inner_request->get_tensor(map_port_locked(*it));
+ GQA_TRACE("pre-infer attention-bias/mask input '" << name << "' axis=" << axis
+ << " shape=" << tensor->get_shape() << " "
+ << ov::npuw::tensor_stats_string(tensor));
+ }
+}
+
void ov::npuw::GQAInferRequest::infer() {
std::lock_guard<std::mutex> lock(m_mutex);
ensure_inner_request_locked();
- m_inner_request->infer();
+ sync_dynamic_kv_cache_tensors_locked();
+ trace_sequence_length_inputs_locked();
+ trace_attention_mask_stats_locked();
+ GQA_TRACE("GQAInferRequest::infer() -> delegating to inner request @ " << m_inner_request.get());
+ // TODO: enclose with try/catch only when tracing is enabled.
+ try {
+ m_inner_request->infer();
+ } catch (const std::exception& ex) {
+ // Surface the real exception message before it propagates and gets wrapped away.
+ (void)ex; // only referenced by GQA_TRACE, a no-op outside NPU_PLUGIN_DEVELOPER_BUILD
+ GQA_TRACE("GQAInferRequest::infer() -> inner request infer() THREW: " << ex.what());
+ throw;
+ } catch (...) {
+ GQA_TRACE("GQAInferRequest::infer() -> inner request infer() THREW an unknown exception");
+ throw;
+ }
+ GQA_TRACE("GQAInferRequest::infer() -> inner request infer() returned");
+ refresh_present_tensors_locked();
+}
+
+// Reads the live value of the GQA op's TOTAL_SEQUENCE_LENGTH Parameter from the inner
+// request's tensor. Returns nullopt if unresolved or not a readable scalar.
+std::optional<size_t> ov::npuw::GQAInferRequest::read_total_sequence_length_locked() const {
+ const auto& param_name = m_compiled_model->m_total_seq_len_param_name;
+ if (!param_name) {
+ return std::nullopt;
+ }
+ const auto& outer_inputs = m_compiled_model->inputs();
+ auto port_it = std::find_if(outer_inputs.begin(), outer_inputs.end(), [&](const auto& input) {
+ return input.get_node()->get_friendly_name() == *param_name;
+ });
+ if (port_it == outer_inputs.end()) {
+ return std::nullopt;
+ }
+ const auto& tensor = m_inner_request->get_tensor(map_port_locked(*port_it));
+ auto value = ov::npuw::read_scalar_int_tensor(tensor);
+ if (!value || *value < 0) {
+ return std::nullopt;
+ }
+ return static_cast<size_t>(*value);
+}
+
+void ov::npuw::GQAInferRequest::copy_kv_cache_prefix(const ov::SoPtr<ov::ITensor>& src,
+ const ov::SoPtr<ov::ITensor>& dst,
+ size_t axis) {
+ OPENVINO_ASSERT(src->get_element_type() == dst->get_element_type());
+ const auto& src_shape = src->get_shape();
+ const auto& dst_shape = dst->get_shape();
+ OPENVINO_ASSERT(src_shape.size() == 4u && dst_shape.size() == 4u, "Expected rank-4 KV-cache tensors");
+ OPENVINO_ASSERT(axis == 2 || axis == 3, "Unsupported dynamic KV-cache axis ", axis);
+ if (axis == 2) {
+ // Axis 2 (not transposed): reuse the per-plane KV-cache copy helper.
+ ov::npuw::util::copy_by_planes(src, dst);
+ return;
+ }
+ // Axis 3 (transposed V-cache): copy each row's valid-length prefix, left-aligned.
+ OPENVINO_ASSERT(src_shape[0] == 1u, "Expected batch size 1");
+ OPENVINO_ASSERT(src_shape[0] == dst_shape[0] && src_shape[1] == dst_shape[1] && src_shape[2] == dst_shape[2]);
+ const auto* src_p = reinterpret_cast<const uint8_t*>(src->data());
+ auto* dst_p = reinterpret_cast<uint8_t*>(dst->data());
+ const auto rows = src_shape[1] * src_shape[2];
+ const auto src_row_stride = src->get_strides()[2];
+ const auto dst_row_stride = dst->get_strides()[2];
+ // Use the tensors' reported shape, not get_strides(): a ROI view's stride reflects
+ // the parent's full row length, not the (possibly shorter) valid length.
+ const auto row_bytes = std::min(src_shape[3], dst_shape[3]) * src->get_element_type().size();
+ for (size_t i = 0; i < rows; ++i) {
+ std::copy_n(src_p, row_bytes, dst_p);
+ src_p += src_row_stride;
+ dst_p += dst_row_stride;
+ }
+}
+
+// Refreshes outer present_key/present_value tensors after infer(): copies the inner
+// buffer's valid prefix into a dense tensor, or aliases it directly when the whole
+// buffer is already valid and no copy is needed (see m_dynamic_kv_cache_output_aliased).
+//
+// Each output name is in one of 3 states across infer() calls: (1) never allocated yet,
+// (2) aliased -- m_dynamic_kv_cache_output_tensors[name] IS the inner request's own live
+// buffer (valid_len == capacity, nothing to exclude), or (3) private -- a separate,
+// densely-shaped buffer holding just the valid prefix (valid_len < capacity). The state
+// can flip either way between calls as valid_len/capacity change. Below,
+// m_dynamic_kv_cache_output_aliased.erase(name) reports (via its return value) whether
+// state (2) applied a moment ago: if so, the cached tensor is literally the inner
+// buffer and must be discarded and freshly allocated rather than reused, since writing
+// through it would corrupt the inner request's working buffer; otherwise it is already
+// a private buffer and can simply be resized in place, keeping its identity stable for
+// callers that cache the tensor pointer/object.
+void ov::npuw::GQAInferRequest::refresh_present_tensors_locked() const {
+ const auto& output_axes = m_compiled_model->m_dynamic_kv_cache_output_axes;
+ if (output_axes.empty()) {
+ return;
+ }
+
+ const auto& outer_outputs = m_compiled_model->outputs();
+ for (const auto& kv : output_axes) {
+ // Pre-C++20: structured bindings can't be captured by lambdas, so use named locals.
+ const auto& name = kv.first;
+ const auto axis = kv.second;
+ auto port_it = std::find_if(outer_outputs.begin(), outer_outputs.end(), [&](const auto& output) {
+ return output.get_node()->get_friendly_name() == name;
+ });
+ if (port_it == outer_outputs.end()) {
+ continue;
+ }
+ if (m_dynamic_kv_cache_output_externally_set.count(name) != 0) {
+ // set_tensor() forwarded this exact buffer to the inner request (shape is
+ // asserted to match its compiled capacity); the inner request already wrote
+ // directly into it during infer(), nothing to copy.
+ continue;
+ }
+ const auto inner_tensor = m_inner_request->get_tensor(map_port_locked(*port_it));
+ const auto capacity = inner_tensor->get_shape().at(axis);
+
+ // Present length = max(past_len, total_sequence_length), not just past_len (which
+ // misses rows just appended). Present->past mapping comes from the GQA op's own
+ // graph connections, not string rewriting (breaks for dot-style naming).
+ // total_sequence_length is read independently of past_len -- the caller may
+ // legitimately never have touched the past_key/value input at all (e.g. it
+ // queries every output tensor up front, before any set_tensor()) and
+ // total_sequence_length alone is still enough to answer accurately instead of
+ // silently falling back to the full, un-copied capacity.
+ std::optional<size_t> past_len;
+ const auto& present_to_past = m_compiled_model->m_present_to_past_param_names;
+ if (auto past_name_it = present_to_past.find(name); past_name_it != present_to_past.end()) {
+ if (auto past_it = m_dynamic_kv_cache_tensors.find(past_name_it->second);
+ past_it != m_dynamic_kv_cache_tensors.end()) {
+ past_len = past_it->second->get_shape().at(axis);
+ }
+ }
+ const auto total_len = read_total_sequence_length_locked();
+ size_t valid_len = capacity;
+ if (past_len || total_len) {
+ valid_len = std::min<size_t>(capacity, std::max<size_t>(past_len.value_or(0u), total_len.value_or(0u)));
+ }
+
+ if (valid_len == capacity) {
+ // Whole buffer valid, no copy needed: alias the outer tensor onto the inner
+ // buffer directly. NEVER set_shape() this entry while aliased -- it's the
+ // inner request's own live working buffer.
+ m_dynamic_kv_cache_output_tensors[name] = inner_tensor;
+ m_dynamic_kv_cache_output_aliased.insert(name);
+ continue;
+ }
+
+ auto out_shape = inner_tensor->get_shape();
+ out_shape.at(axis) = valid_len;
+
+ auto& outer_tensor = m_dynamic_kv_cache_output_tensors[name];
+ const bool was_aliased = m_dynamic_kv_cache_output_aliased.erase(name) != 0;
+ if (!outer_tensor || was_aliased) {
+ // Never allocated, or aliased onto the inner tensor: allocate a fresh,
+ // privately-owned buffer instead of resizing in place.
+ //
+ // Investigated using the inner model's own device context here (the same
+ // remote/host-tensor mechanism as the weights bank, via
+ // ov::npuw::util::allocMem()) instead of a plain host allocation. Measured
+ // as a ~2x decode-throughput regression end-to-end: unlike weights (written
+ // once, read many times), this buffer is rewritten by copy_kv_cache_prefix()
+ // on every refresh, and repeated host-side writes into NPU-host-accessible
+ // memory were far slower than into plain process memory. Kept as a plain
+ // CPU allocation.
+ outer_tensor = ov::SoPtr<ov::ITensor>(ov::make_tensor(inner_tensor->get_element_type(), out_shape));
+ } else if (outer_tensor->get_shape() != out_shape) {
+ // Resize in place to keep this tensor's identity stable across calls (cached
+ // IO-binding callers may hold onto the returned object/data pointer).
+ outer_tensor->set_shape(out_shape);
+ }
+
+ // A strided ROI view over the inner buffer's valid prefix, only used internally
+ // for copy_kv_cache_prefix -- never handed to the caller.
+ ov::Coordinate begin(inner_tensor->get_shape().size(), 0);
+ ov::Coordinate end(inner_tensor->get_shape());
+ end.at(axis) = valid_len;
+ auto inner_view = ov::SoPtr<ov::ITensor>(ov::make_tensor(inner_tensor._ptr, begin, end));
+ ov::npuw::GQAInferRequest::copy_kv_cache_prefix(inner_view, outer_tensor, axis);
+ }
+}
+
+ov::SoPtr<ov::ITensor> ov::npuw::GQAInferRequest::get_present_tensor_locked(const std::string& name) const {
+ auto it = m_dynamic_kv_cache_output_tensors.find(name);
+ if (it != m_dynamic_kv_cache_output_tensors.end()) {
+ return it->second;
+ }
+ // infer() hasn't run yet; ORT/OVEP may query output tensors before the first infer().
+ // Fall back to the inner request's raw tensor instead of hard-failing.
+ GQA_TRACE("get_present_tensor_locked('"
+ << name << "'): no refreshed tensor yet (infer() not called?), falling back to inner request tensor");
+ const auto& outer_outputs = m_compiled_model->outputs();
+ auto port_it = std::find_if(outer_outputs.begin(), outer_outputs.end(), [&](const auto& output) {
+ return output.get_node()->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(port_it != outer_outputs.end(), "GQA present output '", name, "' port not found");
+ return m_inner_request->get_tensor(map_port_locked(*port_it));
}
ov::SoPtr<ov::ITensor> ov::npuw::GQAInferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {
std::lock_guard<std::mutex> lock(m_mutex);
ensure_inner_request_locked();
- return m_inner_request->get_tensor(map_port_locked(port));
+
+ const auto& name = port.get_node()->get_friendly_name();
+ GQA_TRACE("GQAInferRequest::get_tensor(port='" << name << "')");
+ if (m_compiled_model->m_dynamic_kv_cache_axes.count(name) != 0) {
+ // The inner tensor is the static-capacity buffer, not what the caller set; hand
+ // back the exact user-owned tensor instead.
+ auto it = m_dynamic_kv_cache_tensors.find(name);
+ if (it == m_dynamic_kv_cache_tensors.end()) {
+ // get_tensor() before set_tensor() (IO-binding pattern): allocate a private
+ // tensor. Dynamic dims are zeroed (static dims keep real extent), matching
+ // intel_cpu's convention for a never-set dynamic tensor -- a full-capacity
+ // shape would wrongly look "already populated". Caller must set_shape()
+ // before writing.
+ const auto& inner_tensor = m_inner_request->get_tensor(map_port_locked(port));
+ const auto& port_shape = port.get_partial_shape();
+ ov::Shape private_shape;
+ private_shape.reserve(port_shape.size());
+ for (const auto& dim : port_shape) {
+ private_shape.push_back(dim.is_static() ? dim.get_length() : 0u);
+ }
+ // Same reasoning as refresh_present_tensors_locked()'s fresh present buffer:
+ // investigated device-context allocation here too, but kept as a plain CPU
+ // allocation since the host-write path is what matters, not device-read
+ // locality (see that function's comment for the measured regression).
+ auto private_tensor =
+ ov::SoPtr<ov::ITensor>(ov::make_tensor(inner_tensor->get_element_type(), private_shape));
+ it = m_dynamic_kv_cache_tensors.emplace(name, private_tensor).first;
+ GQA_TRACE(
+ " -> no set_tensor() yet, allocated private fallback tensor, shape=" << private_tensor->get_shape());
+ }
+ GQA_TRACE(" -> returning previously set_tensor()'d user tensor, shape=" << it->second->get_shape());
+ return it->second;
+ }
+
+ if (auto out_it = m_compiled_model->m_dynamic_kv_cache_output_axes.find(name);
+ out_it != m_compiled_model->m_dynamic_kv_cache_output_axes.end()) {
+ auto tensor = get_present_tensor_locked(name);
+ GQA_TRACE(" -> returning present output tensor, shape=" << tensor->get_shape());
+ return tensor;
+ }
+
+ auto tensor = m_inner_request->get_tensor(map_port_locked(port));
+ GQA_TRACE(" -> returning inner request tensor, shape=" << tensor->get_shape());
+ return tensor;
}
void ov::npuw::GQAInferRequest::set_tensor(const ov::Output<const ov::Node>& port,
const ov::SoPtr<ov::ITensor>& tensor) {
std::lock_guard<std::mutex> lock(m_mutex);
ensure_inner_request_locked();
- m_inner_request->set_tensor(map_port_locked(port), tensor);
+
+ const auto& name = port.get_node()->get_friendly_name();
+ GQA_TRACE("GQAInferRequest::set_tensor(port='" << name << "', shape=" << tensor->get_shape() << ")");
+
+ // Mark present_* outputs externally owned so refresh_present_tensors_locked() won't
+ // later republish a diverging, separately-copied tensor under this name.
+ if (m_compiled_model->m_dynamic_kv_cache_output_axes.count(name) != 0) {
+ GQA_TRACE(" -> dynamic-axis present output, forwarding to inner request and marking externally owned");
+ // The inner request is bound to a STATIC compiled model: its own set_tensor()
+ // (IBaseInferRequest::set_tensor()) stores whatever it's given with zero shape
+ // validation (check_tensors() is a no-op too), yet the model can only ever
+ // correctly produce/consume its one compiled shape. Fail early instead of
+ // letting a wrong-sized buffer reach the inner request unchecked. (Caller-driven
+ // dynamic present-output sizing below the compiled capacity is a separate,
+ // more involved problem -- tracked separately, not handled here.)
+ const auto& inner_tensor = m_inner_request->get_tensor(map_port_locked(port));
+ OPENVINO_ASSERT(tensor->get_shape() == inner_tensor->get_shape(),
+ "GQA present output '",
+ name,
+ "' shape ",
+ tensor->get_shape(),
+ " does not match the compiled static shape ",
+ inner_tensor->get_shape());
+ m_inner_request->set_tensor(map_port_locked(port), tensor);
+ m_dynamic_kv_cache_output_tensors[name] = tensor;
+ m_dynamic_kv_cache_output_externally_set.insert(name);
+ return;
+ }
+
+ const auto& dynamic_axes = m_compiled_model->m_dynamic_kv_cache_axes;
+ auto it = dynamic_axes.find(name);
+ if (it == dynamic_axes.end()) {
+ GQA_TRACE(" -> not a dynamic-axis input, forwarding to inner request as-is");
+ m_inner_request->set_tensor(map_port_locked(port), tensor);
+ return;
+ }
+
+ // If the caller's tensor is EXACTLY the compiled static capacity, there's no prefix
+ // to carve out: alias the inner request directly onto it and skip the copy.
+ // Otherwise keep the inner tensor and defer the prefix copy to infer() time.
+ const auto axis = it->second;
+ const auto& inner_tensor = m_inner_request->get_tensor(map_port_locked(port));
+ const auto requested_len = tensor->get_shape().at(axis);
+ const auto capacity = inner_tensor->get_shape().at(axis);
+ GQA_TRACE(" -> dynamic-axis input, axis=" << axis << " requested_len=" << requested_len << " capacity="
+ << capacity << " inner_tensor_shape=" << inner_tensor->get_shape());
+ OPENVINO_ASSERT(requested_len <= capacity,
+ "GQA KV-cache '",
+ name,
+ "' length ",
+ requested_len,
+ " exceeds the static capacity (",
+ capacity,
+ ") it was compiled with");
+ if (requested_len == capacity) {
+ // Exact match: alias instead of copying, nothing to carve out.
+ if (m_dynamic_kv_cache_input_aliased.count(name) == 0) {
+ // First alias of this port: stash the inner request's own buffer so a later,
+ // shorter set_tensor() can restore it.
+ m_dynamic_kv_cache_private_buffers[name] = inner_tensor;
+ }
+ m_inner_request->set_tensor(map_port_locked(port), tensor);
+ m_dynamic_kv_cache_tensors[name] = tensor;
+ m_dynamic_kv_cache_input_aliased.insert(name);
+ GQA_TRACE(" -> requested_len == capacity, aliased inner request tensor directly (no copy)");
+ return;
+ }
+ if (m_dynamic_kv_cache_input_aliased.erase(name) != 0) {
+ // Previously aliased onto a now-stale caller tensor; restore the inner request's
+ // own private buffer before this shorter tensor is used.
+ auto priv_it = m_dynamic_kv_cache_private_buffers.find(name);
+ OPENVINO_ASSERT(priv_it != m_dynamic_kv_cache_private_buffers.end(),
+ "GQA KV-cache '",
+ name,
+ "' was aliased but has no stashed private buffer to restore");
+ m_inner_request->set_tensor(map_port_locked(port), priv_it->second);
+ GQA_TRACE(" -> requested_len < capacity, restored inner request's own private buffer");
+ }
+ // Not copied here: the caller may keep writing into `tensor` until infer(); only
+ // sync_dynamic_kv_cache_tensors_locked() is guaranteed to see live content.
+ m_dynamic_kv_cache_tensors[name] = tensor;
+ GQA_TRACE(" -> stored user tensor reference for later sync at infer() time");
+}
+
+void ov::npuw::GQAInferRequest::sync_dynamic_kv_cache_tensors_locked() const {
+ const auto& outer_inputs = m_compiled_model->inputs();
+ for (const auto& kv : m_compiled_model->m_dynamic_kv_cache_axes) {
+ // Pre-C++20: structured bindings can't be captured by lambdas, so use named locals.
+ const auto& name = kv.first;
+ const auto axis = kv.second;
+ auto tensor_it = m_dynamic_kv_cache_tensors.find(name);
+ if (tensor_it == m_dynamic_kv_cache_tensors.end()) {
+ continue; // set_tensor() not called yet for this port
+ }
+ auto port_it = std::find_if(outer_inputs.begin(), outer_inputs.end(), [&](const auto& input) {
+ return input.get_node()->get_friendly_name() == name;
+ });
+ if (port_it == outer_inputs.end()) {
+ continue;
+ }
+ const auto& inner_tensor = m_inner_request->get_tensor(map_port_locked(*port_it));
+ if (&*tensor_it->second == &*inner_tensor) {
+ // Already aliased by set_tensor(); same object, nothing to copy.
+ GQA_TRACE("sync_dynamic_kv_cache_tensors_locked(): '" << name << "' already aliased, skipping copy");
+ continue;
+ }
+ GQA_TRACE("sync_dynamic_kv_cache_tensors_locked(): '"
+ << name << "' axis=" << axis << " copying live prefix, shape=" << tensor_it->second->get_shape());
+ // Re-check here: the tensor can still grow between set_tensor() (which checked
+ // <= capacity at the time) and infer() -- e.g. a private fallback from
+ // get_tensor() followed by set_shape(), or a caller tensor reshaped afterwards.
+ // copy_by_planes() (axis 2) sizes each plane from the source, so an unchecked
+ // over-capacity tensor here would write past the end of the static buffer.
+ const auto src_len = tensor_it->second->get_shape().at(axis);
+ const auto capacity = inner_tensor->get_shape().at(axis);
+ OPENVINO_ASSERT(src_len <= capacity,
+ "GQA KV-cache '",
+ name,
+ "' length ",
+ src_len,
+ " exceeds the static capacity (",
+ capacity,
+ ") it was compiled with");
+ ov::npuw::GQAInferRequest::copy_kv_cache_prefix(tensor_it->second, inner_tensor, axis);
+ }
}
void ov::npuw::GQAInferRequest::check_tensors() const {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.hpp
index 61e277b27d6..9b7710c7f51 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.hpp
@@ -7,8 +7,15 @@
#include <functional>
#include <memory>
#include <mutex>
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+#include <vector>
#include "npuw/compiled_model.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/op/parameter.hpp"
namespace ov::npuw {
@@ -27,6 +34,10 @@ public:
std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override;
std::vector<ov::ProfilingInfo> get_profiling_info() const override;
+ // Copies the valid prefix of a smaller rank-4 tensor into a larger static one,
+ // left-aligned along `axis` (2 for [N,H,S,E], 3 for transposed [N,H,E,S]).
+ static void copy_kv_cache_prefix(const ov::SoPtr<ov::ITensor>& src, const ov::SoPtr<ov::ITensor>& dst, size_t axis);
+
private:
void ensure_inner_request_locked() const;
const ov::Output<const ov::Node>& map_port_locked(const ov::Output<const ov::Node>& port) const;
@@ -34,6 +45,37 @@ private:
std::shared_ptr<const GQACompiledModel> m_compiled_model;
mutable std::mutex m_mutex;
mutable std::shared_ptr<ov::IAsyncInferRequest> m_inner_request;
+ // Outer-facing tensor for dynamic KV-cache/attention-bias ports, keyed by port name.
+ mutable std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_dynamic_kv_cache_tensors;
+ // Dynamic-axis inputs currently bound directly onto the caller's exact-capacity
+ // tensor; must be restored before a shorter set_tensor() reuses the port.
+ mutable std::unordered_set<std::string> m_dynamic_kv_cache_input_aliased;
+ // Private static-capacity buffer stashed when a port gets aliased (see above);
+ // restored once a shorter tensor is bound to the same port.
+ mutable std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_dynamic_kv_cache_private_buffers;
+ // Outer-facing tensors for dynamic present_key/present_value outputs; allocated
+ // lazily and refreshed from the inner static buffer after every infer().
+ mutable std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_dynamic_kv_cache_output_tensors;
+ // Names currently aliased directly onto the inner tensor (no copy needed because the
+ // whole buffer is valid); never set_shape() these.
+ mutable std::unordered_set<std::string> m_dynamic_kv_cache_output_aliased;
+ // Present-output names the caller explicitly set_tensor()'d (forwarded straight to
+ // the inner request after asserting an exact shape match -- see set_tensor());
+ // refresh_present_tensors_locked() must not republish a separately-copied valid
+ // prefix under these names.
+ mutable std::unordered_set<std::string> m_dynamic_kv_cache_output_externally_set;
+
+ ov::SoPtr<ov::ITensor> get_present_tensor_locked(const std::string& name) const;
+ // Reads the live TOTAL_SEQUENCE_LENGTH Parameter value; see gqa_compiled_model.cpp.
+ std::optional<size_t> read_total_sequence_length_locked() const;
+ void refresh_present_tensors_locked() const;
+ // Copies each dynamic-axis input into the inner request's static buffer right before
+ // infer(). No-op for ports already aliased.
+ void sync_dynamic_kv_cache_tensors_locked() const;
+ // Diagnostic-only: traces sequence-length-style inputs before infer().
+ void trace_sequence_length_inputs_locked() const;
+ // Diagnostic-only: traces attention bias/mask stats before infer().
+ void trace_attention_mask_stats_locked() const;
};
class GQACompiledModel final : public ov::npuw::ICompiledModel {
@@ -43,11 +85,45 @@ public:
const std::shared_ptr<const ov::IPlugin>&,
const ov::AnyMap&)>;
+ enum class Case {
+ Unknown,
+ V0,
+ V1,
+ V2,
+ };
+
static std::shared_ptr<ov::npuw::ICompiledModel> make_compiled_model(
const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties);
+ // Classifies `model`'s GQA family, independent of dynamic shapes.
+ static Case identify_case(const std::shared_ptr<const ov::Model>& model);
+
+ // True if `model` should auto-dispatch to GQACompiledModel: a known GQA family with
+ // an actually dynamic max_seq_len.
+ static bool supports(const std::shared_ptr<const ov::Model>& model);
+
+ // True if any GQA op's KV-cache/bias input has a dynamic max_seq_len dimension.
+ static bool has_dynamic_max_seq_len(const std::shared_ptr<const ov::Model>& model);
+
+ // Scans `outer_outputs` for present_key/present_value ports with a single dynamic
+ // axis (output-side mirror of m_dynamic_kv_cache_axes). Exposed for testing.
+ static std::unordered_map<std::string, size_t> find_dynamic_kv_cache_output_axes(
+ const std::vector<ov::Output<const ov::Node>>& outer_outputs);
+
+ // Maps each present_key/present_value Result's name to its past_key/past_value
+ // Parameter's name, derived from each GQA op's own graph connections (not string
+ // rewriting, which breaks for dot-style naming). Exposed for testing.
+ static std::unordered_map<std::string, std::string> find_present_to_past_param_names(
+ const std::shared_ptr<const ov::Model>& model);
+
+ // Writes/reads outer-facing port metadata for export_model()/import_model(), keyed by
+ // friendly name (GQAInferRequest's dynamic-axis lookups key off it too).
+ static void write_port_list(std::ostream& stream, const std::vector<ov::Output<const ov::Node>>& ports);
+ static ov::ParameterVector read_input_port_list(std::istream& stream);
+ static ov::NodeVector read_output_port_list(std::istream& stream);
+
GQACompiledModel(const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties,
@@ -66,7 +142,17 @@ public:
private:
struct PreparedState {
std::shared_ptr<ov::Model> model;
+ std::shared_ptr<ov::Model> compiled_model;
ov::AnyMap properties;
+ // KV-cache/attention-bias Parameter name -> axis pinned to kMaxSeqLen.
+ std::unordered_map<std::string, size_t> dynamic_kv_cache_axes;
+ // Static KV-cache capacity actually used to reshape the model; stripped from the
+ // inner CompiledModel's properties, so this is the only way to read it back.
+ uint32_t effective_max_context_len = 0;
+ // Resolved sliding-window fallback capacity (see resolve_default_sliding_window_capacity()),
+ // 0 if NPUW_LLM_SWA_LEN wasn't configured. Also stripped from the inner
+ // CompiledModel's properties.
+ uint32_t effective_sliding_window_capacity = 0;
};
static PreparedState prepare(const std::shared_ptr<ov::Model>& model, const ov::AnyMap& properties);
@@ -75,11 +161,50 @@ private:
const std::shared_ptr<const ov::IPlugin>& plugin,
CompiledModelFactory factory);
+ // Used by import_model() to reconstruct a GQACompiledModel from a deserialized inner
+ // compiled model. total_seq_len_param_name/present_to_past_param_names are passed in
+ // (not re-derived from outer_model): on import, outer_model is a dummy carcass with
+ // no actual GroupQueryAttention ops, so the graph-walking find_*() helpers would
+ // silently find nothing.
+ GQACompiledModel(const std::shared_ptr<ov::Model>& outer_model,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ std::shared_ptr<ov::npuw::ICompiledModel> inner_compiled_model,
+ std::unordered_map<std::string, size_t> dynamic_kv_cache_axes,
+ uint32_t effective_max_context_len,
+ uint32_t effective_sliding_window_capacity,
+ std::optional<std::string> total_seq_len_param_name,
+ std::unordered_map<std::string, std::string> present_to_past_param_names);
+
std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;
friend class GQAInferRequest;
- std::shared_ptr<ov::npuw::ICompiledModel> m_compiled_model;
+ std::shared_ptr<ov::npuw::ICompiledModel> m_inner_compiled_model;
+ // The outer-facing model (as seen by the caller, pre-reshape-to-static). Returned
+ // as-is from get_runtime_model(); callers care about the outer contract.
+ std::shared_ptr<const ov::Model> m_outer_model;
+ std::unordered_map<std::string, size_t> m_dynamic_kv_cache_axes;
+ // present_key/present_value outer output name -> axis. Not serialized: cheaply
+ // re-derivable from the outer output ports on both compile and import paths.
+ std::unordered_map<std::string, size_t> m_dynamic_kv_cache_output_axes;
+ // TOTAL_SEQUENCE_LENGTH Parameter name, if resolved. Used to compute an accurate
+ // present_key/present_value length instead of mirroring past_key/past_value's own
+ // (stale) length. Derived from the real model on first compile and serialized across
+ // export_model()/import_model() -- NOT re-derivable from m_outer_model on import,
+ // since the import path's outer_model is a dummy carcass with no real GQA ops.
+ std::optional<std::string> m_total_seq_len_param_name;
+ // present_key/present_value outer Result name -> its past_key/past_value Parameter
+ // name (see find_present_to_past_param_names()). Same as above: derived once from the
+ // real model, serialized, and passed through on import rather than re-derived.
+ std::unordered_map<std::string, std::string> m_present_to_past_param_names;
+ // Effective static KV-cache capacity; returned from get_property(NPUW_LLM_MAX_CONTEXT_LEN)
+ // since the inner CompiledModel no longer carries this property. Serialized across
+ // export_model()/import_model().
+ uint32_t m_effective_max_context_len = 0;
+ // Effective sliding-window fallback capacity (0 if unconfigured); returned from
+ // get_property(NPUW_LLM_SWA_LEN) for the same reason. Serialized across
+ // export_model()/import_model().
+ uint32_t m_effective_sliding_window_capacity = 0;
};
} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/logging.cpp b/src/plugins/intel_npu/src/plugin/npuw/logging.cpp
index 5bca55cb2f1..dd2af9c715f 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/logging.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/logging.cpp
@@ -8,6 +8,7 @@
#include <iomanip>
#include <iostream>
#include <mutex>
+#include <sstream>
#include "openvino/runtime/make_tensor.hpp" // get_tensor_impl
@@ -129,6 +130,62 @@ void ov::npuw::dump_tensor(const ov::SoPtr<ov::ITensor>& input, const std::strin
}
}
+std::optional<int64_t> ov::npuw::read_scalar_int_tensor(const ov::SoPtr<ov::ITensor>& tensor) {
+ if (!tensor || ov::shape_size(tensor->get_shape()) == 0) {
+ return std::nullopt;
+ }
+ switch (tensor->get_element_type()) {
+ case ov::element::i32:
+ return static_cast<int64_t>(*tensor->data<int32_t>());
+ case ov::element::i64:
+ return *tensor->data<int64_t>();
+ default:
+ return std::nullopt;
+ }
+}
+
+namespace {
+template <typename T>
+std::string stats_string_typed(const T* data, size_t count) {
+ if (count == 0) {
+ return "<empty>";
+ }
+ double min_value = static_cast<double>(data[0]);
+ double max_value = static_cast<double>(data[0]);
+ size_t non_zero_count = 0;
+ for (size_t i = 0; i < count; ++i) {
+ const double value = static_cast<double>(data[i]);
+ min_value = std::min(min_value, value);
+ max_value = std::max(max_value, value);
+ if (value != 0.0) {
+ ++non_zero_count;
+ }
+ }
+ std::ostringstream out;
+ out << "min=" << min_value << " max=" << max_value << " non_zero=" << non_zero_count << "/" << count;
+ return out.str();
+}
+} // namespace
+
+std::string ov::npuw::tensor_stats_string(const ov::SoPtr<ov::ITensor>& tensor) {
+ if (!tensor) {
+ return "<null tensor>";
+ }
+ const auto count = ov::shape_size(tensor->get_shape());
+ switch (tensor->get_element_type()) {
+ case ov::element::f32:
+ return stats_string_typed(tensor->data<float>(), count);
+ case ov::element::f16:
+ return stats_string_typed(tensor->data<ov::float16>(), count);
+ case ov::element::i32:
+ return stats_string_typed(tensor->data<int32_t>(), count);
+ case ov::element::i64:
+ return stats_string_typed(tensor->data<int64_t>(), count);
+ default:
+ return "<stats unavailable for element_type " + tensor->get_element_type().get_type_name() + ">";
+ }
+}
+
static void dump_file_list(const std::string& list_path, const std::vector<std::string>& base_names) {
std::ofstream list_file(list_path);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/logging.hpp b/src/plugins/intel_npu/src/plugin/npuw/logging.hpp
index 9823c89d27b..544aa2e020f 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/logging.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/logging.hpp
@@ -5,6 +5,7 @@
#pragma once
#include <fstream>
+#include <optional>
#include "openvino/core/log_util.hpp"
#include "openvino/openvino.hpp"
@@ -38,6 +39,15 @@ void dump_input_list(const std::string& base_name, const std::vector<std::string
void dump_output_list(const std::string& base_name, const std::vector<std::string>& base_output_names);
void dump_failure(const std::shared_ptr<ov::Model>& model, const std::string& device, const char* extra);
+
+// Reads a scalar (or single-element) integer tensor's value, regardless of whether it
+// was stored as i32 or i64. Returns nullopt for empty or non-integer tensors.
+std::optional<int64_t> read_scalar_int_tensor(const ov::SoPtr<ov::ITensor>& tensor);
+
+// Formats a one-line "min=.. max=.. non_zero=../.." summary of a numeric tensor's
+// content (fp16/fp32/int32/int64), for compact diagnostic logging. Returns a
+// placeholder string for empty or unsupported element types.
+std::string tensor_stats_string(const ov::SoPtr<ov::ITensor>& tensor);
} // namespace npuw
} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.cpp
new file mode 100644
index 00000000000..646b922e77c
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.cpp
@@ -0,0 +1,324 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "reshape_to_static_gqa.hpp"
+
+#include <algorithm>
+#include <map>
+#include <optional>
+#include <unordered_set>
+
+#include "../logging.hpp"
+#include "../util.hpp"
+#include "openvino/op/group_query_attention.hpp"
+#include "openvino/op/parameter.hpp"
+
+namespace {
+
+// Scans `model`'s past_key/past_value Parameters for a dynamic dimension, keyed by
+// Parameter name. More than one dynamic dim is ambiguous and not resolved.
+std::unordered_map<std::string, size_t> find_dynamic_kv_cache_axes(const std::shared_ptr<ov::Model>& model) {
+ std::unordered_map<std::string, size_t> result;
+
+ const auto resolve_dynamic_axis =
+ [](const std::shared_ptr<ov::op::v0::Parameter>& parameter) -> std::optional<size_t> {
+ const auto& partial_shape = parameter->get_partial_shape();
+ if (auto axis = ov::npuw::util::find_single_dynamic_axis(partial_shape)) {
+ return axis;
+ }
+ if (partial_shape.rank().is_static()) {
+ const auto dynamic_count = std::count_if(partial_shape.begin(), partial_shape.end(), [](const auto& dim) {
+ return dim.is_dynamic();
+ });
+ OPENVINO_ASSERT(dynamic_count <= 1,
+ "GQA parameter '",
+ parameter->get_friendly_name(),
+ "' has more than one dynamic dimension; can't resolve its max_seq_len axis");
+ }
+ return std::nullopt;
+ };
+
+ // The capacity dim is axis 2 of [batch, kv_heads, capacity, head_size], or axis 3
+ // under --transpose_v. Axis 0/1 are never the capacity dimension.
+ for (const auto& parameter : model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (!ov::npuw::util::contains_ignore_case(name, "past_key") &&
+ !ov::npuw::util::contains_ignore_case(name, "past_value")) {
+ continue;
+ }
+ if (auto axis = resolve_dynamic_axis(parameter)) {
+ const auto rank = parameter->get_partial_shape().size();
+ OPENVINO_ASSERT(ov::npuw::util::is_supported_kv_cache_capacity_axis(*axis, rank),
+ "GQA KV-cache parameter '",
+ name,
+ "' has its dynamic dimension at axis ",
+ *axis,
+ " of a rank-",
+ rank,
+ " shape, but GroupQueryAttentionDecomposition only ever reads/writes the "
+ "KV-cache capacity at axis 2 ([batch, kv_heads, capacity, head_size]) or axis 3 "
+ "(--transpose_v layout). Refusing to pin a non-capacity axis to the static "
+ "context length.");
+ result.emplace(name, *axis);
+ }
+ }
+
+ // The attention bias/mask shares max_seq_len but isn't named consistently; locate it
+ // via the GQA op's ATTENTION_BIAS input instead.
+ using ov::op::internal::GroupQueryAttention;
+ using ov::op::internal::GroupQueryAttentionInputs;
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (!gqa || gqa->get_input_size() <= static_cast<size_t>(GroupQueryAttentionInputs::ATTENTION_BIAS)) {
+ continue;
+ }
+ auto bias_parameter = ov::as_type_ptr<ov::op::v0::Parameter>(
+ gqa->input_value(static_cast<size_t>(GroupQueryAttentionInputs::ATTENTION_BIAS)).get_node_shared_ptr());
+ if (!bias_parameter) {
+ continue; // not fed directly by a Parameter; nothing we can reshape here
+ }
+ if (auto axis = resolve_dynamic_axis(bias_parameter)) {
+ // The capacity dim is always the LAST axis ([1, heads, curr, max_kv]), never
+ // the query-length axis -- important for speculative-decode (query_len > 1).
+ const auto last_axis = bias_parameter->get_partial_shape().size() - 1;
+ OPENVINO_ASSERT(*axis == last_axis,
+ "GQA attention-bias parameter '",
+ bias_parameter->get_friendly_name(),
+ "' has its dynamic dimension at axis ",
+ *axis,
+ ", but GroupQueryAttentionDecomposition always reads the KV-cache capacity from "
+ "the last axis (",
+ last_axis,
+ ") of [1, num_heads, curr, max_kv]. Refusing to pin a non-capacity axis to the "
+ "static context length.");
+ result.emplace(bias_parameter->get_friendly_name(), *axis);
+ }
+ }
+
+ return result;
+}
+
+// `sliding_window_cache=true` layers physically evict/repack their KV-cache ring buffer,
+// so they need their own, smaller static capacity derived from `local_window_size`
+// instead of the model-wide max_seq_len.
+//
+// Round local_window_size up to the NPU's 16-token KV granularity plus one headroom
+// block, so evictions are amortized rather than rolling the buffer on every token.
+std::optional<size_t> sliding_window_target_capacity(const ov::op::internal::GroupQueryAttention& gqa) {
+ if (!gqa.get_sliding_window_cache()) {
+ return std::nullopt;
+ }
+ constexpr int64_t kAlign = 16;
+ constexpr int64_t kHeadroom = 16;
+ const int64_t window = gqa.get_local_window_size();
+ OPENVINO_ASSERT(window >= 1,
+ "GQA op '",
+ gqa.get_friendly_name(),
+ "' has sliding_window_cache=true but an invalid local_window_size=",
+ window);
+ const int64_t aligned = ((window + kAlign - 1) / kAlign) * kAlign;
+ return static_cast<size_t>(aligned + kHeadroom);
+}
+
+// Finds the GQA op that directly reads `parameter` as PAST_KEY/PAST_VALUE/ATTENTION_BIAS,
+// used to resolve a Parameter's own target capacity rather than the model-wide max_seq_len.
+std::shared_ptr<ov::op::internal::GroupQueryAttention> find_gqa_consuming_parameter(
+ const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<ov::op::v0::Parameter>& parameter) {
+ using ov::op::internal::GroupQueryAttention;
+ using ov::op::internal::GroupQueryAttentionInputs;
+ for (const auto& node : model->get_ordered_ops()) {
+ auto gqa = ov::as_type_ptr<GroupQueryAttention>(node);
+ if (!gqa) {
+ continue;
+ }
+ for (auto input_idx : {GroupQueryAttentionInputs::PAST_KEY,
+ GroupQueryAttentionInputs::PAST_VALUE,
+ GroupQueryAttentionInputs::ATTENTION_BIAS}) {
+ if (gqa->get_input_size() <= static_cast<size_t>(input_idx)) {
+ continue;
+ }
+ if (gqa->input_value(static_cast<size_t>(input_idx)).get_node_shared_ptr() == parameter) {
+ return gqa;
+ }
+ }
+ }
+ return nullptr;
+}
+
+// Maps each GQA op to a 0-based sequential layer index (op-encounter order), matching
+// how rt_info's "full_attention_layers"/"sliding_window_layers" number layers.
+std::unordered_map<const ov::Node*, int64_t> index_gqa_layers(const std::shared_ptr<ov::Model>& model) {
+ std::unordered_map<const ov::Node*, int64_t> result;
+ int64_t index = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (ov::as_type_ptr<ov::op::internal::GroupQueryAttention>(node)) {
+ result.emplace(node.get(), index++);
+ }
+ }
+ return result;
+}
+
+// Authoritative source for sliding-window layers when GQA ops carry no
+// sliding_window_cache/local_window_size attribute: ONNX metadata_props preserved as
+// OV rt_info["framework"][...].
+struct RtInfoSlidingWindowMetadata {
+ std::unordered_set<int64_t> sliding_layers;
+ size_t sliding_window_size;
+};
+
+std::optional<RtInfoSlidingWindowMetadata> find_rt_info_sliding_window_metadata(
+ const std::shared_ptr<ov::Model>& model) {
+ if (!model->has_rt_info("framework", "sliding_window_layers") ||
+ !model->has_rt_info("framework", "sliding_window_size")) {
+ return std::nullopt;
+ }
+ auto sliding_layers =
+ ov::npuw::util::parse_layer_index_list(model->get_rt_info<std::string>("framework", "sliding_window_layers"));
+ if (sliding_layers.empty()) {
+ return std::nullopt;
+ }
+ // Exact match with the host's own eviction logic; lets GQAInferRequest::set_tensor()
+ // alias the host's tensor directly instead of copying.
+ const auto declared_size = std::stoull(model->get_rt_info<std::string>("framework", "sliding_window_size"));
+ return RtInfoSlidingWindowMetadata{std::move(sliding_layers), static_cast<size_t>(declared_size)};
+}
+
+// Last-resort fallback for models with neither rt_info metadata nor a
+// sliding_window_cache=true attribute: full-attention layers share one
+// SEQLENS_K/TOTAL_SEQUENCE_LENGTH Parameter, sliding-window layers share a different one
+// hinting "sliding" in its name -- group membership falls out of shared input identity,
+// no index parsing needed.
+//
+// The actual capacity number isn't in the graph at all (pure host-side eviction), so it
+// can only come from the caller-supplied m_default_sliding_window_capacity; if unset,
+// every layer just keeps the model-wide max_seq_len.
+bool has_sliding_window_seqlens_name(const ov::op::internal::GroupQueryAttention& gqa) {
+ using ov::op::internal::GroupQueryAttentionInputs;
+ const auto seqlens_input_name = [&](GroupQueryAttentionInputs input) -> std::string {
+ if (gqa.get_input_size() <= static_cast<size_t>(input)) {
+ return {};
+ }
+ return gqa.input_value(static_cast<size_t>(input)).get_node()->get_friendly_name();
+ };
+ return ov::npuw::util::contains_ignore_case(seqlens_input_name(GroupQueryAttentionInputs::SEQLENS_K), "sliding") ||
+ ov::npuw::util::contains_ignore_case(seqlens_input_name(GroupQueryAttentionInputs::TOTAL_SEQUENCE_LENGTH),
+ "sliding");
+}
+
+} // namespace
+
+ov::npuw::ReshapeToStaticGQA::ReshapeToStaticGQA(size_t max_seq_len,
+ std::optional<size_t> default_sliding_window_capacity)
+ : m_max_seq_len(max_seq_len),
+ m_default_sliding_window_capacity(default_sliding_window_capacity) {}
+
+bool ov::npuw::ReshapeToStaticGQA::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ m_dynamic_kv_cache_axes = find_dynamic_kv_cache_axes(model);
+ OPENVINO_ASSERT(!m_dynamic_kv_cache_axes.empty(),
+ "GQA model has a dynamic max_seq_len but no resolvable KV-cache Parameter was found");
+
+ // Per-Parameter target capacity: model-wide max_seq_len normally; a sliding-window
+ // layer gets its own smaller capacity, in priority order: (1) rt_info metadata, (2)
+ // sliding_window_cache=true + local_window_size op attributes, (3) best-effort
+ // seqlens-name fallback using the caller-configured default.
+ auto rt_info_metadata = find_rt_info_sliding_window_metadata(model);
+ auto gqa_layer_index = rt_info_metadata ? index_gqa_layers(model) : std::unordered_map<const ov::Node*, int64_t>{};
+ LOG_INFO(
+ "ReshapeToStaticGQA: resolving per-layer KV-cache capacity (model-wide max_seq_len="
+ << m_max_seq_len << "); rt_info sliding-window metadata " << (rt_info_metadata ? "FOUND" : "NOT found")
+ << (rt_info_metadata
+ ? (", " + std::to_string(rt_info_metadata->sliding_layers.size()) +
+ " layer(s) declared sliding_window_size=" + std::to_string(rt_info_metadata->sliding_window_size))
+ : std::string())
+ << "; seqlens-name fallback default "
+ << (m_default_sliding_window_capacity ? ("configured=" + std::to_string(*m_default_sliding_window_capacity))
+ : std::string("not configured")));
+
+ // End-of-pass summary counters -- which mechanism(s) fired for this model.
+ size_t resolved_via_rt_info = 0;
+ size_t resolved_via_op_attribute = 0;
+ size_t resolved_via_seqlens_name_fallback = 0;
+ size_t resolved_via_default = 0;
+
+ std::map<ov::Output<ov::Node>, ov::PartialShape> new_shapes;
+ for (const auto& kv : m_dynamic_kv_cache_axes) {
+ // NB: structured bindings can't be captured by lambdas pre-C++20, so use
+ // plain named locals for 'name'/'axis' instead of a [name, axis] binding here.
+ const auto& name = kv.first;
+ const auto axis = kv.second;
+ const auto& params = model->get_parameters();
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end(), "KV-cache parameter '", name, "' not found in the model");
+
+ size_t target_capacity = m_max_seq_len;
+ auto gqa = find_gqa_consuming_parameter(model, *it);
+ bool resolved = false;
+ if (gqa && rt_info_metadata) {
+ auto layer_it = gqa_layer_index.find(gqa.get());
+ if (layer_it != gqa_layer_index.end() && rt_info_metadata->sliding_layers.count(layer_it->second)) {
+ target_capacity = std::min(rt_info_metadata->sliding_window_size, m_max_seq_len);
+ resolved = true;
+ resolved_via_rt_info++;
+ LOG_INFO("GQA op '" << gqa->get_friendly_name() << "' (layer " << layer_it->second
+ << ") is listed in rt_info sliding_window_layers: pinning '" << name
+ << "' to the declared sliding_window_size of " << target_capacity
+ << " tokens instead of the model-wide " << m_max_seq_len);
+ }
+ }
+ if (!resolved && gqa) {
+ if (auto window_capacity = sliding_window_target_capacity(*gqa)) {
+ target_capacity = std::min(*window_capacity, m_max_seq_len);
+ resolved = true; // also skip the seqlens-name fallback below
+ resolved_via_op_attribute++;
+ LOG_INFO("GQA op '" << gqa->get_friendly_name() << "' has sliding_window_cache=true: pinning '" << name
+ << "' to its own local capacity of " << target_capacity
+ << " tokens instead of the model-wide " << m_max_seq_len);
+ }
+ }
+ if (!resolved && gqa && m_default_sliding_window_capacity && has_sliding_window_seqlens_name(*gqa)) {
+ target_capacity = std::min(*m_default_sliding_window_capacity, m_max_seq_len);
+ resolved = true;
+ resolved_via_seqlens_name_fallback++;
+ LOG_INFO("GQA op '" << gqa->get_friendly_name()
+ << "' has no rt_info/op-attribute sliding-window signal, but its SEQLENS_K/"
+ "TOTAL_SEQUENCE_LENGTH input name hints a sliding-window group: pinning '"
+ << name << "' to the configured default capacity of " << target_capacity
+ << " tokens instead of the model-wide " << m_max_seq_len
+ << " (best-effort fallback -- no authoritative source for this model)");
+ }
+ if (!resolved) {
+ resolved_via_default++;
+ LOG_INFO("'" << name << "' has no rt_info/op-attribute/seqlens-name sliding-window signal"
+ << (gqa ? "" : " (no owning GQA op found)") << ": pinning it to the model-wide max_seq_len of "
+ << target_capacity << " tokens");
+ }
+
+ auto new_shape = (*it)->get_partial_shape();
+ new_shape[axis] = ov::Dimension(static_cast<int64_t>(target_capacity));
+ new_shapes[(*it)->output(0)] = new_shape;
+ }
+ LOG_INFO("ReshapeToStaticGQA: resolved " << m_dynamic_kv_cache_axes.size() << " dynamic KV-cache/bias axis(es) -- "
+ << "rt_info: " << resolved_via_rt_info
+ << ", op_attribute: " << resolved_via_op_attribute
+ << ", seqlens_name_fallback: " << resolved_via_seqlens_name_fallback
+ << ", default(max_seq_len): " << resolved_via_default);
+ model->reshape(new_shapes);
+
+ for (const auto& kv : m_dynamic_kv_cache_axes) {
+ const auto& name = kv.first;
+ const auto& params = model->get_parameters();
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end() && (*it)->get_partial_shape().is_static(),
+ "Reshaping the GQA KV-cache parameter '",
+ name,
+ "' to a static capacity did not make it fully static");
+ }
+ LOG_INFO("Reshaped dynamic GQA KV-cache to a static capacity (model-wide max of " << m_max_seq_len << " tokens)");
+ return true;
+}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.hpp
new file mode 100644
index 00000000000..d84e6f2d330
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.hpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <optional>
+#include <unordered_map>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+// Reshapes a GQA model's dynamic KV-cache (past_key/past_value) and attention-bias/mask
+// Parameters to a static capacity, as required for NPU compilation. Most layers get the
+// model-wide `max_seq_len`; a sliding-window layer gets its own, smaller capacity instead,
+// resolved in priority order (rt_info metadata, op attributes, seqlens-name fallback --
+// see the .cpp for details).
+// Intended to run on a private clone of the original (still-dynamic) model, since it
+// mutates the model it's given in place -- the caller keeps the original around for
+// tensor-shape bookkeeping.
+class ReshapeToStaticGQA : public ov::pass::ModelPass {
+ size_t m_max_seq_len;
+ std::optional<size_t> m_default_sliding_window_capacity;
+ std::unordered_map<std::string, size_t> m_dynamic_kv_cache_axes;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeToStaticGQA");
+ explicit ReshapeToStaticGQA(size_t max_seq_len,
+ std::optional<size_t> default_sliding_window_capacity = std::nullopt);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+
+ // The dynamic-axis Parameters (KV-cache + attention-bias) discovered and reshaped by
+ // the last run_on_model() call, keyed by Parameter friendly name. Empty until
+ // run_on_model() has been called.
+ const std::unordered_map<std::string, size_t>& dynamic_kv_cache_axes() const {
+ return m_dynamic_kv_cache_axes;
+ }
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index 9a2ca14d656..99776c7747d 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -56,7 +56,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_FLUX2_COMPILED_MODEL_INDICATO
const constexpr ov::npuw::s11n::IndicatorType NPUW_BATCHED_COMPILED_MODEL_INDICATOR =
{char{0x42}, char{0x41}, char{0x54}, char{0x43}, char{0x4d}, char{0x4f}};
-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.34";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.35";
// Forward declaration
namespace intel_npu {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cpp
index 1857f168ae9..d7f227941d2 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp
@@ -5,6 +5,8 @@
#include "util.hpp"
#include <algorithm>
+#include <cctype>
+#include <charconv>
#include <intel_npu/config/config.hpp>
#include <iomanip>
#include <openvino/core/parallel.hpp>
@@ -198,6 +200,86 @@ bool ov::npuw::util::starts_with(const std::string& str, const std::string& pref
return str.substr(0, prefix.size()) == prefix;
}
+bool ov::npuw::util::contains_ignore_case(const std::string& str, const std::string& substr) {
+ auto it = std::search(str.begin(), str.end(), substr.begin(), substr.end(), [](unsigned char a, unsigned char b) {
+ return std::tolower(a) == std::tolower(b);
+ });
+ return it != str.end();
+}
+
+std::optional<int64_t> ov::npuw::util::parse_positive_int_env_var(const std::string& str) {
+ if (str.empty()) {
+ return std::nullopt;
+ }
+ int64_t parsed = 0;
+ const auto* begin = str.data();
+ const auto* end = str.data() + str.size();
+ const auto result = std::from_chars(begin, end, parsed);
+ if (result.ec != std::errc() || result.ptr != end || parsed <= 0) {
+ return std::nullopt;
+ }
+ return parsed;
+}
+
+std::shared_ptr<ov::op::v0::Parameter> ov::npuw::util::trace_back_to_parameter(std::shared_ptr<ov::Node> node) {
+ while (node && !ov::is_type<ov::op::v0::Parameter>(node)) {
+ if (node->get_input_size() != 1) {
+ return nullptr;
+ }
+ node = node->input_value(0).get_node_shared_ptr();
+ }
+ return ov::as_type_ptr<ov::op::v0::Parameter>(node);
+}
+
+std::shared_ptr<ov::op::v0::Result> ov::npuw::util::trace_forward_to_result(const ov::Output<ov::Node>& output) {
+ ov::Output<ov::Node> current = output;
+ while (true) {
+ const auto& targets = current.get_target_inputs();
+ if (targets.size() != 1) {
+ return nullptr;
+ }
+ auto node = targets.begin()->get_node()->shared_from_this();
+ if (auto result = ov::as_type_ptr<ov::op::v0::Result>(node)) {
+ return result;
+ }
+ if (node->get_output_size() != 1) {
+ return nullptr;
+ }
+ current = node->output(0);
+ }
+}
+
+bool ov::npuw::util::reaches(const ov::Node* start, const ov::Node* target) {
+ std::unordered_set<const ov::Node*> visited;
+ std::vector<const ov::Node*> stack{start};
+ while (!stack.empty()) {
+ const auto* node = stack.back();
+ stack.pop_back();
+ if (node == target) {
+ return true;
+ }
+ if (!visited.insert(node).second) {
+ continue;
+ }
+ for (const auto& output : node->outputs()) {
+ for (const auto& input : output.get_target_inputs()) {
+ stack.push_back(input.get_node());
+ }
+ }
+ }
+ return false;
+}
+
+std::unordered_set<int64_t> ov::npuw::util::parse_layer_index_list(const std::string& text) {
+ std::unordered_set<int64_t> result;
+ static const std::regex kNumberRe(R"(-?\d+)");
+ for (auto it = std::sregex_iterator(text.begin(), text.end(), kNumberRe), end = std::sregex_iterator(); it != end;
+ ++it) {
+ result.insert(std::stoll(it->str()));
+ }
+ return result;
+}
+
std::unordered_set<std::string> ov::npuw::util::mutable_properties(
const std::vector<ov::PropertyName>& supported_properties) {
std::unordered_set<std::string> result;
@@ -209,6 +291,26 @@ std::unordered_set<std::string> ov::npuw::util::mutable_properties(
return result;
}
+std::optional<size_t> ov::npuw::util::find_single_dynamic_axis(const ov::PartialShape& shape) {
+ if (shape.rank().is_dynamic()) {
+ return std::nullopt;
+ }
+ std::optional<size_t> dynamic_axis;
+ for (size_t i = 0; i < shape.size(); ++i) {
+ if (shape[i].is_dynamic()) {
+ if (dynamic_axis.has_value()) {
+ return std::nullopt; // more than one dynamic axis -- ambiguous
+ }
+ dynamic_axis = i;
+ }
+ }
+ return dynamic_axis;
+}
+
+bool ov::npuw::util::is_supported_kv_cache_capacity_axis(size_t axis, size_t rank) {
+ return rank == 4 && (axis == 2 || axis == 3);
+}
+
bool ov::npuw::util::is_supported_position_ids_input(const ov::Output<const ov::Node>& p) {
const auto& shape = p.get_shape();
return p.get_node()->get_friendly_name() == "position_ids" &&
diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hpp
index 688a3c65d78..3a2291f1ed1 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp
@@ -15,6 +15,7 @@
#include "logging.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
#include "openvino/runtime/icompiled_model.hpp"
#include "openvino/runtime/iplugin.hpp"
#include "openvino/runtime/itensor.hpp"
@@ -39,6 +40,40 @@ ov::Tensor copy_tensor_from_const(const std::shared_ptr<ov::Node>& node);
bool starts_with(const std::string& str, const std::string& prefix);
+// Case-insensitive substring search.
+bool contains_ignore_case(const std::string& str, const std::string& substr);
+
+// Strictly parses `str` as a positive base-10 integer (std::from_chars; whole string
+// consumed, no sign accepted, unlike std::stoull). Returns nullopt for anything else,
+// including an empty string or 0.
+std::optional<int64_t> parse_positive_int_env_var(const std::string& str);
+
+// Walks back from `node`'s single input along pass-through ops (e.g. Convert) until it
+// reaches a Parameter, or gives up (nullptr) if the chain branches or dead-ends.
+std::shared_ptr<ov::op::v0::Parameter> trace_back_to_parameter(std::shared_ptr<ov::Node> node);
+
+// Forward analog of trace_back_to_parameter(): walks from `output` along pass-through ops
+// until it reaches a Result, or gives up (nullptr) on a branch/dead-end. Used to map a
+// GroupQueryAttention op's present_key/
+// present_value output directly to its model-level Result, independent of naming.
+std::shared_ptr<ov::op::v0::Result> trace_forward_to_result(const ov::Output<ov::Node>& output);
+
+// Forward data-flow reachability: true if `target` can be reached from `start` by following
+// output->target_input edges.
+bool reaches(const ov::Node* start, const ov::Node* target);
+
+// Parses a bracketed, comma-separated integer list (ONNX metadata_props stored as a
+// string rt_info value, e.g. "[0, 1, 5, 6]"). Returns an empty set if missing/malformed.
+std::unordered_set<int64_t> parse_layer_index_list(const std::string& text);
+
+// Returns the single dynamic axis of `shape`, or nullopt if rank is dynamic, no axis is
+// dynamic, or more than one is (ambiguous).
+std::optional<size_t> find_single_dynamic_axis(const ov::PartialShape& shape);
+
+// True if `axis` is a plausible GQA KV-cache capacity axis for a rank-4 past_key/
+// past_value parameter: axis 2 ([N,H,S,E]) or axis 3 (--transpose_v's [N,H,E,S]).
+bool is_supported_kv_cache_capacity_axis(size_t axis, size_t rank);
+
// Names of all RW entries of an ov::supported_properties list (of a compiled model or a plugin)
std::unordered_set<std::string> mutable_properties(const std::vector<ov::PropertyName>& supported_properties);
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index d20f670ada6..e0d3310e655 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -153,6 +153,8 @@ set(NPUW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_sliced_head_to_static.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static_gqa.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static_gqa.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/propagate_slice.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/propagate_slice.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/slice_out_embeds.cpp
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index 3da908c8ef1..48ca7459a40 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -18,6 +18,7 @@
#include "intel_npu/config/options.hpp"
#include "intel_npu/utils/utils.hpp"
#include "npuw/compiled_model.hpp"
+#include "npuw/gqa_compiled_model.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/runtime/intel_npu/properties.hpp"
@@ -256,6 +257,13 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
// NPUW is disabled, remove the key from the properties
localProperties.erase(useNpuwKey);
}
+ } else if (ov::npuw::GQACompiledModel::supports(model)) {
+ // Zero-config path: detect if the model suits the NPUW_GQA path
+ _logger.info("Auto-detected NPUW_GQA path with no NPU_USE_NPUW set; routing through NPUW "
+ "automatically.");
+ auto npuwProperties = localProperties;
+ npuwProperties[useNpuwKey] = true;
+ return ov::npuw::ICompiledModel::create(model->clone(), shared_from_this(), npuwProperties);
}
// DEVICE_ID can be passed both as an index and as a platform name.
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 9ba46393cd0..d6c873943da 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -126,6 +126,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static_gqa.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/right_align_mask_slice_for_conv.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/gqa_compiled_model_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/gqa_compiled_model_test.cpp
index 9b0f5d9280a..eafd61998ae 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/gqa_compiled_model_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/gqa_compiled_model_test.cpp
@@ -6,11 +6,15 @@
#include <algorithm>
#include <memory>
+#include <sstream>
#include <string>
#include <vector>
#include "gqa_compiled_model.hpp"
#include "llm_test_helpers.hpp"
+#include "npuw_transformations/reshape_to_static_gqa.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/op/add.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convolution.hpp"
#include "openvino/op/convert.hpp"
@@ -19,11 +23,14 @@
#include "openvino/op/multiply.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/runtime/make_tensor.hpp"
#include "openvino/runtime/properties.hpp"
+#include "serialization.hpp"
namespace {
@@ -63,6 +70,456 @@ std::shared_ptr<ov::Model> build_group_query_attention_model() {
return std::make_shared<ov::Model>(results, params, "gqa_model");
}
+// Builds a model with a well-formed GQA op plus the surrounding transformer traits
+// (activation input, position_ids, named past/present KV cache Parameters/Results)
+// that supports() looks for. `position_signal` picks between an explicit `position_ids`
+// Parameter (V1) or a `past_seq_len`/`total_seq_len` pair with no position_ids input (V0).
+enum class PositionSignal {
+ PositionIds,
+ SeqLenPair,
+};
+
+std::shared_ptr<ov::Model> build_full_gqa_transformer_model(int64_t num_heads = 4,
+ int64_t kv_num_heads = 2,
+ bool do_rotary = true,
+ PositionSignal position_signal = PositionSignal::PositionIds,
+ bool with_2bit_weights = false) {
+ // Shaped {1, num_heads, 16} so it Unsqueeze's below into QUERY's {1, num_heads, 1, 16}
+ // without a volume mismatch -- identify_case() requires this Parameter to be
+ // data-connected to the GQA op, not just present by name.
+ auto input_hidden_states =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, static_cast<size_t>(num_heads), 16});
+ input_hidden_states->set_friendly_name("input_hidden_states");
+ auto query_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {2});
+ auto query = std::make_shared<ov::op::v0::Unsqueeze>(input_hidden_states, query_axis);
+
+ std::shared_ptr<ov::op::v0::Parameter> position_ids;
+ if (position_signal == PositionSignal::PositionIds) {
+ position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+ position_ids->set_friendly_name("position_ids");
+ }
+
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::Shape{1, static_cast<size_t>(kv_num_heads), 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::Shape{1, static_cast<size_t>(kv_num_heads), 1, 16});
+ auto past_key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::Shape{1, static_cast<size_t>(kv_num_heads), 8, 16});
+ past_key->set_friendly_name("past_keys_0");
+ auto past_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::Shape{1, static_cast<size_t>(kv_num_heads), 8, 16});
+ past_value->set_friendly_name("past_values_0");
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ if (position_signal == PositionSignal::SeqLenPair) {
+ // V0 wiring: no position_ids input; seqlens_k/total_sequence_length double as the
+ // "past_seq_len"/"total_seq_len" naming evidence.
+ seqlens_k->set_friendly_name("past_seq_len");
+ total_sequence_length->set_friendly_name("total_seq_len");
+ }
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ ov::OutputVector gqa_inputs{query, key, value, past_key, past_value, seqlens_k, total_sequence_length,
+ cos_cache, sin_cache};
+ if (position_ids) {
+ // POSITION_IDS (index 9) -- wiring it here is what identify_case() requires as evidence.
+ gqa_inputs.push_back(position_ids);
+ }
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(gqa_inputs,
+ num_heads,
+ kv_num_heads,
+ 0.0f,
+ do_rotary,
+ false);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_0");
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_0");
+
+ ov::ResultVector results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)), present_key, present_value};
+ ov::ParameterVector params = {input_hidden_states};
+ if (position_ids) {
+ params.push_back(position_ids);
+ }
+ params.insert(params.end(),
+ {key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache});
+ if (with_2bit_weights) {
+ // V2 models ship weights as 2-bit group-quantized (u2) Parameters. The GQA op
+ // doesn't need to consume this directly; has_2bit_group_quantized_weights() just
+ // scans the model's Parameters.
+ auto quantized_weight = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{8, 16});
+ quantized_weight->set_friendly_name("quantized_weight");
+ params.push_back(quantized_weight);
+ }
+ return std::make_shared<ov::Model>(results, params, "gqa_full_transformer_model");
+}
+
+// Leaves past_key/past_value's KV-cache dimension dynamic at `axis` (2 plain [N,H,S,E],
+// 3 transpose_v [N,H,E,S]) to exercise has_dynamic_max_seq_len()/prepare().
+void make_kv_cache_dynamic(const std::shared_ptr<ov::Model>& model, size_t axis) {
+ for (const auto& parameter : model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (name != "past_keys_0" && name != "past_values_0") {
+ continue;
+ }
+ auto shape = parameter->get_partial_shape();
+ shape[axis] = ov::Dimension::dynamic();
+ parameter->set_partial_shape(shape);
+ }
+ model->validate_nodes_and_infer_types();
+}
+
+// Same wiring as build_full_gqa_transformer_model(), but with the KV-cache dimension left
+// dynamic at `axis` to exercise has_dynamic_max_seq_len()/prepare().
+std::shared_ptr<ov::Model> build_gqa_model_with_dynamic_kv_cache(size_t axis) {
+ auto model = build_full_gqa_transformer_model();
+ make_kv_cache_dynamic(model, axis);
+ return model;
+}
+
+// Same wiring, but with an extra `attention_mask` feeding ATTENTION_BIAS (index 10) with
+// a dynamic last dimension, mirroring speculative-decode dumps. POSITION_IDS (index 9)
+// is "not provided" via a zero-size Constant, matching the V0 wiring.
+std::shared_ptr<ov::Model> build_gqa_model_with_dynamic_attention_bias(bool dynamic_kv_cache = false) {
+ auto input_hidden_states = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 16});
+ input_hidden_states->set_friendly_name("input_hidden_states");
+
+ auto query = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+
+ ov::PartialShape kv_shape{1, 2, 8, 16};
+ if (dynamic_kv_cache) {
+ kv_shape[2] = ov::Dimension::dynamic();
+ }
+ auto past_key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape);
+ past_key->set_friendly_name("past_keys_0");
+ auto past_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape);
+ past_value->set_friendly_name("past_values_0");
+
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ seqlens_k->set_friendly_name("past_seq_len");
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ total_sequence_length->set_friendly_name("total_seq_len");
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto position_ids_placeholder = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{0}, {});
+ auto attention_mask =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 1, 4, ov::Dimension::dynamic()});
+ attention_mask->set_friendly_name("attention_mask");
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query,
+ key,
+ value,
+ past_key,
+ past_value,
+ seqlens_k,
+ total_sequence_length,
+ cos_cache,
+ sin_cache,
+ position_ids_placeholder,
+ attention_mask},
+ 4,
+ 2,
+ 0.0f,
+ true,
+ false);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_0");
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_0");
+
+ ov::ResultVector results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)), present_key, present_value};
+ ov::ParameterVector params = {input_hidden_states,
+ query,
+ key,
+ value,
+ past_key,
+ past_value,
+ seqlens_k,
+ total_sequence_length,
+ cos_cache,
+ sin_cache,
+ attention_mask};
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_attention_bias_model");
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
+// Same wiring as build_gqa_model_with_dynamic_kv_cache(), but with sliding_window_cache=
+// true -- a dynamic axis here must be pinned by ReshapeToStaticGQA to its own
+// local_window_size-derived capacity, not the model-wide max_seq_len.
+std::shared_ptr<ov::Model> build_gqa_model_with_sliding_window_cache(size_t axis) {
+ auto input_hidden_states = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 16});
+ input_hidden_states->set_friendly_name("input_hidden_states");
+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+ position_ids->set_friendly_name("position_ids");
+
+ auto query = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+
+ ov::PartialShape kv_shape{1, 2, 8, 16};
+ kv_shape[axis] = ov::Dimension::dynamic();
+ auto past_key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape);
+ past_key->set_friendly_name("past_keys_0");
+ auto past_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape);
+ past_value->set_friendly_name("past_values_0");
+
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache},
+ /*num_heads=*/4,
+ /*kv_num_heads=*/2,
+ /*scale=*/0.0f,
+ /*do_rotary=*/true,
+ /*rotary_interleaved=*/false,
+ /*kv_cache_bit_width=*/0,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ /*local_window_size=*/6,
+ /*sliding_window_cache=*/true);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_0");
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_0");
+
+ ov::ResultVector results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)), present_key, present_value};
+ ov::ParameterVector params = {input_hidden_states,
+ position_ids,
+ query,
+ key,
+ value,
+ past_key,
+ past_value,
+ seqlens_k,
+ total_sequence_length,
+ cos_cache,
+ sin_cache};
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_sliding_window_cache_model");
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
+// A single model with TWO independent GQA layers sharing the same dynamic axis: a
+// "global" layer (sliding_window_cache=false, should take the model-wide max_seq_len)
+// and a "sliding" layer (sliding_window_cache=true, local_window_size=6, should get its
+// own small capacity). Proves the two don't bleed into each other.
+std::shared_ptr<ov::Model> build_gqa_model_with_mixed_global_and_sliding_layers() {
+ auto make_layer = [](const std::string& suffix, bool sliding) {
+ auto query = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+
+ auto past_key =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_key->set_friendly_name("past_keys_" + suffix);
+ auto past_value =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_value->set_friendly_name("past_values_" + suffix);
+
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache},
+ /*num_heads=*/4,
+ /*kv_num_heads=*/2,
+ /*scale=*/0.0f,
+ /*do_rotary=*/true,
+ /*rotary_interleaved=*/false,
+ /*kv_cache_bit_width=*/0,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ /*local_window_size=*/sliding ? 6 : -1,
+ /*sliding_window_cache=*/sliding);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_" + suffix);
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_" + suffix);
+
+ ov::ResultVector layer_results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)),
+ present_key,
+ present_value};
+ ov::ParameterVector layer_params =
+ {query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache};
+ return std::make_pair(layer_results, layer_params);
+ };
+
+ auto [global_results, global_params] = make_layer("global", /*sliding=*/false);
+ auto [sliding_results, sliding_params] = make_layer("sliding", /*sliding=*/true);
+
+ ov::ResultVector results = global_results;
+ results.insert(results.end(), sliding_results.begin(), sliding_results.end());
+ ov::ParameterVector params = global_params;
+ params.insert(params.end(), sliding_params.begin(), sliding_params.end());
+
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_mixed_global_and_sliding_model");
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
+// Same two-layer wiring as build_gqa_model_with_mixed_global_and_sliding_layers(), but
+// neither GQA op sets sliding_window_cache/local_window_size; instead the model carries
+// rt_info["framework"]["sliding_window_layers"/"sliding_window_size"] (mirroring ONNX
+// metadata_props). The "sliding" layer's query is wired via a real data dependency on the
+// "global" layer's output, so topological op order matches layer numbering (0, 1, ...) --
+// the same assumption index_gqa_layers() relies on. Unconnected branches would leave
+// relative order implementation-defined and make this test flaky.
+std::shared_ptr<ov::Model> build_gqa_model_with_rt_info_sliding_window_layers(size_t declared_sliding_window_size) {
+ auto make_layer = [](const std::string& suffix, const ov::Output<ov::Node>& prev_attention_output) {
+ ov::Output<ov::Node> query_input;
+ auto query_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ if (prev_attention_output.get_node()) {
+ // Previous layer's output is [1, 1, 64]; reshape to [1, 4, 1, 16] and fold
+ // into this layer's query so this GQA op depends on the previous one.
+ auto reshaped_prev = std::make_shared<ov::op::v1::Reshape>(
+ prev_attention_output,
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {1, 4, 1, 16}),
+ false);
+ query_input = std::make_shared<ov::op::v1::Add>(query_param, reshaped_prev);
+ } else {
+ query_input = query_param;
+ }
+
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+
+ auto past_key =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_key->set_friendly_name("past_keys_" + suffix);
+ auto past_value =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_value->set_friendly_name("past_values_" + suffix);
+
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query_input, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache},
+ /*num_heads=*/4,
+ /*kv_num_heads=*/2,
+ /*scale=*/0.0f,
+ /*do_rotary=*/true,
+ /*rotary_interleaved=*/false,
+ /*kv_cache_bit_width=*/0,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_" + suffix);
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_" + suffix);
+
+ ov::ResultVector layer_results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)),
+ present_key,
+ present_value};
+ ov::ParameterVector layer_params = {query_param,
+ key,
+ value,
+ past_key,
+ past_value,
+ seqlens_k,
+ total_sequence_length,
+ cos_cache,
+ sin_cache};
+ return std::make_tuple(layer_results, layer_params, gqa->output(0));
+ };
+
+ auto [global_results, global_params, global_attention_output] = make_layer("global", ov::Output<ov::Node>());
+ auto [sliding_results, sliding_params, sliding_attention_output] = make_layer("sliding", global_attention_output);
+
+ ov::ResultVector results = global_results;
+ results.insert(results.end(), sliding_results.begin(), sliding_results.end());
+ ov::ParameterVector params = global_params;
+ params.insert(params.end(), sliding_params.begin(), sliding_params.end());
+
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_rt_info_sliding_window_model");
+ model->set_rt_info(std::string("[1]"), "framework", "sliding_window_layers");
+ model->set_rt_info(std::string("[0]"), "framework", "full_attention_layers");
+ model->set_rt_info(std::to_string(declared_sliding_window_size), "framework", "sliding_window_size");
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
+// Same two-independent-layer shape, but with neither sliding_window_cache/
+// local_window_size attributes nor rt_info -- only each layer's SEQLENS_K/
+// TOTAL_SEQUENCE_LENGTH Parameter name optionally hints "sliding". When `name_hint` is
+// false, no hint exists and the fallback must leave every layer at max_seq_len.
+std::shared_ptr<ov::Model> build_gqa_model_with_seqlens_name_hint(bool name_hint) {
+ auto make_layer = [&](const std::string& suffix, bool sliding) {
+ auto query = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+
+ auto past_key =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_key->set_friendly_name("past_keys_" + suffix);
+ auto past_value =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 2, ov::Dimension::dynamic(), 16});
+ past_value->set_friendly_name("past_values_" + suffix);
+
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ if (name_hint) {
+ seqlens_k->set_friendly_name(sliding ? "past_seq_len_sliding" : "past_seq_len_full");
+ total_sequence_length->set_friendly_name(sliding ? "total_seq_len_sliding" : "total_seq_len_full");
+ }
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache},
+ /*num_heads=*/4,
+ /*kv_num_heads=*/2,
+ /*scale=*/0.0f,
+ /*do_rotary=*/true,
+ /*rotary_interleaved=*/false,
+ /*kv_cache_bit_width=*/0,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE,
+ ov::op::internal::GroupQueryAttentionQuantType::NONE);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_" + suffix);
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_" + suffix);
+
+ ov::ResultVector layer_results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)),
+ present_key,
+ present_value};
+ ov::ParameterVector layer_params =
+ {query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache};
+ return std::make_pair(layer_results, layer_params);
+ };
+
+ auto [global_results, global_params] = make_layer("global", /*sliding=*/false);
+ auto [sliding_results, sliding_params] = make_layer("sliding", /*sliding=*/true);
+
+ ov::ResultVector results = global_results;
+ results.insert(results.end(), sliding_results.begin(), sliding_results.end());
+ ov::ParameterVector params = global_params;
+ params.insert(params.end(), sliding_params.begin(), sliding_params.end());
+
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_seqlens_name_hint_model");
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
std::shared_ptr<ov::Model> build_unqdq_model(const ov::element::Type& input_type = ov::element::f32) {
auto input = std::make_shared<ov::op::v0::Parameter>(input_type, ov::Shape{1, 4});
auto input_low = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {-1.0f});
@@ -264,7 +721,7 @@ TEST_F(GQACompiledModelTest, AddsExpectedNpuwDefaultsBeforeInnerCompilation) {
ASSERT_NE(compiled, nullptr);
const auto& call = recorder.only_call();
- EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "REP");
+ EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "NONE");
EXPECT_EQ(call.props.at("NPUW_DEVICES").as<std::string>(), "NPU");
EXPECT_EQ(call.props.at("NPUW_ONLINE_ISOLATE").as<std::string>(), "ATTN");
EXPECT_EQ(call.props.at("NPUW_ONLINE_KEEP_BLOCKS_TAGGED").as<std::string>(), "attn");
@@ -276,6 +733,54 @@ TEST_F(GQACompiledModelTest, AddsExpectedNpuwDefaultsBeforeInnerCompilation) {
EXPECT_EQ(call.props.count("NPUW_UNFOLD_IREQS"), 0u);
}
+TEST_F(GQACompiledModelTest, DisablesOnlinePipelineForCaseV1Models) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(
+ build_full_gqa_transformer_model(4, 2, true, PositionSignal::PositionIds),
+ {},
+ recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& call = recorder.only_call();
+ EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "NONE");
+}
+
+TEST_F(GQACompiledModelTest, DisablesOnlinePipelineForCaseV0Models) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(
+ build_full_gqa_transformer_model(4, 2, true, PositionSignal::SeqLenPair),
+ {},
+ recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& call = recorder.only_call();
+ EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "NONE");
+}
+
+TEST_F(GQACompiledModelTest, KeepsDefaultOnlinePipelineForCaseV2Models) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(
+ build_full_gqa_transformer_model(4,
+ 2,
+ true,
+ PositionSignal::SeqLenPair,
+ /*with_2bit_weights=*/true),
+ {},
+ recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ // Unlike V0/V1, a 2-bit group-quantized (V2) model isn't forced to NONE -- it's left
+ // unset so the plugin-wide default (REG) applies.
+ const auto& call = recorder.only_call();
+ EXPECT_EQ(call.props.count("NPUW_ONLINE_PIPELINE"), 0u);
+}
+
TEST_F(GQACompiledModelTest, AppliesFoldOnlyAttnForGenerateStyleModels) {
RecordingFactory recorder;
std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
@@ -284,7 +789,7 @@ TEST_F(GQACompiledModelTest, AppliesFoldOnlyAttnForGenerateStyleModels) {
ASSERT_NE(compiled, nullptr);
const auto& call = recorder.only_call();
- EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "REP");
+ EXPECT_EQ(call.props.at("NPUW_ONLINE_PIPELINE").as<std::string>(), "NONE");
EXPECT_EQ(call.props.at("NPUW_DEVICES").as<std::string>(), "NPU");
EXPECT_EQ(call.props.at("NPUW_FOLD").as<std::string>(), "YES");
EXPECT_EQ(call.props.at(ov::cache_mode.name()).as<ov::CacheMode>(), ov::CacheMode::OPTIMIZE_SPEED);
@@ -347,8 +852,8 @@ TEST_F(GQACompiledModelTest, PassesGqaModelThroughWithoutDecomposition) {
ASSERT_NO_THROW(compiled = create_compiled_model(model, {}, recorder));
ASSERT_NE(compiled, nullptr);
- // GQA model is passed through unchanged — the online partitioner handles
- // isolation and folding of GQA blocks via the NPUW_FOLD_ONLY=attn path.
+ // GQA model is passed through unchanged -- the online partitioner handles isolation
+ // and folding of GQA blocks via the NPUW_FOLD_ONLY=attn path.
const auto& call = recorder.only_call();
EXPECT_GT(count_ops<ov::op::internal::GroupQueryAttention>(call.model), 0u);
}
@@ -424,4 +929,1014 @@ TEST_F(GQACompiledModelTest, ForwardsPropertyAccessToInnerCompiledModel) {
EXPECT_TRUE(compiled.get_property("NPUW_FOLD").as<bool>());
}
+TEST(GQACompiledModelSupportsTest, ReturnsTrueForWellFormedGqaTransformerModel) {
+ // supports() is the auto-dispatch gate: a well-formed GQA model must also have a
+ // dynamic KV-cache to be routed here (see GQACompiledModelSupportsTest.*DynamicShape*).
+ auto model = build_full_gqa_transformer_model();
+ make_kv_cache_dynamic(model, 2);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseForFullyStaticGqaTransformerModel) {
+ // identify_case() still classifies a fully static model as a known GQA family, but
+ // supports() must not route it here -- this wrapper only bridges a dynamic max_seq_len
+ // to the NPU's static-shape requirement.
+ auto model = build_full_gqa_transformer_model(); // no dynamic dims anywhere
+ EXPECT_NE(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::Unknown);
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseForBareGqaOpWithoutSurroundingModelContext) {
+ // The op alone (no input_hidden_states/position_ids/KV cache naming) isn't enough
+ // evidence -- avoid false positives on unrelated graphs using the op.
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::supports(build_group_query_attention_model()));
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseWhenHeadCountsAreInconsistent) {
+ // num_heads not evenly divisible by kv_num_heads: not a valid GQA grouping.
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::supports(build_full_gqa_transformer_model(5, 2)));
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseForUnconnectedActivationAndPositionIds) {
+ // A generic decoder reusing "input_hidden_states"/"position_ids" names for
+ // unrelated, disconnected tensors must not be mistaken for a GQA model: ports must
+ // actually be wired to the GQA op, not just name-matched.
+ auto input_hidden_states = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 16});
+ input_hidden_states->set_friendly_name("input_hidden_states");
+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+ position_ids->set_friendly_name("position_ids");
+
+ auto query = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 4, 1, 16});
+ auto key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 16});
+ auto past_key = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 8, 16});
+ past_key->set_friendly_name("past_keys_0");
+ auto past_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 8, 16});
+ past_value->set_friendly_name("past_values_0");
+ auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});
+ auto cos_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+ auto sin_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{32, 8});
+
+ auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(
+ ov::OutputVector{query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache,
+ sin_cache},
+ 4,
+ 2,
+ 0.0f,
+ true,
+ false);
+
+ auto present_key = std::make_shared<ov::op::v0::Result>(gqa->output(1));
+ present_key->set_friendly_name("present_keys_0");
+ auto present_value = std::make_shared<ov::op::v0::Result>(gqa->output(2));
+ present_value->set_friendly_name("present_values_0");
+
+ ov::ResultVector results = {std::make_shared<ov::op::v0::Result>(gqa->output(0)), present_key, present_value};
+ ov::ParameterVector params = {input_hidden_states,
+ position_ids,
+ query,
+ key,
+ value,
+ past_key,
+ past_value,
+ seqlens_k,
+ total_sequence_length,
+ cos_cache,
+ sin_cache};
+ auto model = std::make_shared<ov::Model>(results, params, "gqa_disconnected_ports");
+ EXPECT_EQ(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::Unknown);
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseWithoutPositionIds) {
+ auto model = build_full_gqa_transformer_model();
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "position_ids") {
+ parameter->set_friendly_name("position_ids_removed_for_test");
+ }
+ }
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, ReturnsFalseWithoutPastPresentKvCacheNaming) {
+ auto model = build_full_gqa_transformer_model();
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "past_keys_0") {
+ parameter->set_friendly_name("layer0_prior_kv_k");
+ } else if (parameter->get_friendly_name() == "past_values_0") {
+ parameter->set_friendly_name("layer0_prior_kv_v");
+ }
+ }
+ for (const auto& result : model->get_results()) {
+ if (result->get_friendly_name() == "present_keys_0") {
+ result->set_friendly_name("layer0_next_kv_k");
+ } else if (result->get_friendly_name() == "present_values_0") {
+ result->set_friendly_name("layer0_next_kv_v");
+ }
+ }
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, IdentifiesCaseV1ForExplicitPositionIdsModel) {
+ // identify_case() classifies purely from structure, regardless of shape-dynamism.
+ auto model = build_full_gqa_transformer_model(4, 2, true, PositionSignal::PositionIds);
+ EXPECT_EQ(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::V1);
+ // supports() additionally requires a dynamic KV-cache to auto-dispatch.
+ make_kv_cache_dynamic(model, 2);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, IdentifiesCaseV0ForSeqLenPairModel) {
+ // Wiring: no position_ids input at all -- RoPE
+ // position is implied by past_seq_len/total_seq_len instead.
+ // identify_case() classifies purely from structure, regardless of shape-dynamism.
+ auto model = build_full_gqa_transformer_model(4, 2, true, PositionSignal::SeqLenPair);
+ EXPECT_EQ(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::V0);
+ // supports() additionally requires a dynamic KV-cache to auto-dispatch.
+ make_kv_cache_dynamic(model, 2);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, IdentifiesCaseV2ForSeqLenPairModelWith2BitWeights) {
+ // Same seqlens_k/total_sequence_length wiring as V0, but the model also carries
+ // 2-bit group-quantized (u2) weight Parameters -- the distinctive V2 trait.
+ auto model = build_full_gqa_transformer_model(4,
+ 2,
+ true,
+ PositionSignal::SeqLenPair,
+ /*with_2bit_weights=*/true);
+ EXPECT_EQ(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::V2);
+ make_kv_cache_dynamic(model, 2);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::supports(model));
+}
+
+TEST(GQACompiledModelSupportsTest, IdentifiesCaseUnknownWithoutAnyPositionSignal) {
+ auto model = build_full_gqa_transformer_model(4, 2, true, PositionSignal::PositionIds);
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "position_ids") {
+ parameter->set_friendly_name("position_ids_removed_for_test");
+ }
+ }
+ EXPECT_EQ(ov::npuw::GQACompiledModel::identify_case(model), ov::npuw::GQACompiledModel::Case::Unknown);
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, ReturnsFalseForFullyStaticModel) {
+ auto model = build_full_gqa_transformer_model();
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, DetectsDynamicSeqLenAtAxis2) {
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, DetectsDynamicSeqLenAtAxis3) {
+ // Mirrors the --transpose_v layout, where the KV-cache dimension moves to the last axis.
+ auto model = build_gqa_model_with_dynamic_kv_cache(3);
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, IgnoresDynamicBatchAxis) {
+ // Regression test: axis 0 (batch) is never the KV-cache capacity dimension (see
+ // GroupQueryAttentionDecomposition, which reads/writes capacity at axis 2 or 3).
+ auto model = build_gqa_model_with_dynamic_kv_cache(0);
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, IgnoresDynamicKvHeadsAxis) {
+ // Same as above for axis 1 (kv_heads) -- also never the capacity dimension.
+ auto model = build_gqa_model_with_dynamic_kv_cache(1);
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, DetectsDynamicAttentionBias) {
+ // Speculative-decode-style wiring: the KV-cache itself is static, only the
+ // attention mask/bias fed into ATTENTION_BIAS carries a dynamic max_seq_len.
+ auto model = build_gqa_model_with_dynamic_attention_bias();
+ EXPECT_TRUE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST(GQACompiledModelDynamicKvCacheTest, ReturnsFalseWhenAttentionBiasIsFullyStatic) {
+ auto model = build_gqa_model_with_dynamic_attention_bias();
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "attention_mask") {
+ parameter->set_partial_shape(ov::PartialShape{1, 1, 4, 8});
+ }
+ }
+ model->validate_nodes_and_infer_types();
+ EXPECT_FALSE(ov::npuw::GQACompiledModel::has_dynamic_max_seq_len(model));
+}
+
+TEST_F(GQACompiledModelTest, ReshapesDynamicKvCacheToStaticCapacityAtAxis2) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(model, {}, recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& call = recorder.only_call();
+ EXPECT_FALSE(call.model->is_dynamic());
+ for (const auto& parameter : call.model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (name == "past_keys_0" || name == "past_values_0") {
+ EXPECT_EQ(parameter->get_shape().at(2), 8192u);
+ }
+ }
+
+ // The outer, user-facing model stays dynamic so the infer request still accepts
+ // variable-length KV-cache input.
+ EXPECT_TRUE(compiled->inputs().front().get_partial_shape().is_dynamic() ||
+ std::any_of(compiled->inputs().begin(), compiled->inputs().end(), [](const auto& input) {
+ return input.get_partial_shape().is_dynamic();
+ }));
+}
+
+TEST_F(GQACompiledModelTest, ReshapesDynamicKvCacheToStaticCapacityAtAxis3) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+ auto model = build_gqa_model_with_dynamic_kv_cache(3);
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(model, {}, recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& call = recorder.only_call();
+ EXPECT_FALSE(call.model->is_dynamic());
+ for (const auto& parameter : call.model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (name == "past_keys_0" || name == "past_values_0") {
+ EXPECT_EQ(parameter->get_shape().at(3), 8192u);
+ }
+ }
+}
+
+TEST_F(GQACompiledModelTest, GetPropertyReturnsEffectiveMaxContextLenInsteadOfThrowing) {
+ // Regression test for review comment AlexanderKalistratov#4246978192 on PR
+ // openvinotoolkit/openvino#38304: NPUW_LLM_MAX_CONTEXT_LEN is stripped before the
+ // inner CompiledModel is created, so forwarding get_property() there throws. It must
+ // be answered directly from the wrapper, reflecting the effective capacity used.
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(model, {{"NPUW_LLM_MAX_CONTEXT_LEN", "4096"}}, recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ ov::Any max_context_len;
+ ASSERT_NO_THROW(max_context_len = compiled->get_property("NPUW_LLM_MAX_CONTEXT_LEN"));
+ EXPECT_EQ(max_context_len.as<uint32_t>(), 4096u);
+}
+
+TEST_F(GQACompiledModelTest, GetPropertyReturnsEffectiveSlidingWindowCapacityInsteadOfThrowing) {
+ // Same class of bug as GetPropertyReturnsEffectiveMaxContextLenInsteadOfThrowing:
+ // NPUW_LLM_SWA_LEN is also a ROOT-only option stripped before the inner
+ // CompiledModel is created, so it must likewise be answered directly from the
+ // wrapper instead of being forwarded (and throwing).
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+
+ ASSERT_NO_THROW(
+ compiled = create_compiled_model(model, {{"NPUW_LLM_MAX_CONTEXT_LEN", "16"}, {"NPUW_LLM_SWA_LEN", "8"}}, recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ ov::Any sliding_window_len;
+ ASSERT_NO_THROW(sliding_window_len = compiled->get_property("NPUW_LLM_SWA_LEN"));
+ EXPECT_EQ(sliding_window_len.as<uint32_t>(), 8u);
+}
+
+TEST_F(GQACompiledModelTest, ReshapesDynamicAttentionBiasToStaticCapacity) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::GQACompiledModel> compiled;
+ auto model = build_gqa_model_with_dynamic_attention_bias(/*dynamic_kv_cache=*/true);
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(model, {}, recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& call = recorder.only_call();
+ EXPECT_FALSE(call.model->is_dynamic());
+ for (const auto& parameter : call.model->get_parameters()) {
+ const auto& name = parameter->get_friendly_name();
+ if (name == "attention_mask") {
+ EXPECT_EQ(parameter->get_shape().at(3), 8192u);
+ } else if (name == "past_keys_0" || name == "past_values_0") {
+ EXPECT_EQ(parameter->get_shape().at(2), 8192u);
+ }
+ }
+}
+
+TEST_F(GQACompiledModelTest, RejectsDynamicAttentionBiasAxisThatIsNotTheCapacityAxis) {
+ // Regression test for review comment AlexanderKalistratov#4246980391 on PR
+ // openvinotoolkit/openvino#38304: attention_bias's capacity dimension is always the
+ // LAST axis, never query-length. A model leaving axis 2 (query length) dynamic
+ // instead must be rejected, not silently pinned.
+ auto model = build_gqa_model_with_dynamic_attention_bias(/*dynamic_kv_cache=*/true);
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "attention_mask") {
+ // Dynamic axis moved off the last position, which is now statically 8.
+ parameter->set_partial_shape(ov::PartialShape{1, 1, ov::Dimension::dynamic(), 8});
+ }
+ }
+ model->validate_nodes_and_infer_types();
+
+ RecordingFactory recorder;
+ EXPECT_THROW(create_compiled_model(model, {}, recorder), ov::Exception);
+}
+
+namespace {
+// A minimal fake "inner" compiled model / infer request pair for exercising
+// GQAInferRequest::set_tensor()/get_tensor() end-to-end (unlike RecordingFactory/
+// MockSubCompiledModel, whose create_sync_infer_request() returns nullptr). Every port
+// gets a real, pre-allocated tensor -- mirrors TestInferRequest in failsafe.cpp.
+class FakeInnerSyncInferRequest final : public ov::ISyncInferRequest {
+public:
+ explicit FakeInnerSyncInferRequest(const std::shared_ptr<const ov::ICompiledModel>& compiled_model)
+ : ov::ISyncInferRequest(compiled_model) {
+ for (const auto& input : get_inputs()) {
+ ov::ISyncInferRequest::set_tensor(
+ input,
+ ov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));
+ }
+ for (const auto& output : get_outputs()) {
+ ov::ISyncInferRequest::set_tensor(
+ output,
+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));
+ }
+ }
+ void infer() override {}
+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {
+ return {};
+ }
+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {
+ return {};
+ }
+};
+
+class FakeInnerCompiledModel final : public ov::npuw::ICompiledModel {
+public:
+ FakeInnerCompiledModel(const std::shared_ptr<ov::Model>& model, const std::shared_ptr<const ov::IPlugin>& plugin)
+ : ov::npuw::ICompiledModel(model, plugin) {}
+ void export_model(std::ostream&) const override {}
+ std::shared_ptr<const ov::Model> get_runtime_model() const override {
+ return {};
+ }
+ void set_property(const ov::AnyMap&) override {}
+ ov::Any get_property(const std::string&) const override {
+ return {};
+ }
+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {
+ return std::make_shared<FakeInnerSyncInferRequest>(shared_from_this());
+ }
+};
+
+ov::npuw::GQACompiledModel::CompiledModelFactory fake_inner_factory() {
+ return [](const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ const ov::AnyMap&) -> std::shared_ptr<ov::npuw::ICompiledModel> {
+ return std::make_shared<FakeInnerCompiledModel>(model, plugin);
+ };
+}
+
+// build_gqa_model_with_dynamic_kv_cache()'s past_key/past_value ports are f16; this
+// helper fills a real f16 tensor so set_tensor()'s type-check passes.
+ov::SoPtr<ov::ITensor> make_f16_kv_cache_tensor(const ov::Shape& shape, float start_val = 0.f) {
+ auto tensor = ov::get_tensor_impl(ov::Tensor(ov::element::f16, shape));
+ auto* data = reinterpret_cast<ov::float16*>(tensor->data());
+ for (size_t i = 0; i < tensor->get_size(); ++i) {
+ data[i] = ov::float16(start_val + static_cast<float>(i));
+ }
+ return tensor;
+}
+} // namespace
+
+namespace {
+ov::SoPtr<ov::ITensor> make_kv_cache_tensor(const ov::Shape& shape, float start_val = 0.f) {
+ auto tensor = ov::get_tensor_impl(ov::Tensor(ov::element::f32, shape));
+ auto* data = reinterpret_cast<float*>(tensor->data());
+ for (size_t i = 0; i < tensor->get_size(); ++i) {
+ data[i] = start_val + static_cast<float>(i);
+ }
+ return tensor;
+}
+
+std::vector<float> to_vec(const ov::SoPtr<ov::ITensor>& t) {
+ const auto* data = reinterpret_cast<const float*>(t->data());
+ return std::vector<float>(data, data + t->get_size());
+}
+} // namespace
+
+TEST_F(GQACompiledModelTest, SetTensorDoesNotCorruptStaleFullCapacityCallerTensorAfterShortTensor) {
+ // Regression test: after a port's inner request got aliased onto a full-capacity
+ // caller tensor, a later set_tensor() with a *shorter* tensor left the inner request
+ // pointing at the stale, orphaned full tensor; the subsequent sync then wrote the
+ // new data straight into it, silently corrupting memory the caller might still hold.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(
+ model,
+ m_plugin,
+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},
+ fake_inner_factory());
+ ASSERT_NE(compiled, nullptr);
+
+ const uint32_t capacity = 16;
+ const size_t num_heads = 2, head_size = 16;
+ auto request = compiled->create_infer_request();
+ ASSERT_NE(request, nullptr);
+
+ ov::Output<const ov::Node> past_key_port;
+ for (const auto& input : compiled->inputs()) {
+ if (input.get_node()->get_friendly_name() == "past_keys_0") {
+ past_key_port = input;
+ }
+ }
+ ASSERT_TRUE(past_key_port.get_node());
+
+ // 1) Full-capacity caller tensor -- exercises the "exact capacity" aliasing branch.
+ auto full_tensor = make_f16_kv_cache_tensor({1, num_heads, capacity, head_size}, /*start_val=*/0.f);
+ request->set_tensor(past_key_port, full_tensor);
+ // Poison every element so we can detect any stray writes into this (now stale) tensor.
+ auto* full_data = reinterpret_cast<ov::float16*>(full_tensor->data());
+ for (size_t i = 0; i < full_tensor->get_size(); ++i) {
+ full_data[i] = ov::float16(-1.0f);
+ }
+
+ // 2) Short caller tensor for the same port -- used to leave the inner request
+ // pointing at `full_tensor` while bookkeeping moved on to the short one.
+ const size_t short_len = 4;
+ auto short_tensor = make_f16_kv_cache_tensor({1, num_heads, short_len, head_size}, /*start_val=*/0.f);
+ request->set_tensor(past_key_port, short_tensor);
+
+ ASSERT_NO_THROW(request->infer());
+
+ // The stale full-capacity caller tensor must be left untouched: it's no longer part
+ // of the live request, and the caller may still hold a reference to it.
+ for (size_t i = 0; i < full_tensor->get_size(); ++i) {
+ EXPECT_FLOAT_EQ(static_cast<float>(full_data[i]), -1.0f)
+ << "stale full-capacity caller tensor was corrupted at index " << i;
+ }
+
+ // 3) Going back to a full-capacity tensor afterwards must still work (re-alias path).
+ auto full_tensor_2 = make_f16_kv_cache_tensor({1, num_heads, capacity, head_size}, /*start_val=*/100.f);
+ ASSERT_NO_THROW(request->set_tensor(past_key_port, full_tensor_2));
+ ASSERT_NO_THROW(request->infer());
+}
+
+TEST_F(GQACompiledModelTest, SetTensorOnDynamicPresentOutputIsHonoredByGetTensorAfterInfer) {
+ // Regression test: present_* outputs (not tracked by m_dynamic_kv_cache_axes, which
+ // only covers inputs) fell through to the generic "forward as-is" branch, but
+ // refresh_present_tensors_locked() still republished its own separately-copied
+ // tensor under the same name once past_len < capacity -- diverging from the exact
+ // tensor object the caller set.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(
+ model,
+ m_plugin,
+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},
+ fake_inner_factory());
+ ASSERT_NE(compiled, nullptr);
+
+ auto request = compiled->create_infer_request();
+ ASSERT_NE(request, nullptr);
+
+ ov::Output<const ov::Node> past_key_port, present_key_port;
+ for (const auto& input : compiled->inputs()) {
+ if (input.get_node()->get_friendly_name() == "past_keys_0") {
+ past_key_port = input;
+ }
+ }
+ for (const auto& output : compiled->outputs()) {
+ if (output.get_node()->get_friendly_name() == "present_keys_0") {
+ present_key_port = output;
+ }
+ }
+ ASSERT_TRUE(past_key_port.get_node());
+ ASSERT_TRUE(present_key_port.get_node());
+
+ // A short past tensor (4 of 16 capacity) normally makes
+ // refresh_present_tensors_locked() copy the valid prefix of the present output into a
+ // fresh buffer.
+ auto short_past = make_f16_kv_cache_tensor({1, 2, 4, 16}, /*start_val=*/0.f);
+ request->set_tensor(past_key_port, short_past);
+
+ // The caller IO-binds the present output to its own full-capacity buffer, as real
+ // apps do.
+ auto caller_present = make_f16_kv_cache_tensor({1, 2, 16, 16}, /*start_val=*/0.f);
+ ASSERT_NO_THROW(request->set_tensor(present_key_port, caller_present));
+
+ ASSERT_NO_THROW(request->infer());
+
+ // get_tensor() must keep returning the exact same tensor object the caller set --
+ // not a separate, internally-copied prefix.
+ auto returned = request->get_tensor(present_key_port);
+ EXPECT_EQ(returned._ptr.get(), caller_present._ptr.get());
+}
+
+TEST_F(GQACompiledModelTest, GetTensorBeforeSetTensorReturnsZeroSizedDynamicAxisNotFullCapacity) {
+ // Regression test: get_tensor() on a dynamic-axis input, called before set_tensor(),
+ // used to allocate a fallback tensor at full static capacity -- indistinguishable
+ // from "fully populated". Other OV plugins instead zero the dynamic dim, giving an
+ // unambiguous "nothing written yet" signal.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(
+ model,
+ m_plugin,
+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},
+ fake_inner_factory());
+ ASSERT_NE(compiled, nullptr);
+
+ auto request = compiled->create_infer_request();
+ ASSERT_NE(request, nullptr);
+
+ ov::Output<const ov::Node> past_key_port;
+ for (const auto& input : compiled->inputs()) {
+ if (input.get_node()->get_friendly_name() == "past_keys_0") {
+ past_key_port = input;
+ }
+ }
+ ASSERT_TRUE(past_key_port.get_node());
+
+ auto tensor = request->get_tensor(past_key_port);
+ ASSERT_NE(tensor, nullptr);
+ const auto shape = tensor->get_shape();
+ ASSERT_EQ(shape.size(), 4u);
+ EXPECT_EQ(shape[0], 1u); // N: static
+ EXPECT_EQ(shape[1], 2u); // H: static
+ EXPECT_EQ(shape[2], 0u); // S: dynamic KV-cache axis -- must be 0, not 16
+ EXPECT_EQ(shape[3], 16u); // E: static
+}
+
+TEST_F(GQACompiledModelTest, PresentOutputLenReflectsTotalSeqLenEvenWhenPastInputNeverTouched) {
+ // Regression test: refresh_present_tensors_locked() only consulted
+ // total_sequence_length once a past_key/value tensor had already been looked up
+ // (set_tensor()'d or get_tensor()'d by the caller). A caller that queries every
+ // output tensor without ever touching the past_key/value input at all (e.g.
+ // up-front IO-binding discovery) got back the full, un-copied capacity instead --
+ // the same "ambiguous full tensor" ambiguity already fixed for inputs.
+ auto model = build_full_gqa_transformer_model(4, 2, /*do_rotary=*/true, PositionSignal::SeqLenPair);
+ make_kv_cache_dynamic(model, /*axis=*/2);
+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(
+ model,
+ m_plugin,
+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},
+ fake_inner_factory());
+ ASSERT_NE(compiled, nullptr);
+
+ auto request = compiled->create_infer_request();
+ ASSERT_NE(request, nullptr);
+
+ ov::Output<const ov::Node> total_seq_len_port, present_key_port;
+ for (const auto& input : compiled->inputs()) {
+ if (input.get_node()->get_friendly_name() == "total_seq_len") {
+ total_seq_len_port = input;
+ }
+ }
+ for (const auto& output : compiled->outputs()) {
+ if (output.get_node()->get_friendly_name() == "present_keys_0") {
+ present_key_port = output;
+ }
+ }
+ ASSERT_TRUE(total_seq_len_port.get_node());
+ ASSERT_TRUE(present_key_port.get_node());
+
+ auto total_seq_len_tensor = ov::get_tensor_impl(ov::Tensor(ov::element::i32, ov::Shape{1}));
+ *reinterpret_cast<int32_t*>(total_seq_len_tensor->data()) = 5;
+ request->set_tensor(total_seq_len_port, total_seq_len_tensor);
+
+ // past_keys_0/past_values_0 are deliberately never touched here.
+ ASSERT_NO_THROW(request->infer());
+
+ auto present_tensor = request->get_tensor(present_key_port);
+ ASSERT_NE(present_tensor, nullptr);
+ EXPECT_EQ(present_tensor->get_shape().at(2), 5u); // total_seq_len, not the 16-capacity
+}
+
+
+TEST(GQACompiledModelCopyKvCachePrefixTest, CopiesPrefixAlongAxis2LeftAligned) {
+ // [N=1, H=2, S, E=3]: src has S1=2, dst has capacity S2=4.
+ auto src = make_kv_cache_tensor({1, 2, 2, 3}, 0.f);
+ auto dst = make_kv_cache_tensor({1, 2, 4, 3}, 100.f);
+
+ ASSERT_NO_THROW(ov::npuw::GQAInferRequest::copy_kv_cache_prefix(src, dst, /*axis=*/2));
+
+ const auto dst_values = to_vec(dst);
+ // Head 0: src rows [0..5] copied into dst's first 2 (of 4) rows; head 1 likewise.
+ EXPECT_EQ(std::vector<float>(dst_values.begin(), dst_values.begin() + 6),
+ (std::vector<float>{0, 1, 2, 3, 4, 5}));
+ EXPECT_EQ(std::vector<float>(dst_values.begin() + 12, dst_values.begin() + 18),
+ (std::vector<float>{6, 7, 8, 9, 10, 11}));
+}
+
+TEST(GQACompiledModelCopyKvCachePrefixTest, CopiesPrefixAlongAxis3LeftAligned) {
+ // [N=1, H=1, E=2, S] (transpose_v layout): src has S1=2, dst has capacity S2=4.
+ auto src = make_kv_cache_tensor({1, 1, 2, 2}, 0.f);
+ auto dst = make_kv_cache_tensor({1, 1, 2, 4}, 100.f);
+
+ ASSERT_NO_THROW(ov::npuw::GQAInferRequest::copy_kv_cache_prefix(src, dst, /*axis=*/3));
+
+ const auto dst_values = to_vec(dst);
+ // Row 0 (e=0): src[0,1] into dst's first 2 (of 4) slots; row 1 (e=1) likewise.
+ EXPECT_EQ(std::vector<float>(dst_values.begin(), dst_values.begin() + 2), (std::vector<float>{0, 1}));
+ EXPECT_EQ(std::vector<float>(dst_values.begin() + 4, dst_values.begin() + 6), (std::vector<float>{2, 3}));
+}
+
+// Exercises the wire-format round trip that export_model()/import_model() rely on: outer
+// ports and the dynamic-axis map must survive a write/read cycle through the same
+// ov::npuw::orc::Stream machinery without losing data.
+TEST(GQACompiledModelSerializationTest, RoundTripsOuterModelPortsAndDynamicAxisMap) {
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+
+ std::vector<ov::Output<const ov::Node>> outer_inputs;
+ for (const auto& p : model->get_parameters()) {
+ outer_inputs.push_back(p->output(0));
+ }
+ std::vector<ov::Output<const ov::Node>> outer_outputs;
+ for (const auto& r : model->get_results()) {
+ outer_outputs.push_back(r->output(0));
+ }
+ const std::unordered_map<std::string, size_t> axis_map{{"past_keys_0", 2u}, {"past_values_0", 2u}};
+
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ ov::npuw::GQACompiledModel::write_port_list(buffer, outer_inputs);
+ ov::npuw::GQACompiledModel::write_port_list(buffer, outer_outputs);
+ {
+ auto writer = ov::npuw::orc::Stream::writer(buffer);
+ writer & axis_map;
+ }
+
+ ov::ParameterVector read_parameters = ov::npuw::GQACompiledModel::read_input_port_list(buffer);
+ ov::NodeVector read_results = ov::npuw::GQACompiledModel::read_output_port_list(buffer);
+ std::unordered_map<std::string, size_t> read_axis_map;
+ {
+ auto reader = ov::npuw::orc::Stream::reader(buffer);
+ reader & read_axis_map;
+ }
+
+ ASSERT_EQ(read_parameters.size(), outer_inputs.size());
+ ASSERT_EQ(read_results.size(), outer_outputs.size());
+ EXPECT_EQ(read_axis_map, axis_map);
+
+ // Positional correspondence matters: map_port_locked() assumes outer_inputs/outputs
+ // line up index-by-index with what's read back, with names/types/shapes preserved.
+ for (size_t i = 0; i < outer_inputs.size(); ++i) {
+ EXPECT_EQ(read_parameters[i]->get_friendly_name(), outer_inputs[i].get_node()->get_friendly_name());
+ EXPECT_EQ(read_parameters[i]->get_element_type(), outer_inputs[i].get_element_type());
+ EXPECT_EQ(read_parameters[i]->get_partial_shape(), outer_inputs[i].get_partial_shape());
+ }
+ for (size_t i = 0; i < outer_outputs.size(); ++i) {
+ EXPECT_EQ(read_results[i]->get_friendly_name(), outer_outputs[i].get_node()->get_friendly_name());
+ EXPECT_EQ(read_results[i]->get_output_element_type(0), outer_outputs[i].get_element_type());
+ EXPECT_EQ(read_results[i]->get_output_partial_shape(0), outer_outputs[i].get_partial_shape());
+ }
+
+ // The reconstructed vectors must form a valid ov::Model preserving input/output order.
+ auto rebuilt_model =
+ std::make_shared<ov::Model>(ov::as_output_vector(read_results), read_parameters, "gqa_outer_model");
+ ASSERT_EQ(rebuilt_model->inputs().size(), outer_inputs.size());
+ for (size_t i = 0; i < outer_inputs.size(); ++i) {
+ EXPECT_EQ(rebuilt_model->input(i).get_node()->get_friendly_name(),
+ outer_inputs[i].get_node()->get_friendly_name());
+ }
+
+ bool found_dynamic_past_key = false;
+ for (const auto& p : read_parameters) {
+ if (p->get_friendly_name() == "past_keys_0") {
+ found_dynamic_past_key = true;
+ EXPECT_TRUE(p->get_partial_shape().is_dynamic());
+ ASSERT_GT(p->get_partial_shape().rank().get_length(), 2);
+ EXPECT_TRUE(p->get_partial_shape()[2].is_dynamic());
+ }
+ }
+ EXPECT_TRUE(found_dynamic_past_key);
+}
+
+// Regression test: ORT/OVEP matches ports via tensor names (Output::get_names()), not
+// friendly name. A reconstructed port with dropped tensor names passes friendly-name
+// assertions but still breaks ORT-side lookup -- crashed with ACCESS_VIOLATION before.
+TEST(GQACompiledModelSerializationTest, RoundTripsTensorNamesSeparatelyFromFriendlyName) {
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 32, -1, 64});
+ param->set_friendly_name("past_keys_0");
+ param->output(0).get_tensor().set_names({"past_key_values.0.key"});
+ std::vector<ov::Output<const ov::Node>> ports{param->output(0)};
+
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ ov::npuw::GQACompiledModel::write_port_list(buffer, ports);
+ auto read_back = ov::npuw::GQACompiledModel::read_input_port_list(buffer);
+
+ ASSERT_EQ(read_back.size(), 1u);
+ EXPECT_EQ(read_back[0]->get_friendly_name(), "past_keys_0");
+ EXPECT_EQ(read_back[0]->output(0).get_names(), std::unordered_set<std::string>{"past_key_values.0.key"});
+}
+
+// Regression test: import_model()'s outer_model is a dummy carcass with no real
+// GroupQueryAttention ops, so find_total_sequence_length_param_name()/
+// find_present_to_past_param_names() can't be re-run on it after a cache hit -- they'd
+// silently find nothing, and refresh_present_tensors_locked() would then fall back to
+// full capacity (returning uncopied/stale KV-cache content to the caller, which crashed
+// an ORT consumer expecting the real valid length). export_model() must therefore write
+// these two fields out directly, and import_model() must read them back instead of
+// recomputing.
+TEST(GQACompiledModelSerializationTest, RoundTripsTotalSeqLenParamNameAndPresentToPastMap) {
+ const std::optional<std::string> total_seq_len_param_name{"total_seq_len"};
+ const std::unordered_map<std::string, std::string> present_to_past{
+ {"present_keys_0/sink_port_0", "past_keys_0"},
+ {"present_values_0/sink_port_0", "past_values_0"},
+ };
+
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ {
+ auto writer = ov::npuw::orc::Stream::writer(buffer);
+ auto mutable_name = total_seq_len_param_name;
+ auto mutable_map = present_to_past;
+ writer & mutable_name;
+ writer & mutable_map;
+ }
+
+ std::optional<std::string> read_name;
+ std::unordered_map<std::string, std::string> read_map;
+ {
+ auto reader = ov::npuw::orc::Stream::reader(buffer);
+ reader & read_name;
+ reader & read_map;
+ }
+
+ EXPECT_EQ(read_name, total_seq_len_param_name);
+ EXPECT_EQ(read_map, present_to_past);
+}
+
+// Guards the string-based shape/type round trip for a *bounded* dynamic dimension
+// (e.g. "1..8192") and a non-f32 element type, both common for real attention-mask/
+// KV-cache ports.
+TEST(GQACompiledModelSerializationTest, RoundTripsBoundedDynamicDimensionAndNonF32Type) {
+ const ov::PartialShape shape{1, 32, ov::Dimension(1, 8192), 64};
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, shape);
+ param->set_friendly_name("attention_bias");
+ std::vector<ov::Output<const ov::Node>> ports{param->output(0)};
+
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ ov::npuw::GQACompiledModel::write_port_list(buffer, ports);
+ auto read_back = ov::npuw::GQACompiledModel::read_input_port_list(buffer);
+
+ ASSERT_EQ(read_back.size(), 1u);
+ EXPECT_EQ(read_back[0]->get_friendly_name(), "attention_bias");
+ EXPECT_EQ(read_back[0]->get_element_type(), ov::element::f16);
+ ASSERT_EQ(read_back[0]->get_partial_shape().rank().get_length(), 4);
+ EXPECT_EQ(read_back[0]->get_partial_shape()[2], ov::Dimension(1, 8192));
+ EXPECT_EQ(read_back[0]->get_partial_shape(), shape);
+}
+
+TEST(ReshapeToStaticGQATest, PinsSlidingWindowCacheToItsOwnSmallerCapacityNotModelWideMax) {
+ // Regression test for review comment ankitm3k#4230466592 on PR
+ // openvinotoolkit/openvino#38304: sliding_window_cache=true means the KV-cache is a
+ // fixed-capacity ring buffer, so it must get its own 16-aligned+headroom capacity
+ // (6 -> 16 -> 32), independent of the much larger model-wide max_seq_len.
+ auto model = build_gqa_model_with_sliding_window_cache(/*axis=*/2);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto it = std::find_if(params.begin(), params.end(), [](const auto& parameter) {
+ return parameter->get_friendly_name() == "past_keys_0";
+ });
+ ASSERT_NE(it, params.end());
+ EXPECT_EQ((*it)->get_partial_shape(), ov::PartialShape({1, 2, 32, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, MixedGlobalAndSlidingLayersKeepDistinctCapacities) {
+ // The sliding layer's small capacity must not leak onto the global layer's, and vice
+ // versa -- both layers share the same model-wide max_seq_len argument, but only the
+ // global layer should actually end up pinned to it.
+ auto model = build_gqa_model_with_mixed_global_and_sliding_layers();
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto shape_of = [&](const std::string& name) {
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end(), "parameter '", name, "' not found");
+ return (*it)->get_partial_shape();
+ };
+
+ EXPECT_EQ(shape_of("past_keys_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_values_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_keys_sliding"), ov::PartialShape({1, 2, 32, 16}));
+ EXPECT_EQ(shape_of("past_values_sliding"), ov::PartialShape({1, 2, 32, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, UsesRtInfoSlidingWindowLayersAsExactCapacityNotMaxSeqLen) {
+ // Models declare windowing via rt_info["framework"]["sliding_window_layers"/
+ // "sliding_window_size"] instead of op attributes. The declared size (2048) must be
+ // used VERBATIM (exact contract with host eviction logic), while max_seq_len (8192)
+ // still applies to the layer not listed in sliding_window_layers.
+ auto model = build_gqa_model_with_rt_info_sliding_window_layers(/*declared_sliding_window_size=*/2048);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto shape_of = [&](const std::string& name) {
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end(), "parameter '", name, "' not found");
+ return (*it)->get_partial_shape();
+ };
+
+ EXPECT_EQ(shape_of("past_keys_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_values_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_keys_sliding"), ov::PartialShape({1, 2, 2048, 16}));
+ EXPECT_EQ(shape_of("past_values_sliding"), ov::PartialShape({1, 2, 2048, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, RtInfoSlidingWindowSizeIsCappedByMaxSeqLen) {
+ // A declared sliding_window_size larger than the configured max_seq_len must not
+ // blow past the model-wide context budget -- cap it instead of pinning it verbatim.
+ auto model = build_gqa_model_with_rt_info_sliding_window_layers(/*declared_sliding_window_size=*/4096);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/1024);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto it = std::find_if(params.begin(), params.end(), [](const auto& parameter) {
+ return parameter->get_friendly_name() == "past_keys_sliding";
+ });
+ ASSERT_NE(it, params.end());
+ EXPECT_EQ((*it)->get_partial_shape(), ov::PartialShape({1, 2, 1024, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, SeqlensNameHintFallbackAppliesConfiguredDefaultCapacity) {
+ // Last-resort case: no rt_info, no op attribute -- only a shared SEQLENS_K/
+ // TOTAL_SEQUENCE_LENGTH name hinting "sliding" plus a caller-configured default.
+ // The sliding layer gets the configured default; the full layer keeps max_seq_len.
+ auto model = build_gqa_model_with_seqlens_name_hint(/*name_hint=*/true);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192, /*default_sliding_window_capacity=*/2048);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto shape_of = [&](const std::string& name) {
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end(), "parameter '", name, "' not found");
+ return (*it)->get_partial_shape();
+ };
+
+ EXPECT_EQ(shape_of("past_keys_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_values_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_keys_sliding"), ov::PartialShape({1, 2, 2048, 16}));
+ EXPECT_EQ(shape_of("past_values_sliding"), ov::PartialShape({1, 2, 2048, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, SeqlensNameHintFallbackIsOptInOnly) {
+ // The fallback must do nothing unless the caller configured a default -- never
+ // guessed implicitly, to avoid silently reshaping a model that wasn't asked for.
+ auto model = build_gqa_model_with_seqlens_name_hint(/*name_hint=*/true);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto it = std::find_if(params.begin(), params.end(), [](const auto& parameter) {
+ return parameter->get_friendly_name() == "past_keys_sliding";
+ });
+ ASSERT_NE(it, params.end());
+ EXPECT_EQ((*it)->get_partial_shape(), ov::PartialShape({1, 2, 8192, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, SeqlensNameHintFallbackDoesNothingWithoutNameHint) {
+ // No rt_info, no op attribute, no "sliding" name hint -- no signal to act on, so a
+ // configured default must not affect either layer.
+ auto model = build_gqa_model_with_seqlens_name_hint(/*name_hint=*/false);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/8192, /*default_sliding_window_capacity=*/2048);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+
+ const auto& params = model->get_parameters();
+ auto shape_of = [&](const std::string& name) {
+ auto it = std::find_if(params.begin(), params.end(), [&](const auto& parameter) {
+ return parameter->get_friendly_name() == name;
+ });
+ OPENVINO_ASSERT(it != params.end(), "parameter '", name, "' not found");
+ return (*it)->get_partial_shape();
+ };
+
+ EXPECT_EQ(shape_of("past_keys_global"), ov::PartialShape({1, 2, 8192, 16}));
+ EXPECT_EQ(shape_of("past_keys_sliding"), ov::PartialShape({1, 2, 8192, 16}));
+}
+
+TEST(ReshapeToStaticGQATest, AllowsOrdinaryDynamicKvCacheWithoutSlidingWindowCache) {
+ // Sanity check: ordinary (sliding_window_cache=false) dynamic KV-cache models must
+ // keep reshaping successfully -- the new check must not become overly broad.
+ auto model = build_gqa_model_with_dynamic_kv_cache(/*axis=*/2);
+ ov::npuw::ReshapeToStaticGQA reshape_to_static_gqa(/*max_seq_len=*/16);
+ EXPECT_NO_THROW(reshape_to_static_gqa.run_on_model(model));
+}
+
+TEST(GQACompiledModelPresentAxisTest, FindsDynamicPresentOutputsAtAxis2) {
+ // past_keys_0/past_values_0's dynamic axis propagates (present = past + current) to
+ // present_keys_0/present_values_0 becoming dynamic too.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ std::vector<ov::Output<const ov::Node>> outputs;
+ for (const auto& result : model->get_results()) {
+ std::shared_ptr<const ov::Node> node = result;
+ outputs.emplace_back(node, 0);
+ }
+ auto axes = ov::npuw::GQACompiledModel::find_dynamic_kv_cache_output_axes(outputs);
+ ASSERT_EQ(axes.count("present_keys_0"), 1u);
+ ASSERT_EQ(axes.count("present_values_0"), 1u);
+ EXPECT_EQ(axes.at("present_keys_0"), 2u);
+ EXPECT_EQ(axes.at("present_values_0"), 2u);
+}
+
+TEST(GQACompiledModelPresentAxisTest, IgnoresFullyStaticPresentOutputs) {
+ auto model = build_full_gqa_transformer_model(); // no dynamic dims anywhere
+ std::vector<ov::Output<const ov::Node>> outputs;
+ for (const auto& result : model->get_results()) {
+ std::shared_ptr<const ov::Node> node = result;
+ outputs.emplace_back(node, 0);
+ }
+ auto axes = ov::npuw::GQACompiledModel::find_dynamic_kv_cache_output_axes(outputs);
+ EXPECT_TRUE(axes.empty());
+}
+
+TEST(GQACompiledModelPresentAxisTest, MatchesSinkPortSuffixedFriendlyName) {
+ // Mirrors the ONNX frontend's Result-node convention: appends "/sink_port_0" to the
+ // friendly name while the tensor name stays clean.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ for (const auto& result : model->get_results()) {
+ if (result->get_friendly_name() == "present_keys_0") {
+ result->set_friendly_name("present_keys_0/sink_port_0");
+ }
+ }
+ std::vector<ov::Output<const ov::Node>> outputs;
+ for (const auto& result : model->get_results()) {
+ std::shared_ptr<const ov::Node> node = result;
+ outputs.emplace_back(node, 0);
+ }
+ auto axes = ov::npuw::GQACompiledModel::find_dynamic_kv_cache_output_axes(outputs);
+ ASSERT_EQ(axes.count("present_keys_0/sink_port_0"), 1u);
+ EXPECT_EQ(axes.at("present_keys_0/sink_port_0"), 2u);
+}
+
+TEST(GQACompiledModelPresentAxisTest, MatchesDotStylePresentNamingScheme) {
+ // Regression test: identify_case() accepts dot-style present naming (e.g.
+ // "present.0.key"), but find_dynamic_kv_cache_output_axes() used to only match
+ // "present_key"/"present_value" -- leaving dot-style present outputs uncopied and
+ // get_tensor() returning the full static inner tensor.
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ for (const auto& result : model->get_results()) {
+ if (result->get_friendly_name() == "present_keys_0") {
+ result->set_friendly_name("present.0.key");
+ } else if (result->get_friendly_name() == "present_values_0") {
+ result->set_friendly_name("present.0.value");
+ }
+ }
+ std::vector<ov::Output<const ov::Node>> outputs;
+ for (const auto& result : model->get_results()) {
+ std::shared_ptr<const ov::Node> node = result;
+ outputs.emplace_back(node, 0);
+ }
+ auto axes = ov::npuw::GQACompiledModel::find_dynamic_kv_cache_output_axes(outputs);
+ ASSERT_EQ(axes.count("present.0.key"), 1u);
+ ASSERT_EQ(axes.count("present.0.value"), 1u);
+ EXPECT_EQ(axes.at("present.0.key"), 2u);
+ EXPECT_EQ(axes.at("present.0.value"), 2u);
+}
+
+// find_present_to_past_param_names() derives the present->past mapping from the GQA
+// op's own graph connections, not string name-rewriting -- so it works regardless of
+// the model's actual naming convention.
+TEST(GQACompiledModelPresentToPastParamNamesTest, MapsUnderscoreStyleNames) {
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ auto map = ov::npuw::GQACompiledModel::find_present_to_past_param_names(model);
+ ASSERT_EQ(map.count("present_keys_0"), 1u);
+ ASSERT_EQ(map.count("present_values_0"), 1u);
+ EXPECT_EQ(map.at("present_keys_0"), "past_keys_0");
+ EXPECT_EQ(map.at("present_values_0"), "past_values_0");
+}
+
+// Regression test: onnxruntime-genai dot-style naming has present outputs
+// "present.0.key"/"present.0.value" but past inputs "past_key_values.0.key"/
+// "past_key_values.0.value" -- a naive substring swap would wrongly produce "past.0.key",
+// matching no real Parameter and silently defeating the present->past length lookup.
+TEST(GQACompiledModelPresentToPastParamNamesTest, MapsDotStyleNamesNotMatchingSubstringSwap) {
+ auto model = build_gqa_model_with_dynamic_kv_cache(2);
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "past_keys_0") {
+ parameter->set_friendly_name("past_key_values.0.key");
+ } else if (parameter->get_friendly_name() == "past_values_0") {
+ parameter->set_friendly_name("past_key_values.0.value");
+ }
+ }
+ for (const auto& result : model->get_results()) {
+ if (result->get_friendly_name() == "present_keys_0") {
+ result->set_friendly_name("present.0.key");
+ } else if (result->get_friendly_name() == "present_values_0") {
+ result->set_friendly_name("present.0.value");
+ }
+ }
+ auto map = ov::npuw::GQACompiledModel::find_present_to_past_param_names(model);
+ ASSERT_EQ(map.count("present.0.key"), 1u);
+ ASSERT_EQ(map.count("present.0.value"), 1u);
+ EXPECT_EQ(map.at("present.0.key"), "past_key_values.0.key");
+ EXPECT_EQ(map.at("present.0.value"), "past_key_values.0.value");
+}
+
} // namespace