OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] GQA dynamic: avoid early zero-initialization (#39900)
Dmitry Matveev7d511a670731
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.cppindex 4ea9b53954f..446d1ca8f55 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@@ -844,32 +844,10 @@ void ov::npuw::GQAInferRequest::ensure_inner_request_locked() const {if (m_inner_request == nullptr) {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;+ [[maybe_unused]] 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.- [[maybe_unused]] size_t zeroed_count = 0; // only read by the developer-build GQA_TRACE below- 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)");}}@@ -1164,7 +1142,6 @@ ov::SoPtr<ov::ITensor> ov::npuw::GQAInferRequest::get_tensor(const ov::Output<co// 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());@@ -1175,8 +1152,7 @@ ov::SoPtr<ov::ITensor> ov::npuw::GQAInferRequest::get_tensor(const ov::Output<co// 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));+ auto private_tensor = ov::SoPtr<ov::ITensor>(ov::make_tensor(port.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());@@ -1216,14 +1192,14 @@ void ov::npuw::GQAInferRequest::set_tensor(const ov::Output<const ov::Node>& por// 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(),+ const auto inner_shape = map_port_locked(port).get_shape();+ OPENVINO_ASSERT(tensor->get_shape() == inner_shape,"GQA present output '",name,"' shape ",tensor->get_shape()," does not match the compiled static shape ",- inner_tensor->get_shape());+ inner_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);@@ -1240,13 +1216,21 @@ void ov::npuw::GQAInferRequest::set_tensor(const ov::Output<const ov::Node>& por// 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.+ // Otherwise defer padding allocation and 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& inner_port = map_port_locked(port);+ const auto inner_shape = inner_port.get_shape();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());+ const auto capacity = inner_shape.at(axis);+ GQA_TRACE(" -> dynamic-axis input, axis=" << axis << " requested_len=" << requested_len+ << " capacity=" << capacity << " inner_tensor_shape=" << inner_shape);+ auto expected_shape = inner_shape;+ expected_shape.at(axis) = requested_len;+ OPENVINO_ASSERT(+ tensor->get_element_type() == inner_port.get_element_type() && tensor->get_shape() == expected_shape,+ "GQA input '",+ name,+ "' must match the compiled element type and non-capacity dimensions");OPENVINO_ASSERT(requested_len <= capacity,"GQA KV-cache '",name,@@ -1256,29 +1240,12 @@ void ov::npuw::GQAInferRequest::set_tensor(const ov::Output<const ov::Node>& porcapacity,") 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_private_buffers.erase(name);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;@@ -1292,30 +1259,22 @@ void ov::npuw::GQAInferRequest::sync_dynamic_kv_cache_tensors_locked() const {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());+ const auto& inner_port = map_port_locked(*port_it);+ const auto inner_shape = inner_port.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);+ const auto src_len =+ tensor_it == m_dynamic_kv_cache_tensors.end() ? 0u : tensor_it->second->get_shape().at(axis);+ const auto capacity = inner_shape.at(axis);OPENVINO_ASSERT(src_len <= capacity,"GQA KV-cache '",name,@@ -1324,14 +1283,37 @@ void ov::npuw::GQAInferRequest::sync_dynamic_kv_cache_tensors_locked() const {" exceeds the static capacity (",capacity,") it was compiled with");- ov::npuw::GQAInferRequest::copy_kv_cache_prefix(tensor_it->second, inner_tensor, axis);+ if (tensor_it != m_dynamic_kv_cache_tensors.end()) {+ auto expected_shape = inner_shape;+ expected_shape.at(axis) = src_len;+ OPENVINO_ASSERT(tensor_it->second->get_element_type() == inner_port.get_element_type() &&+ tensor_it->second->get_shape() == expected_shape,+ "GQA input '",+ name,+ "' must match the compiled element type and non-capacity dimensions");+ if (src_len == capacity) {+ m_inner_request->set_tensor(inner_port, tensor_it->second);+ m_dynamic_kv_cache_private_buffers.erase(name);+ continue;+ }+ }+ auto& private_buffer = m_dynamic_kv_cache_private_buffers[name];+ if (!private_buffer) {+ private_buffer = ov::SoPtr<ov::ITensor>(ov::make_tensor(inner_port.get_element_type(), inner_shape));+ if (private_buffer->get_byte_size() != 0) {+ std::memset(private_buffer->data(), 0, private_buffer->get_byte_size());+ }+ }+ m_inner_request->set_tensor(inner_port, private_buffer);+ if (tensor_it != m_dynamic_kv_cache_tensors.end()) {+ ov::npuw::GQAInferRequest::copy_kv_cache_prefix(tensor_it->second, private_buffer, axis);+ }}}void ov::npuw::GQAInferRequest::check_tensors() const {std::lock_guard<std::mutex> lock(m_mutex);- // Trigger lazy inner request initialization; the JustInferRequest constructor- // allocates all sub-tensors during construction, so nothing more is needed here.+ // Keep top-level I/O lazy until the caller binds tensors or inference needs them.ensure_inner_request_locked();}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.hppindex b86fa0cfafe..39fcb1827ec 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@@ -47,11 +47,8 @@ private: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.+ // Static-capacity fallback buffers, allocated only when inference needs padding.+ // Released when a full-capacity caller tensor replaces the fallback.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().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.cppindex 821bba7c0a8..bc243acf4a4 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@@ -11,6 +11,8 @@#include <memory>#include <sstream>#include <string>+#include <unordered_map>+#include <unordered_set>#include <vector>#include "common_test_utils/test_assertions.hpp"@@ -1505,25 +1507,31 @@ TEST_F(GQACompiledModelTest, RejectsDynamicAttentionBiasAxisThatIsNotTheCapacity}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.+struct FakeInnerRequestState {+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> tensors;+ std::unordered_set<std::string> allocated_ports;+};+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())));+ FakeInnerSyncInferRequest(const std::shared_ptr<const ov::ICompiledModel>& compiled_model,+ std::shared_ptr<FakeInnerRequestState> state)+ : ov::ISyncInferRequest(compiled_model),+ m_state(std::move(state)) {}+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ const auto& name = port.get_node()->get_friendly_name();+ auto& tensor = m_state->tensors[name];+ if (!tensor) {+ tensor = ov::get_tensor_impl(ov::Tensor(port.get_element_type(), port.get_shape()));+ std::fill_n(static_cast<uint8_t*>(tensor->data()), tensor->get_byte_size(), uint8_t{0});+ m_state->allocated_ports.insert(name);}+ return tensor;}+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ m_state->tensors[port.get_node()->get_friendly_name()] = tensor;+ }+ void check_tensors() const override {}void infer() override {}std::vector<ov::ProfilingInfo> get_profiling_info() const override {return {};@@ -1531,12 +1539,18 @@ public:std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {return {};}++private:+ std::shared_ptr<FakeInnerRequestState> m_state;};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) {}+ FakeInnerCompiledModel(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ std::shared_ptr<FakeInnerRequestState> state)+ : ov::npuw::ICompiledModel(model, plugin),+ m_state(std::move(state)) {}void export_model(std::ostream&) const override {}std::shared_ptr<const ov::Model> get_runtime_model() const override {return {};@@ -1546,15 +1560,19 @@ public:return {};}std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {- return std::make_shared<FakeInnerSyncInferRequest>(shared_from_this());+ return std::make_shared<FakeInnerSyncInferRequest>(shared_from_this(), m_state);}++private:+ std::shared_ptr<FakeInnerRequestState> m_state;};-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);+ov::npuw::GQACompiledModel::CompiledModelFactory fake_inner_factory(+ std::shared_ptr<FakeInnerRequestState> state = std::make_shared<FakeInnerRequestState>()) {+ return [state](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, state);};}@@ -1586,6 +1604,93 @@ std::vector<float> to_vec(const ov::SoPtr<ov::ITensor>& t) {}} // namespace+TEST_F(GQACompiledModelTest, SharedCallerKvBuffersDoNotAllocateInnerKvTensors) {+ for (const size_t axis : {2u, 3u}) {+ auto state = std::make_shared<FakeInnerRequestState>();+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(+ build_gqa_model_with_dynamic_kv_cache(axis),+ m_plugin,+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},+ fake_inner_factory(state));+ auto request = compiled->create_infer_request();+ request->query_state();+ EXPECT_TRUE(state->tensors.empty());++ for (const auto& input : compiled->inputs()) {+ const auto& name = input.get_node()->get_friendly_name();+ if (name != "past_keys_0" && name != "past_values_0") {+ continue;+ }+ auto empty = request->get_tensor(input);+ EXPECT_EQ(empty->get_shape().at(axis), 0u);+ EXPECT_EQ(state->tensors.count(name), 0u);+ auto shape = empty->get_shape();+ shape.at(axis) = 16;+ auto tensor = make_f16_kv_cache_tensor(shape, 1.f);+ request->set_tensor(input, tensor);+ const auto output_name = name == "past_keys_0" ? "present_keys_0" : "present_values_0";+ const auto output = std::find_if(compiled->outputs().begin(), compiled->outputs().end(), [&](const auto& port) {+ return port.get_node()->get_friendly_name() == output_name;+ });+ ASSERT_NE(output, compiled->outputs().end());+ request->set_tensor(*output, tensor);+ EXPECT_EQ(state->tensors.at(name)._ptr, tensor._ptr);+ EXPECT_EQ(state->tensors.at(output_name)._ptr, tensor._ptr);+ }+ EXPECT_TRUE(state->allocated_ports.empty());+ ASSERT_NO_THROW(request->infer());+ for (const auto* name : {"past_keys_0", "past_values_0", "present_keys_0", "present_values_0"}) {+ EXPECT_EQ(state->allocated_ports.count(name), 0u);+ }+ }+}++TEST_F(GQACompiledModelTest, PaddingBufferIsLazyZeroedAndReleasedWhenReplaced) {+ for (const size_t axis : {2u, 3u}) {+ auto state = std::make_shared<FakeInnerRequestState>();+ auto compiled = std::make_shared<ov::npuw::GQACompiledModel>(+ build_gqa_model_with_dynamic_kv_cache(axis),+ m_plugin,+ ov::AnyMap{{"NPUW_GQA", "YES"}, {"NPUW_LLM_MAX_CONTEXT_LEN", "16"}},+ fake_inner_factory(state));+ auto request = compiled->create_infer_request();+ const auto input = std::find_if(compiled->inputs().begin(), compiled->inputs().end(), [](const auto& port) {+ return port.get_node()->get_friendly_name() == "past_keys_0";+ });+ ASSERT_NE(input, compiled->inputs().end());+ auto shape = request->get_tensor(*input)->get_shape();+ shape.at(axis) = 4;+ auto short_tensor = make_f16_kv_cache_tensor(shape, 1.f);+ request->set_tensor(*input, short_tensor);+ EXPECT_TRUE(state->tensors.empty());+ ASSERT_NO_THROW(request->infer());+ const auto& padded = state->tensors.at("past_keys_0");+ EXPECT_EQ(padded->get_shape().at(axis), 16u);+ const auto* data = static_cast<const ov::float16*>(padded->data());+ const auto* source_data = static_cast<const ov::float16*>(short_tensor->data());+ const auto row_size = padded->get_shape().back();+ for (size_t index = 0; index < padded->get_size(); ++index) {+ const auto sequence_index = axis == 2 ? (index / row_size) % 16 : index % 16;+ if (sequence_index >= 4) {+ EXPECT_FLOAT_EQ(static_cast<float>(data[index]), 0.f);+ } else {+ const auto source_index = axis == 2 ? (index / (16 * row_size)) * 4 * row_size + index % (16 * row_size)+ : (index / 16) * 4 + index % 16;+ EXPECT_FLOAT_EQ(static_cast<float>(data[index]), static_cast<float>(source_data[source_index]));+ }+ }+ const auto& untouched = state->tensors.at("past_values_0");+ const auto* untouched_data = static_cast<const ov::float16*>(untouched->data());+ for (size_t index = 0; index < untouched->get_size(); ++index) {+ EXPECT_FLOAT_EQ(static_cast<float>(untouched_data[index]), 0.f);+ }+ std::weak_ptr<ov::ITensor> old_padding = padded._ptr;+ shape.at(axis) = 16;+ request->set_tensor(*input, make_f16_kv_cache_tensor(shape));+ EXPECT_TRUE(old_padding.expired());+ }+}+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