Skip to content

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

[GPU] Defer allocations of static inputs in SyncInferRequest (#36578)

Bartlomiej Filipekf67f8c097f60
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/sync_infer_request.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/sync_infer_request.hpp
index 8855e87ad3c..4ad6087f03d 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/sync_infer_request.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/sync_infer_request.hpp
@@ -15,6 +15,8 @@
#include <vector>
#include <memory>
#include <atomic>
+#include <mutex>
+#include <shared_mutex>
namespace ov::intel_gpu {
@@ -59,6 +61,38 @@ struct TensorWrapper {
size_t actual_size;
};
+// Couples the lazily-allocated user-input map with its mutex so the map is reachable only
+// through a held lock: read() takes a shared lock (read-only view), write() an exclusive one.
+class GuardedMap {
+public:
+ using map_t = std::unordered_map<size_t, TensorWrapper>;
+
+ GuardedMap() = default;
+ GuardedMap(const GuardedMap&) = delete;
+
+ template <typename LockType, typename MapRef>
+ class Accessor {
+ public:
+ Accessor(LockType lock, MapRef map) : m_lock(std::move(lock)), m_map(map) {}
+ auto operator->() { return &m_map; }
+ MapRef operator*() { return m_map; }
+ private:
+ LockType m_lock;
+ MapRef m_map;
+ };
+
+ Accessor<std::shared_lock<std::shared_mutex>, const map_t&> read() const {
+ return { std::shared_lock<std::shared_mutex>(m_mutex), m_map};
+ }
+ Accessor<std::unique_lock<std::shared_mutex>, map_t&> write() {
+ return {std::unique_lock<std::shared_mutex>(m_mutex), m_map};
+ }
+
+private:
+ mutable std::shared_mutex m_mutex;
+ map_t m_map;
+};
+
class SyncInferRequest : public ov::ISyncInferRequest {
public:
using Ptr = std::shared_ptr<SyncInferRequest>;
@@ -89,7 +123,13 @@ public:
private:
void check_tensors() const override;
- std::unordered_map<size_t, TensorWrapper> m_user_inputs;
+ // Materializes a deferred (lazy) input slot on first access. Const-safe; takes
+ // an exclusive lock on m_user_inputs.
+ void ensure_input_allocated(size_t input_idx) const;
+
+ // Mutable so the const lazy-alloc path (get_tensor) can take a write lock.
+ // Self-guarding: reachable only via read()/write(), which lock internally.
+ mutable GuardedMap m_user_inputs;
std::unordered_map<size_t, TensorWrapper> m_user_outputs;
std::unordered_map<size_t, TensorWrapper> m_plugin_inputs;
@@ -132,7 +172,7 @@ private:
void allocate_inputs();
void allocate_outputs();
void allocate_states();
- void allocate_input(const ov::Output<const ov::Node>& port, size_t input_idx);
+ void allocate_input(size_t input_idx, GuardedMap::map_t& user_inputs);
void allocate_output(const ov::Output<const ov::Node>& port, size_t output_idx);
cldnn::event::ptr copy_output_data(cldnn::memory::ptr src, ov::ITensor& dst) const;
diff --git a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
index a56d4b92537..80447a6e91b 100644
--- a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
+++ b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
@@ -31,6 +31,8 @@
#include <unordered_set>
#include <functional>
#include <utility>
+#include <mutex>
+#include <shared_mutex>
namespace {
@@ -211,7 +213,8 @@ void SyncInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
bool is_input = port_info.type == ov::ISyncInferRequest::FoundPort::Type::INPUT;
if (is_input) {
- update_tensors_maps(port_index, m_user_inputs, m_plugin_inputs, tensor);
+ auto inputs = m_user_inputs.write();
+ update_tensors_maps(port_index, *inputs, m_plugin_inputs, tensor);
} else {
update_tensors_maps(port_index, m_user_outputs, m_plugin_outputs, tensor);
}
@@ -243,8 +246,23 @@ ov::SoPtr<ov::ITensor> SyncInferRequest::get_tensor(const ov::Output<const ov::N
bool is_input = port_info.type == ov::ISyncInferRequest::FoundPort::Type::INPUT;
size_t port_index = port_info.idx;
if (is_input) {
- OPENVINO_ASSERT(m_user_inputs.count(port_index) == 1, "[GPU] Input tensor with index ", port_index, " is not found");
- return { m_user_inputs.at(port_index).ptr, nullptr };
+ std::shared_ptr<ov::ITensor> tensor_ptr;
+ {
+ auto inputs = m_user_inputs.read();
+ auto it = inputs->find(port_index);
+ OPENVINO_ASSERT(it != inputs->end(), "[GPU] Input tensor with index ", port_index, " is not found");
+ tensor_ptr = it->second.ptr;
+ }
+ // Materialize the reserved slot on first access.
+ if (!tensor_ptr) {
+ ensure_input_allocated(port_index);
+ GPU_DEBUG_LOG << "[lazy alloc] input " << port_index
+ << " shape: " << port.get_partial_shape()
+ << " allocated at get_tensor" << std::endl;
+ auto inputs = m_user_inputs.read();
+ tensor_ptr = inputs->at(port_index).ptr;
+ }
+ return { tensor_ptr, nullptr };
} else {
OPENVINO_ASSERT(m_user_outputs.count(port_index) == 1, "[GPU] Output tensor with index ", port_index, " is not found");
return { m_user_outputs.at(port_index).ptr, nullptr };
@@ -254,8 +272,17 @@ ov::SoPtr<ov::ITensor> SyncInferRequest::get_tensor(const ov::Output<const ov::N
void SyncInferRequest::check_tensors() const {
const auto& inputs = get_compiled_model()->inputs();
for (size_t i = 0; i < inputs.size(); i++) {
- if (!is_batched_input(inputs[i]))
+ if (!is_batched_input(inputs[i])) {
+ // Skip not-yet-materialized lazy slots.
+ const bool not_allocated = [&] {
+ auto inputs = m_user_inputs.read();
+ auto it = inputs->find(i);
+ return it != inputs->end() && !it->second.ptr;
+ }();
+ if (not_allocated)
+ continue;
check_tensor(inputs[i], get_tensor_ptr(inputs[i]));
+ }
}
const auto& outputs = get_compiled_model()->outputs();
for (size_t i = 0; i < outputs.size(); i++) {
@@ -300,17 +327,44 @@ void SyncInferRequest::enqueue() {
size_t port_idx = it.first;
const auto& port = it.second;
- if (m_batched_tensors.count(port.get_tensor_ptr()) > 0) {
+ const bool is_batched = m_batched_tensors.count(port.get_tensor_ptr()) > 0;
+
+ // Materialize a reserved lazy input slot before inference.
+ if (!is_batched) {
+ bool needs_alloc = false;
+ {
+ auto inputs = m_user_inputs.read();
+ auto uit = inputs->find(port_idx);
+ needs_alloc = uit != inputs->end() && !uit->second.ptr;
+ }
+ if (needs_alloc) {
+ ensure_input_allocated(port_idx);
+ GPU_DEBUG_LOG << "[lazy alloc] input " << port_idx
+ << " shape: " << port.get_partial_shape()
+ << " allocated at enqueue" << std::endl;
+ }
+ }
+
+ if (is_batched) {
auto events = prepare_batched_input(port_idx, port, m_batched_tensors.at(port.get_tensor_ptr()));
std::move(events.begin(), events.end(), std::back_inserter(dependencies));
} else {
cldnn::primitive_id internal_name = m_graph->input_port_index_to_internal(port_idx)[0];
- auto events = prepare_input(internal_name, port_idx, port, m_user_inputs.at(port_idx));
+ TensorWrapper user_tensor;
+ {
+ auto inputs = m_user_inputs.read();
+ user_tensor = inputs->at(port_idx);
+ }
+ auto events = prepare_input(internal_name, port_idx, port, user_tensor);
std::move(events.begin(), events.end(), std::back_inserter(dependencies));
}
if (need_alias_detection) {
- const auto& wrapper = m_user_inputs.at(port_idx);
+ TensorWrapper wrapper;
+ {
+ auto inputs = m_user_inputs.read();
+ wrapper = inputs->at(port_idx);
+ }
if (wrapper.ptr && !std::dynamic_pointer_cast<IRemoteTensor>(wrapper.ptr)) {
if (auto* p = wrapper.ptr->data()) {
input_host_ptrs.insert(p);
@@ -685,18 +739,33 @@ cldnn::event::ptr SyncInferRequest::copy_output_data(cldnn::memory::ptr src, ov:
}
}
-void SyncInferRequest::allocate_input(const ov::Output<const ov::Node>& port, size_t input_idx) {
- const auto& shape = port.get_partial_shape();
- auto element_type = port.get_element_type();
+void SyncInferRequest::ensure_input_allocated(size_t input_idx) const {
+ // Serializes lazy allocation against concurrent get_tensor()/infer().
+ auto inputs = m_user_inputs.write();
+ auto it = inputs->find(input_idx);
+ if (it != inputs->end() && it->second.ptr) {
+ return; // already materialized
+ }
+ // const_cast: base set_tensor() is non-const.
+ const_cast<SyncInferRequest&>(*this).allocate_input(input_idx, *inputs);
+}
- m_user_inputs[input_idx] = { create_host_tensor(shape, element_type), TensorOwner::PLUGIN };
+void SyncInferRequest::allocate_input(size_t input_idx, GuardedMap::map_t& user_inputs) {
+ // Caller passes the already write-locked map. Shape/type come from m_input_ports_map (this
+ // compiled model's own port), not a caller port which may carry a different (un-reshaped) shape.
+ const auto& internal_port = m_input_ports_map.at(input_idx);
+ const auto& shape = internal_port.get_partial_shape();
+ auto element_type = internal_port.get_element_type();
+
+ user_inputs[input_idx] = { create_host_tensor(shape, element_type), TensorOwner::PLUGIN };
if (element_type == ov::element::string) {
// In case the element type is string and input data is an empty string,
// it produces the segmentation fault unless the each element of tensor.data is initialized.
- auto data = m_user_inputs.at(input_idx).ptr->data<std::string>();
- std::uninitialized_fill_n(data, m_user_inputs.at(input_idx).ptr->get_size(), std::string());
+ auto data = user_inputs.at(input_idx).ptr->data<std::string>();
+ std::uninitialized_fill_n(data, user_inputs.at(input_idx).ptr->get_size(), std::string());
}
- ov::ISyncInferRequest::set_tensor(port, m_user_inputs.at(input_idx).ptr);
+ // Base-qualified to avoid re-entering the input lock; use internal_port to match the allocated shape.
+ ov::ISyncInferRequest::set_tensor(internal_port, user_inputs.at(input_idx).ptr);
}
void SyncInferRequest::allocate_output(const ov::Output<const ov::Node>& port, size_t output_idx) {
@@ -726,6 +795,10 @@ void SyncInferRequest::allocate_output(const ov::Output<const ov::Node>& port, s
void SyncInferRequest::allocate_inputs() {
OV_ITT_SCOPED_TASK(itt::domains::intel_gpu_plugin, "SyncInferRequest::allocate_inputs");
+ auto inputs = m_user_inputs.write();
+ // Reserve up-front to avoid rehashing while the lazy path holds the lock.
+ inputs->reserve(m_input_ports_map.size());
+
for (const auto& it : m_input_ports_map) {
size_t input_idx = it.first;
const auto& port = it.second;
@@ -741,7 +814,17 @@ void SyncInferRequest::allocate_inputs() {
}
if (!is_nv12_input) {
- allocate_input(port, input_idx);
+ const auto& pshape = port.get_partial_shape();
+ const bool can_defer = pshape.is_static() && port.get_element_type() != ov::element::string;
+ if (can_defer) {
+ // Reserve a null slot; materialized lazily or replaced by set_tensor().
+ (*inputs)[input_idx] = { nullptr, TensorOwner::PLUGIN };
+ GPU_DEBUG_LOG << "[lazy alloc] reserved input slot " << input_idx
+ << " shape: " << pshape << std::endl;
+ } else {
+ // Dynamic/string inputs stay eager.
+ allocate_input(input_idx, *inputs);
+ }
}
}
}
diff --git a/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp b/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp
index 4d88ccc9079..c62d5fc375d 100644
--- a/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp
+++ b/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp
@@ -2,6 +2,10 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <atomic>
+#include <thread>
+#include <vector>
+
#include "common_test_utils/ov_tensor_utils.hpp"
#include "common_test_utils/test_common.hpp"
#include "common_test_utils/common_utils.hpp"
@@ -91,6 +95,197 @@ INSTANTIATE_TEST_SUITE_P(smoke_GPU_BehaviorTests, InferRequestIOPrecision,
::testing::Values(ov::test::utils::DEVICE_GPU)),
InferRequestIOPrecision::getTestCaseName);
+static std::shared_ptr<ov::Model> makeStaticInputModel(ov::Shape& shape_out) {
+ const ov::Shape shape{1, 64};
+ shape_out = shape;
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ param->set_friendly_name("static_input");
+ param->output(0).get_tensor().set_names({"static_input"});
+ auto relu = std::make_shared<ov::op::v0::Relu>(param);
+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(relu)};
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{param});
+}
+
+// Static input must be inferable when set_tensor() is never called.
+TEST(TensorTest, smoke_lazyAllocStaticInputInferWithoutSetTensor) {
+ ov::Shape shape;
+ auto model = makeStaticInputModel(shape);
+
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU);
+ auto request = compiled_model.create_infer_request();
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ ov::Tensor in;
+ OV_ASSERT_NO_THROW(in = request.get_input_tensor(0));
+ ASSERT_EQ(in.get_shape(), shape);
+ ASSERT_NE(in.data(), nullptr);
+ OV_ASSERT_NO_THROW(request.get_output_tensor(0));
+}
+
+// get_tensor() before infer() must also materialize the lazy slot.
+TEST(TensorTest, smoke_lazyAllocStaticInputGetTensorBeforeInfer) {
+ ov::Shape shape;
+ auto model = makeStaticInputModel(shape);
+
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU);
+ auto request = compiled_model.create_infer_request();
+
+ ov::Tensor in;
+ OV_ASSERT_NO_THROW(in = request.get_input_tensor(0));
+ ASSERT_EQ(in.get_shape(), shape);
+ ASSERT_NE(in.data(), nullptr);
+
+ OV_ASSERT_NO_THROW(request.infer());
+}
+
+// AUTO_BATCH's shared buffer must be sized batch=N, not the slot's own batch=1 port. Checked
+// by value: an offset bug doesn't change the exposed shape, only which bytes get read/written.
+TEST(TensorTest, smoke_lazyAllocAutoBatchUsesBatchedShapeNotSlotShape) {
+ constexpr int kBatch = 4;
+ ov::Shape shape;
+ auto model = makeStaticInputModel(shape);
+
+ auto core = ov::Core();
+ // Non-zero timeout so requests are actually batched together (same value used in
+ // auto_batch/tests/functional/behavior/ov_plugin/auto_batching_tests.cpp).
+ auto compiled_model = core.compile_model(model,
+ "BATCH:" + std::string(ov::test::utils::DEVICE_GPU) +
+ "(" + std::to_string(kBatch) + ")",
+ ov::auto_batch_timeout(1000));
+
+ std::vector<ov::InferRequest> requests;
+ for (int i = 0; i < kBatch; ++i) {
+ requests.push_back(compiled_model.create_infer_request());
+ }
+
+ // Distinct value per slot: an offset bug would mix these together.
+ for (int i = 0; i < kBatch; ++i) {
+ ov::Tensor in;
+ OV_ASSERT_NO_THROW(in = requests[i].get_input_tensor(0));
+ ASSERT_EQ(in.get_shape(), shape);
+ auto* in_data = in.data<float>();
+ ASSERT_NE(in_data, nullptr);
+ std::fill_n(in_data, in.get_size(), static_cast<float>(i + 1));
+ }
+
+ for (auto& req : requests) {
+ OV_ASSERT_NO_THROW(req.start_async());
+ }
+ for (auto& req : requests) {
+ OV_ASSERT_NO_THROW(req.wait());
+ }
+
+ // Relu(i+1) == i+1; a corrupted shared buffer would mix values across slots.
+ for (int i = 0; i < kBatch; ++i) {
+ ov::Tensor out;
+ OV_ASSERT_NO_THROW(out = requests[i].get_output_tensor(0));
+ ASSERT_EQ(out.get_shape(), shape);
+ const auto* data = out.data<float>();
+ ASSERT_NE(data, nullptr);
+ for (size_t j = 0; j < out.get_size(); ++j) {
+ ASSERT_FLOAT_EQ(data[j], static_cast<float>(i + 1)) << "slot " << i << " element " << j;
+ }
+ }
+}
+
+static std::shared_ptr<ov::Model> makeDynamicInputModel() {
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32,
+ ov::PartialShape{1, ov::Dimension::dynamic()});
+ param->set_friendly_name("dyn_input");
+ param->output(0).get_tensor().set_names({"dyn_input"});
+ auto relu = std::make_shared<ov::op::v0::Relu>(param);
+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(relu)};
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{param});
+}
+
+TEST(TensorTest, smoke_eagerAllocDynamicInputInfer) {
+ auto model = makeDynamicInputModel();
+
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU);
+ auto request = compiled_model.create_infer_request();
+
+ // Eagerly allocated: accessing the tensor before set/infer must not throw.
+ OV_ASSERT_NO_THROW(request.get_input_tensor(0));
+
+ const ov::Shape concrete{1, 8};
+ ov::Tensor input(ov::element::f32, concrete);
+ OV_ASSERT_NO_THROW(request.set_input_tensor(0, input));
+ OV_ASSERT_NO_THROW(request.infer());
+
+ ov::Tensor out;
+ OV_ASSERT_NO_THROW(out = request.get_output_tensor(0));
+ ASSERT_EQ(out.get_shape(), concrete);
+}
+
+// Many threads race on the first get_tensor() of a fresh request; ensure_input_allocated()'s
+// lock must collapse them into a single allocation so all threads observe the same buffer.
+TEST(TensorTest, smoke_lazyAllocStaticInputConcurrentFirstGetTensorRace) {
+ ov::Shape shape;
+ auto model = makeStaticInputModel(shape);
+
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU);
+
+ constexpr int kThreads = 8;
+ constexpr int kIterations = 100;
+
+ std::atomic<bool> failed{false};
+
+ for (int iter = 0; iter < kIterations && !failed.load(); ++iter) {
+ // Fresh request re-arms the race for each iteration.
+ auto request = compiled_model.create_infer_request();
+
+ std::atomic<int> ready{0};
+ std::atomic<bool> go{false};
+ std::vector<const void*> observed(kThreads, nullptr);
+
+ std::vector<std::thread> threads;
+ threads.reserve(kThreads);
+ for (int t = 0; t < kThreads; ++t) {
+ threads.emplace_back([&, t] {
+ ready.fetch_add(1, std::memory_order_acq_rel);
+ while (!go.load(std::memory_order_acquire)) {
+ std::this_thread::yield();
+ }
+ try {
+ auto in = request.get_input_tensor(0);
+ if (in.get_shape() != shape || in.data() == nullptr) {
+ failed.store(true);
+ }
+ observed[t] = in.data();
+ } catch (...) {
+ // Any exception on the concurrent first-touch materialization is a failure.
+ failed.store(true);
+ }
+ });
+ }
+
+ // Release all threads at once to maximize contention.
+ while (ready.load(std::memory_order_acquire) < kThreads) {
+ std::this_thread::yield();
+ }
+ go.store(true, std::memory_order_release);
+
+ for (auto& th : threads) {
+ th.join();
+ }
+
+ // All racers must observe the same buffer.
+ const void* first = observed[0];
+ for (int t = 1; t < kThreads; ++t) {
+ if (observed[t] != first) {
+ failed.store(true);
+ }
+ }
+ }
+
+ ASSERT_FALSE(failed.load());
+}
+
TEST(TensorTest, smoke_canSetShapeForPreallocatedTensor) {
auto core = ov::Core();
using namespace ov::preprocess;