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
[GPU] Defer allocations of static outputs in SyncInferRequest (#37518)
Bartlomiej Filipekbe40116a45ab
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.hppindex 4ad6087f03d..b2f7b8427be 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@@ -61,7 +61,7 @@ struct TensorWrapper {size_t actual_size;};-// Couples the lazily-allocated user-input map with its mutex so the map is reachable only+// Couples a lazily-allocated user tensor 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:@@ -127,10 +127,13 @@ private:// an exclusive lock on m_user_inputs.void ensure_input_allocated(size_t input_idx) const;+ // Materializes a deferred (lazy) static output slot on first access (get_tensor/enqueue).+ void ensure_output_allocated(size_t output_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;+ mutable GuardedMap m_user_outputs;std::unordered_map<size_t, TensorWrapper> m_plugin_inputs;std::unordered_map<size_t, TensorWrapper> m_plugin_outputs;@@ -173,7 +176,9 @@ private:void allocate_outputs();void allocate_states();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);+ void allocate_output(const ov::Output<const ov::Node>& port,+ size_t output_idx,+ GuardedMap::map_t& user_outputs);cldnn::event::ptr copy_output_data(cldnn::memory::ptr src, ov::ITensor& dst) const;void init_mappings();diff --git a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cppindex e7da5c37d87..9368b2750eb 100644--- a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp+++ b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp@@ -3,6 +3,7 @@//#include "openvino/runtime/make_tensor.hpp"+#include "openvino/core/memory_util.hpp"#include "openvino/core/preprocess/input_tensor_info.hpp"#include "openvino/core/parallel.hpp"#include "openvino/core/validation_util.hpp"@@ -222,7 +223,8 @@ void SyncInferRequest::set_tensor(const ov::Output<const ov::Node>& port, constauto 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);+ auto outputs = m_user_outputs.write();+ update_tensors_maps(port_index, *outputs, m_plugin_outputs, tensor);}ov::ISyncInferRequest::set_tensor(port, tensor);@@ -270,8 +272,15 @@ ov::SoPtr<ov::ITensor> SyncInferRequest::get_tensor(const ov::Output<const ov::N}return { tensor_ptr, nullptr };}- 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};+ {+ auto outputs = m_user_outputs.read();+ OPENVINO_ASSERT(outputs->count(port_index) == 1,+ "[GPU] Output tensor with index ", port_index, " is not found");+ }+ // Materialize the reserved slot on first access.+ ensure_output_allocated(port_index);+ auto outputs = m_user_outputs.read();+ return {outputs->at(port_index).ptr, nullptr};}void SyncInferRequest::check_tensors() const {@@ -291,6 +300,11 @@ void SyncInferRequest::check_tensors() const {}const auto& outputs = get_compiled_model()->outputs();for (size_t i = 0; i < outputs.size(); i++) {+ auto user_outputs = m_user_outputs.read();+ const auto it = user_outputs->find(i);+ if (it != user_outputs->end() && !it->second.ptr)+ continue;+check_tensor(outputs[i], get_tensor_ptr(outputs[i]));}}@@ -397,7 +411,14 @@ void SyncInferRequest::enqueue() {size_t port_idx = it.first;const auto& port = it.second;- auto events = prepare_output(port_idx, port, m_user_outputs.at(port_idx));+ // Materialize any deferred output slot the user did not provide via set_tensor().+ ensure_output_allocated(port_idx);+ TensorWrapper user_output;+ {+ auto outputs = m_user_outputs.read();+ user_output = outputs->at(port_idx);+ }+ auto events = prepare_output(port_idx, port, user_output);std::move(events.begin(), events.end(), std::back_inserter(dependencies));}@@ -491,8 +512,13 @@ void SyncInferRequest::wait() {GPU_DEBUG_TRACE_DETAIL << internal_name << " model output with index " << port_idx << ": " << output_memory->buffer_ptr() << std::endl;}- OPENVINO_ASSERT(m_user_outputs.count(port_idx) > 0, "[GPU] Output index ", port_idx, " is not found in output tensors map");- auto output_tensor_wrapper = m_user_outputs.at(port_idx);+ TensorWrapper output_tensor_wrapper;+ {+ auto outputs = m_user_outputs.read();+ OPENVINO_ASSERT(outputs->count(port_idx) > 0,+ "[GPU] Output index ", port_idx, " is not found in output tensors map");+ output_tensor_wrapper = outputs->at(port_idx);+ }auto output_tensor = output_tensor_wrapper.ptr;auto remote_tensor_impl_ptr = std::dynamic_pointer_cast<RemoteTensorImpl>(output_tensor);auto iremote_tensor_ptr = std::dynamic_pointer_cast<IRemoteTensor>(output_tensor);@@ -755,6 +781,21 @@ void SyncInferRequest::ensure_input_allocated(size_t input_idx) const {const_cast<SyncInferRequest&>(*this).allocate_input(input_idx, *inputs);}+void SyncInferRequest::ensure_output_allocated(size_t output_idx) const {+ auto outputs = m_user_outputs.write();+ auto it = outputs->find(output_idx);+ if (it != outputs->end() && it->second.ptr) {+ return; // already materialized or user-provided+ }+ // const_cast: base set_tensor() is non-const.+ auto& self = const_cast<SyncInferRequest&>(*this);+ const auto& port = m_output_ports_map.at(output_idx);+ (*outputs)[output_idx] = {self.create_host_tensor(port.get_partial_shape(), port.get_element_type()),+ TensorOwner::PLUGIN};+ self.ov::ISyncInferRequest::set_tensor(port, outputs->at(output_idx).ptr);+ GPU_DEBUG_LOG << "[lazy alloc] output " << output_idx << " materialized" << std::endl;+}+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.@@ -773,12 +814,23 @@ void SyncInferRequest::allocate_input(size_t input_idx, GuardedMap::map_t& user_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) {+void SyncInferRequest::allocate_output(const ov::Output<const ov::Node>& port,+ size_t output_idx,+ GuardedMap::map_t& user_outputs) {const auto& shape = port.get_partial_shape();auto element_type = port.get_element_type();- m_user_outputs[output_idx] = { create_host_tensor(shape, element_type), TensorOwner::PLUGIN };- ov::ISyncInferRequest::set_tensor(port, m_user_outputs.at(output_idx).ptr);+ // EXPERIMENTAL (CVS-192347): defer static output host tensor. Reserve a null slot;+ // materialized lazily via ensure_output_allocated() or replaced by user set_tensor() (IOBinding).+ const bool can_defer = shape.is_static() && element_type != ov::element::string;+ if (can_defer) {+ user_outputs[output_idx] = {nullptr, TensorOwner::PLUGIN};+ GPU_DEBUG_LOG << "[lazy alloc] reserved output slot " << output_idx << " shape: " << shape << std::endl;+ return;+ }++ user_outputs[output_idx] = {create_host_tensor(shape, element_type), TensorOwner::PLUGIN};+ ov::ISyncInferRequest::set_tensor(port, user_outputs.at(output_idx).ptr);// For dynamic outputs with USM host support, create an OutputMemoryBlock// that will be plugged into the graph to enable zero-copy output.@@ -838,14 +890,22 @@ void SyncInferRequest::allocate_outputs() {OV_ITT_SCOPED_TASK(itt::domains::intel_gpu_plugin, "SyncInferRequest::allocate_outputs");total_output_bytes = 0;+ auto outputs = m_user_outputs.write();+ outputs->reserve(m_output_ports_map.size());// allocate outputsfor (const auto& it : m_output_ports_map) {size_t output_idx = it.first;const auto& port = it.second;GPU_DEBUG_LOG << "[init output blob with index: " << output_idx << "]" << " shape: " << port.get_partial_shape() << " type: " << port.get_element_type() << std::endl;- allocate_output(port, output_idx);- total_output_bytes += ov::ISyncInferRequest::get_tensor(port)->get_byte_size();+ allocate_output(port, output_idx, *outputs);+ const auto& pshape = port.get_partial_shape();+ // Deferred static outputs have no tensor yet; size them from the static shape.+ if (pshape.is_static())+ total_output_bytes += ov::util::get_memory_size(port.get_element_type(),+ ov::shape_size(pshape.to_shape()));+ else+ total_output_bytes += ov::ISyncInferRequest::get_tensor(port)->get_byte_size();}}diff --git a/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp b/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cppindex c62d5fc375d..3f8fe06afb0 100644--- a/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp+++ b/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp@@ -141,6 +141,32 @@ TEST(TensorTest, smoke_lazyAllocStaticInputGetTensorBeforeInfer) {OV_ASSERT_NO_THROW(request.infer());}+TEST(TensorTest, smoke_lazyAllocStaticOutputReusesUserTensor) {+ 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 input(ov::element::f32, shape);+ ov::Tensor output(ov::element::f32, shape);+ request.set_input_tensor(input);+ request.set_output_tensor(output);++ for (float value : {1.0f, 2.0f}) {+ std::fill_n(input.data<float>(), input.get_size(), value);++ OV_ASSERT_NO_THROW(request.infer());++ auto actual = request.get_output_tensor();+ ASSERT_EQ(actual.data(), output.data());+ for (size_t i = 0; i < actual.get_size(); ++i) {+ ASSERT_FLOAT_EQ(actual.data<const float>()[i], value);+ }+ }+}+// 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) {@@ -286,6 +312,67 @@ TEST(TensorTest, smoke_lazyAllocStaticInputConcurrentFirstGetTensorRace) {ASSERT_FALSE(failed.load());}+// Many threads race on the first get_tensor() of a fresh request; lazy output+// materialization must collapse them into a single allocation.+TEST(TensorTest, smoke_lazyAllocStaticOutputConcurrentFirstGetTensorRace) {+ 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) {+ 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 out = request.get_output_tensor(0);+ if (out.get_shape() != shape || out.data() == nullptr) {+ failed.store(true);+ }+ observed[t] = out.data();+ } catch (...) {+ failed.store(true);+ }+ });+ }++ 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();+ }++ 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;