Skip to content

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

[GPU] Reuse infer request output tensor in the dynamic shape scenario (#34442)

Maksim Kutakov75f5aa847c6f
diff --git a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
index 3a91945601f..fe56224e17f 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
@@ -24,6 +24,10 @@
#include <list>
#include <set>
+namespace ov::intel_gpu {
+class OutputMemoryBlock;
+} // namespace ov::intel_gpu
+
namespace cldnn {
/// @brief Represents network output returned by @ref network::get_output().
@@ -187,6 +191,26 @@ public:
bool has_output_remote_memory_ptr(const primitive_id& id) const;
void reset_output_remote_memory_ptrs();
+ /// @brief Register an externally-owned output memory block for a network output primitive.
+ /// The block is owned by the infer request; the network holds a non-owning pointer.
+ void register_output_memory_block(const primitive_id& id, ov::intel_gpu::OutputMemoryBlock* block);
+
+ /// @brief Unregister a previously registered output memory block for a primitive.
+ /// Invalidates cached output memory so the graph falls back to its normal memory pool.
+ void unregister_output_memory_block(const primitive_id& id);
+
+ /// @brief Get the registered output memory block for a primitive, or nullptr if none.
+ ov::intel_gpu::OutputMemoryBlock* get_output_memory_block(const primitive_id& id) const;
+
+ /// @brief Clear all registered output memory blocks (called on infer request destruction
+ /// or when switching to a different graph).
+ void clear_output_memory_blocks();
+
+ /// @brief Walk backward from an output node through optimized predecessors
+ /// to find the compute node(s) whose output memory aliases the ext_block,
+ /// and clear their _outputs[0].
+ void invalidate_ext_block_compute_nodes(const primitive_id& output_id);
+
memory_pool& get_memory_pool() const {
return *_memory_pool;
}
@@ -229,6 +253,9 @@ private:
memory::ptr _shape_info_ptr;
std::unordered_map<primitive_id, memory::ptr> _output_remote_mem_ptrs;
+ // Non-owning pointers to OutputMemoryBlocks, keyed by Result node's primitive_id.
+ // Owned by SyncInferRequest::m_output_memory_blocks. One entry per OV model output.
+ std::unordered_map<primitive_id, ov::intel_gpu::OutputMemoryBlock*> _output_memory_blocks;
std::unordered_map<primitive_id, std::shared_ptr<primitive_inst>> _primitives;
std::vector<shared_mem_type> _in_out_shared_mem_types;
@@ -254,6 +281,7 @@ private:
void transfer_memory_to_device(std::shared_ptr<primitive_inst> instance, program_node const& node);
void add_to_exec_order(const primitive_id& id);
std::shared_ptr<primitive_inst> find_primitive(const primitive_id& id) const;
+ void invalidate_output_memory_chain(const primitive_id& id);
void add_default_output_chains();
void calculate_weights_cache_capacity();
output_chains_map::iterator add_output_chain(std::shared_ptr<primitive_inst>& p_inst);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/output_memory_block.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/output_memory_block.hpp
new file mode 100644
index 00000000000..cbc65c1704d
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/output_memory_block.hpp
@@ -0,0 +1,84 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <array>
+
+#include "intel_gpu/runtime/engine.hpp"
+#include "intel_gpu/runtime/layout.hpp"
+#include "intel_gpu/runtime/memory.hpp"
+
+namespace ov::intel_gpu {
+
+/// @brief Owns a USM host memory buffer for a dynamic output tensor.
+///
+/// This block is owned by the infer request and plugged into the network graph
+/// before each inference. The block encapsulates grow-only allocation with a reclaim policy for shape reduction.
+///
+/// Lifetime: owned by SyncInferRequest, outlives any single network::execute() call.
+/// The graph holds a non-owning pointer.
+class OutputMemoryBlock {
+public:
+ explicit OutputMemoryBlock(cldnn::engine& engine, size_t reclaim_threshold = 2) : m_engine(engine), m_reclaim_threshold(reclaim_threshold) {}
+
+ /// @brief Ensures the current buffer has enough capacity for the given layout.
+ ///
+ /// - If the current buffer is large enough (in bytes), it is reused via reinterpret_buffer.
+ /// - If the buffer is too large (bytes > needed_bytes * reclaim_threshold),
+ /// it is released and reallocated.
+ /// - If the buffer is too small or absent, a new USM host buffer is allocated.
+ ///
+ /// After this call, memory() returns a cldnn::memory whose layout matches
+ /// alloc_layout, so memory()->count() gives the capacity in elements.
+ ///
+ /// @param alloc_layout Layout to allocate (may include shape predictor padding).
+ void resize(const cldnn::layout& alloc_layout) {
+ auto needed_bytes = alloc_layout.bytes_count();
+
+ auto& buf = m_buffers[m_buff_idx];
+ auto alloc_bytes = buf ? buf->get_mem_tracker()->size() : size_t{0};
+
+ // RECLAIM: if current allocation is much larger than needed, release and reallocate
+ if (buf && m_reclaim_threshold > 0 && needed_bytes * m_reclaim_threshold < alloc_bytes) {
+ GPU_DEBUG_TRACE_DETAIL << "OutputMemoryBlock: reclaim oversized buffer " << alloc_bytes << "B -> " << needed_bytes << "B" << std::endl;
+ buf = nullptr;
+ alloc_bytes = 0;
+ }
+
+ // REUSE: current buffer has enough bytes — reinterpret to the requested layout
+ // so that memory()->count() reflects the correct element count and data type.
+ if (buf && needed_bytes <= alloc_bytes) {
+ buf = m_engine.reinterpret_buffer(*buf, alloc_layout);
+ return;
+ }
+
+ // ALLOCATE: need a (larger) buffer
+ buf = m_engine.allocate_memory(alloc_layout, cldnn::allocation_type::usm_host);
+ }
+
+ /// @return Current memory pointer (may be null if not yet allocated or after reclaim).
+ cldnn::memory::ptr memory() const {
+ return m_buffers[m_buff_idx];
+ }
+
+ /// @return Raw data pointer of the current buffer, for alias detection.
+ void* rawPtr() const {
+ auto& mem = m_buffers[m_buff_idx];
+ return mem ? mem->buffer_ptr() : nullptr;
+ }
+
+ /// @brief Switch to the alternate buffer.
+ void nextMemory() {
+ m_buff_idx ^= 1;
+ }
+
+private:
+ cldnn::engine& m_engine;
+ std::array<cldnn::memory::ptr, 2> m_buffers;
+ int m_buff_idx = 0;
+ size_t m_reclaim_threshold; ///< Reclaim if capacity > needed * threshold.
+};
+
+} // namespace ov::intel_gpu
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 4f9b6c06ec0..0bc545de44e 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
@@ -5,6 +5,7 @@
#pragma once
#include "intel_gpu/plugin/variable_state.hpp"
+#include "intel_gpu/plugin/output_memory_block.hpp"
#include "openvino/runtime/isync_infer_request.hpp"
#include "intel_gpu/plugin/graph.hpp"
#include "intel_gpu/plugin/remote_tensor.hpp"
@@ -44,7 +45,7 @@ public:
explicit SyncInferRequest(const std::shared_ptr<const CompiledModel>& compiled_model);
SyncInferRequest(const SyncInferRequest &) = delete;
- ~SyncInferRequest() override = default;
+ ~SyncInferRequest() override;
void infer() override;
std::vector<ov::ProfilingInfo> get_profiling_info() const override;
@@ -118,8 +119,14 @@ private:
void init_mappings();
bool is_batched_input(const ov::Output<const ov::Node>& port) const;
uint64_t total_output_bytes = 0;
+
+ // Per-output-port OutputMemoryBlock for zero-copy dynamic output.
+ // Keyed by output port index. Only populated when USM host memory is available.
+ std::unordered_map<size_t, std::unique_ptr<OutputMemoryBlock>> m_output_memory_blocks;
+
// Variable to hold the inference request string with compiled model name
// to prevent this string being constructed for each inference call
- std::string m_itt_infer_request_str;};
+ std::string m_itt_infer_request_str;
+};
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
index e29f5960ab6..a7da1033230 100644
--- a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
@@ -366,6 +366,7 @@ public:
std::shared_ptr<const PType> get_typed_desc() const { return _impl_params->typed_desc<PType>(); }
virtual void update_output_memory() {}
+ void clear_output_memory();
virtual int32_t get_prealloc_iter_num() { return -1; }
virtual void update_shape_info_tensor(const kernel_impl_params& params);
@@ -507,8 +508,6 @@ protected:
virtual bool need_reset_output_memory() const;
- void clear_output_memory();
-
// This could be implemented via single map std::unordered_map<instrumentation::perf_counter_key, std::tuple<int64_t, size_t>>
// but the overhead on using perf_counter_key as map key is too big, thus we use hash as map key
// and store mapping onto original perf_clounter_key for further data analysis and dumps
diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cpp
index d2379089cdd..352edf0733f 100644
--- a/src/plugins/intel_gpu/src/graph/network.cpp
+++ b/src/plugins/intel_gpu/src/graph/network.cpp
@@ -3,6 +3,7 @@
//
#include "intel_gpu/plugin/variable_state.hpp"
+#include "intel_gpu/plugin/output_memory_block.hpp"
#include "intel_gpu/primitives/read_value.hpp"
#include "intel_gpu/primitives/lora.hpp"
#include "intel_gpu/primitives/data.hpp"
@@ -671,6 +672,79 @@ void network::reset_output_remote_memory_ptrs() {
}
}
+void network::invalidate_output_memory_chain(const primitive_id& id) {
+ auto p_inst = find_primitive(id);
+ p_inst->clear_output_memory();
+
+ auto o_iter = _output_chains.find(id);
+ if (o_iter != _output_chains.end()) {
+ for (auto* prim : o_iter->second) {
+ if (prim != p_inst.get()) {
+ prim->clear_output_memory();
+ }
+ }
+ }
+}
+
+void network::invalidate_ext_block_compute_nodes(const primitive_id& output_id) {
+ // Walk backward from the output node through optimized single-dependency
+ // predecessors until we reach the compute node (the first non-optimized one).
+ // Clear its _outputs[0] so that prepare_primitive's null-check triggers
+ // realloc_if_needed, which will re-probe forward and pick up the new ext_block
+ // buffer after a double-buffer flip.
+ //
+ // Stop at runtime-skippable nodes: they may have had can_be_optimized flipped
+ // to false by do_runtime_skip_*() and should not participate in the ext_block chain.
+ auto cursor = find_primitive(output_id);
+ while (cursor->can_be_optimized() && !cursor->dependencies().empty()) {
+ cursor->clear_output_memory();
+ GPU_DEBUG_TRACE_DETAIL << "[double-buffer] cleared output memory on optimized node " << cursor->id() << std::endl;
+ auto dep_id = cursor->dependencies().front().first->id();
+ auto dep = find_primitive(dep_id);
+ // Stop before runtime-skippable nodes: their can_be_optimized() may
+ // have been re-evaluated at runtime — they are the compute boundary.
+ if (dep->get_node().is_runtime_skippable())
+ break;
+ cursor = dep;
+ }
+ // cursor is now the compute node — clear its output so it re-acquires from ext_block
+ if (!cursor->has_inner_networks() && !cursor->can_be_optimized()) {
+ cursor->clear_output_memory();
+ GPU_DEBUG_TRACE_DETAIL << "[double-buffer] cleared output memory on compute node " << cursor->id() << std::endl;
+ }
+}
+
+void network::register_output_memory_block(const primitive_id& id, ov::intel_gpu::OutputMemoryBlock* block) {
+ OPENVINO_ASSERT(block != nullptr, "[GPU] Use unregister path (nullptr) via clear_output_memory_blocks or erase");
+
+ auto [it, inserted] = _output_memory_blocks.emplace(id, block);
+ if (!inserted) {
+ if (it->second == block)
+ return; // Same block already registered — nothing to do
+ it->second = block;
+ }
+}
+
+void network::unregister_output_memory_block(const primitive_id& id) {
+ auto it = _output_memory_blocks.find(id);
+ if (it != _output_memory_blocks.end()) {
+ _output_memory_blocks.erase(it);
+ invalidate_ext_block_compute_nodes(id);
+ }
+}
+
+ov::intel_gpu::OutputMemoryBlock* network::get_output_memory_block(const primitive_id& id) const {
+ auto it = _output_memory_blocks.find(id);
+ return (it != _output_memory_blocks.end()) ? it->second : nullptr;
+}
+
+void network::clear_output_memory_blocks() {
+ for (auto& [prim_id, block_ptr] : _output_memory_blocks) {
+ invalidate_ext_block_compute_nodes(prim_id);
+ }
+ _output_memory_blocks.clear();
+}
+
void network::add_to_exec_order(const primitive_id& id) {
auto inst = get_primitive(id);
_exec_order.push_back(inst);
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index 5ec52c342a1..9f68ae9603b 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -751,6 +751,39 @@ void primitive_inst::realloc_outputs(bool prev_execution_skipped) {
if (get_node().is_type<input_layout>())
return;
+ // Forward probe: walk through single-user optimized chains to find an output
+ // node with an external output memory block (ext_block). If found, use the
+ // ext_block memory directly so this node's kernel writes into it, achieving
+ // zero-copy. This handles arbitrary-depth chains like:
+ // ComputeNode -> Reshape(opt) -> Reorder(opt) -> Result(opt, ext_block)
+ {
+ auto* cursor = this;
+ while (cursor->get_user_insts().size() == 1 && cursor->get_user_insts().front()->can_be_optimized()) {
+ auto* next = cursor->get_user_insts().front();
+ if (next->is_output()) {
+ auto* ext_block = get_network().get_output_memory_block(next->id());
+ if (ext_block) {
+ ext_block->resize(actual_layouts[0]);
+ _outputs[0] = ext_block->memory();
+ _max_output_layout_count[0] = _outputs[0]->get_mem_tracker()->size()
+ / cldnn::data_type_traits::size_of(actual_layouts[0].data_type);
+ GPU_DEBUG_TRACE_DETAIL << id() << ": use ext output memory block via forward probe -> "
+ << next->id() << " - "
+ << actual_layouts[0].get_linear_size() << "/" << _max_output_layout_count[0]
+ << std::endl;
+ GPU_DEBUG_PROFILED_STAGE_MEMALLOC_INFO("ext_output_block_via_forward_probe");
+ return;
+ }
+ break; // output node without ext_block — stop probing
+ }
+ // Stop at runtime-skippable nodes: their can_be_optimized() is
+ // tentative and may flip to false once their prepare_primitive runs.
+ if (next->get_node().is_runtime_skippable())
+ break;
+ cursor = next;
+ }
+ }
+
auto& sp = *get_network().get_shape_predictor();
std::vector<size_t> dt_sizes_in_B;
for (size_t i = 0; i < actual_layouts.size(); ++i) {
@@ -1058,6 +1091,24 @@ void primitive_inst::realloc_outputs(bool prev_execution_skipped) {
updated_params.output_layouts[i] = updated_layouts[i];
}
+ // Check for external output memory block (zero-copy dynamic output path).
+ // When registered by the infer request, the block owns USM host memory that the
+ // GPU kernel writes into directly, avoiding an extra GPU->Host copy after execution.
+ if (is_output()) {
+ auto* ext_block = get_network().get_output_memory_block(id());
+ if (ext_block) {
+ ext_block->resize(updated_params.output_layouts[i]);
+ _outputs[i] = get_network().get_engine().reinterpret_buffer(*ext_block->memory(), actual_layouts[i]);
+ _max_output_layout_count[i] = ext_block->memory()->get_mem_tracker()->size()
+ / cldnn::data_type_traits::size_of(actual_layouts[i].data_type);
+ GPU_DEBUG_TRACE_DETAIL << id() << ": ext output memory block for output[" << i << "] - "
+ << actual_layouts[i].get_linear_size() << "/" << _max_output_layout_count[i]
+ << std::endl;
+ GPU_DEBUG_PROFILED_STAGE_MEMALLOC_INFO("ext_output_block");
+ continue;
+ }
+ }
+
if (can_reuse_buffer) {
GPU_DEBUG_TRACE_DETAIL << id() << ": reuse previously allocated output buffer[" << i << "] - "
<< actual_layouts[i].get_linear_size() << "/" << _max_output_layout_count[i]
@@ -2099,6 +2150,13 @@ void primitive_inst::prepare_primitive() {
_update_shape_done_by_other = false; // reset
OPENVINO_ASSERT(_impl != nullptr, "[GPU] Implementation is nullptr for ", primitive_id, " primitive");
+ // Re-acquire output memory when _outputs[0] was cleared by
+ // invalidate_ext_block_compute_nodes (double-buffer flip).
+ if (is_dynamic() && !has_inner_networks() && !_outputs.empty() && !_outputs[0]) {
+ realloc_if_needed(prev_execution_skipped);
+ set_flag(ExecutionFlags::MEMORY_CHANGED);
+ }
+
std::function<bool(const cldnn::primitive_inst*)> has_dynamic_dependencies_insts =
[&has_dynamic_dependencies_insts](const cldnn::primitive_inst* prim_inst) {
for (auto& dep : prim_inst->_deps) {
diff --git a/src/plugins/intel_gpu/src/plugin/program_builder.cpp b/src/plugins/intel_gpu/src/plugin/program_builder.cpp
index 6646cee1ca3..1c843435c09 100644
--- a/src/plugins/intel_gpu/src/plugin/program_builder.cpp
+++ b/src/plugins/intel_gpu/src/plugin/program_builder.cpp
@@ -107,6 +107,8 @@ ProgramBuilder::ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine&
CustomLayer::LoadFromFile(custom_layers_config, m_custom_layers, custom_layers_config.empty());
auto ops = model->get_ordered_ops();
+
+ GPU_DEBUG_LOG << "Build model name: " << m_model->get_name() << " friendly name: " << m_model->get_friendly_name() << std::endl;
m_program = build(ops, is_inner_program);
}
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 0529b10289c..800356cbaea 100644
--- a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
+++ b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
@@ -28,6 +28,7 @@
#include <memory>
#include <string>
#include <map>
+#include <unordered_set>
#include <functional>
#include <utility>
@@ -101,6 +102,18 @@ SyncInferRequest::SyncInferRequest(const std::shared_ptr<const CompiledModel>& c
allocate_states();
}
+SyncInferRequest::~SyncInferRequest() {
+ // Clear the network's non-owning pointers to our OutputMemoryBlocks
+ // before they are destroyed, to prevent dangling pointers.
+ if (!m_output_memory_blocks.empty()) {
+ std::lock_guard<std::mutex> lk(m_graph->get_mutex());
+ auto network = m_graph->get_network();
+ if (network) {
+ network->clear_output_memory_blocks();
+ }
+ }
+}
+
void SyncInferRequest::infer() {
// String can be constructed once in the constructor
OV_ITT_SCOPED_TASK_BASE(itt::domains::intel_gpu_inference, m_itt_infer_request_str.c_str());
@@ -241,6 +254,14 @@ void SyncInferRequest::enqueue() {
// into the network object primitives
std::vector<cldnn::event::ptr> dependencies;
+ // Collect host-side input pointers during the input preparation loop so
+ // we can later detect when a user feeds the previous output back as input
+ // (double-buffer alias detection). Only non-remote tensors have valid host
+ // pointers; remote tensors live in device memory and can never alias a
+ // USM-host output block.
+ std::unordered_set<const void*> input_host_ptrs;
+ const bool need_alias_detection = !m_output_memory_blocks.empty();
+
for (const auto& it : m_input_ports_map) {
size_t port_idx = it.first;
const auto& port = it.second;
@@ -253,6 +274,30 @@ void SyncInferRequest::enqueue() {
auto events = prepare_input(internal_name, port_idx, port, m_user_inputs.at(port_idx));
std::move(events.begin(), events.end(), std::back_inserter(dependencies));
}
+
+ if (need_alias_detection) {
+ const auto& wrapper = m_user_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);
+ }
+ }
+ }
+ }
+
+ // Double buffering: detect when an input tensor aliases an output memory
+ // block — i.e. the user fed the previous output back as input. Switch the
+ // aliased block to its alternate buffer so the kernel writes to a different
+ // location than the one being read as input.
+ if (!m_output_memory_blocks.empty() && !input_host_ptrs.empty()) {
+ auto network = m_graph->get_network();
+ for (auto& [idx, block] : m_output_memory_blocks) {
+ if (block->rawPtr() && input_host_ptrs.count(block->rawPtr())) {
+ block->nextMemory();
+ network->invalidate_ext_block_compute_nodes(m_output_names_map.at(idx));
+ GPU_DEBUG_TRACE_DETAIL << "Output block [" << idx << "]: input aliases output - switching to alternate buffer" << std::endl;
+ }
+ }
}
for (const auto& it : m_output_ports_map) {
@@ -400,12 +445,25 @@ void SyncInferRequest::wait() {
if (is_dynamic) {
bool need_reallocate = true;
auto usm_host_tensor = std::dynamic_pointer_cast<USMHostTensor>(output_tensor);
- if (usm_host_tensor && output_memory)
+
+ // Zero-copy path: if we have an OutputMemoryBlock for this output,
+ // the block already owns the memory that the GPU wrote into.
+ // Update the USMHostTensor's backing memory to point to the block's buffer.
+ auto block_it = m_output_memory_blocks.find(port_idx);
+ if (block_it != m_output_memory_blocks.end() && block_it->second->memory() && usm_host_tensor
+ && output_tensor_wrapper.owner == TensorOwner::PLUGIN) {
+ auto block_mem = block_it->second->memory();
+ auto* impl = usm_host_tensor->get_impl().get();
+ // Update the backing memory to match the block's current buffer and actual data size
+ impl->set_memory(block_mem, output_memory->count());
+ need_reallocate = false;
+ } else if (usm_host_tensor && output_memory) {
need_reallocate = usm_host_tensor->get_impl()->get_original_memory()->size() < output_memory->size();
- else if (!is_remote_tensor_impl && output_memory)
+ } else if (!is_remote_tensor_impl && output_memory) {
need_reallocate = output_tensor_wrapper.actual_size < output_memory->size();
- else if (is_remote_tensor_impl && output_memory)
+ } else if (is_remote_tensor_impl && output_memory) {
need_reallocate = false;
+ }
if (need_reallocate) {
std::string internal_name = m_output_names_map.at(port_idx);
@@ -493,7 +551,18 @@ void SyncInferRequest::setup_stream_graph() {
auto num_graphs = stream_graphs.size();
stream_id = stream_id % num_graphs;
}
- m_graph = stream_graphs[stream_id];
+
+ auto new_graph = stream_graphs[stream_id];
+ // When switching to a different graph, clear the old graph's non-owning pointers
+ // to our OutputMemoryBlocks to prevent dangling pointers and stale associations.
+ if (new_graph != m_graph && !m_output_memory_blocks.empty()) {
+ std::lock_guard<std::mutex> lk(m_graph->get_mutex());
+ auto network = m_graph->get_network();
+ if (network) {
+ network->clear_output_memory_blocks();
+ }
+ }
+ m_graph = new_graph;
}
std::shared_ptr<ov::ITensor> SyncInferRequest::create_host_tensor(const ov::PartialShape& port_shape, const ov::element::Type& port_element_type) const {
@@ -602,6 +671,15 @@ void SyncInferRequest::allocate_output(const ov::Output<const ov::Node>& port, s
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);
+
+ // For dynamic outputs with USM host support, create an OutputMemoryBlock
+ // that will be plugged into the graph to enable zero-copy output.
+ if (shape.is_dynamic() && can_use_usm_host(m_graph->get_engine(), total_output_bytes)) {
+ auto device_et = convert_to_supported_device_type(element_type);
+ if (!is_convert_required(device_et, element_type)) {
+ m_output_memory_blocks[output_idx] = std::make_unique<OutputMemoryBlock>(m_graph->get_engine());
+ }
+ }
}
void SyncInferRequest::allocate_inputs() {
@@ -816,9 +894,9 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
auto usm_host_raw_ptr = engine.get_device_info().dev_type == cldnn::device_type::integrated_gpu &&
user_tensor_mem_type == cldnn::allocation_type::usm_host;
- bool update_device_tensor = (m_plugin_inputs.count(input_idx) == 0) ||
- (m_plugin_inputs[input_idx].owner == TensorOwner::USER && !is_remote_tensor_impl) ||
- (plugin_tensor_mem_type != cldnn::allocation_type::usm_host && usm_host_raw_ptr);
+ bool update_device_tensor = ((m_plugin_inputs.count(input_idx) == 0) ||
+ (m_plugin_inputs[input_idx].owner == TensorOwner::USER && !is_remote_tensor_impl) ||
+ (plugin_tensor_mem_type != cldnn::allocation_type::usm_host && usm_host_raw_ptr));
if (update_device_tensor) {
// If device input hasn't been created, then try to use user memory if it's usm_host, or allocate new device buffer
m_plugin_inputs[input_idx] =
@@ -956,8 +1034,21 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
}
// Missing output in _plugin_outputs means that the network is dynamic and outputs couldn't be pre-allocated
- if (m_plugin_outputs.find(output_idx) == m_plugin_outputs.end())
+ if (m_plugin_outputs.find(output_idx) == m_plugin_outputs.end()) {
+ // For dynamic PLUGIN-owned outputs with an OutputMemoryBlock, register the block
+ // into the network so that realloc_outputs() can use it for zero-copy output.
+ if (is_dynamic && user_tensor_wrapper.owner == TensorOwner::PLUGIN) {
+ auto block_it = m_output_memory_blocks.find(output_idx);
+ if (block_it != m_output_memory_blocks.end()) {
+ network->register_output_memory_block(internal_name, block_it->second.get());
+ }
+ } else if (is_dynamic) {
+ // User set a custom tensor — unregister any previously registered block
+ // so the graph uses its normal memory pool and copies to user's tensor.
+ network->unregister_output_memory_block(internal_name);
+ }
return {};
+ }
auto output_tensor = std::dynamic_pointer_cast<RemoteTensorImpl>(m_plugin_outputs.at(output_idx).ptr);
auto output_memory = output_tensor->get_memory();
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.cpp b/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.cpp
index 27a95de2c91..dd614e3523d 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.cpp
@@ -38,7 +38,7 @@ bool PrintModelStatistics::run_on_model(const std::shared_ptr<ov::Model>& m) {
size_t total = collect_stats(m, ops_stat);
std::stringstream ss;
- ss << "Operations statistics:\n";
+ ss << "Operations statistics for model with friendly_name: " << m->get_friendly_name() << " with name: " << m->get_name() << "\n";
for (auto& kv : ops_stat) {
ss << "\t" << kv.first.version_id << "::" << kv.first.name << " " << kv.second << std::endl;
}
diff --git a/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_aliasing_test.cpp b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_aliasing_test.cpp
new file mode 100644
index 00000000000..c4cf5f38048
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_aliasing_test.cpp
@@ -0,0 +1,124 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Regression test for zero-copy output aliasing.
+//
+// When a user calls infer_request.get_output_tensor() and then feeds
+// that same tensor back via infer_request.set_input_tensor() the GPU
+// kernel would read from and write to the same buffer (because the
+// output tensor is backed by the OutputMemoryBlock). For non-element-
+// wise operations (e.g. MatMul) this corrupts data.
+//
+// The model is:
+// Parameter{-1, K} → MatMul(const weights{K, K}) → Result
+//
+// Two iterations are executed:
+// iter 0: input = A → expected output = A * W
+// iter 1: input = (A * W) → expected output = (A * W) * W
+// The iter-1 result is compared to a reference computed on the TEMPLATE
+// plugin. If aliasing corrupts data, the comparison will fail.
+
+#include "common_test_utils/node_builders/constant.hpp"
+#include "common_test_utils/ov_plugin_cache.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/test_common.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/runtime/core.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace {
+using ov::test::InputShape;
+
+class OVDynamicOutputAliasingTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr size_t K = 1024; // feature size — large enough to force
+ // tiled GPU execution so that reads and
+ // writes to the same buffer interleave.
+ // Weights must be square (K×K) because
+ // the output tensor is fed back as input,
+ // requiring matching feature dimensions.
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ // Dynamic input shape: batch is dynamic, feature dim is fixed.
+ // Small batch sizes keep runtime low while K=1024 forces tiling.
+ const auto input_shapes = std::vector<InputShape>{{{-1, static_cast<int64_t>(K)}, {{2, K}, {4, K}}}};
+ init_input_shapes(input_shapes);
+
+ // Build model: Parameter{-1, K} × Const{K, K} → Result
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), static_cast<int64_t>(K)});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ // Random weight matrix — small values to avoid overflow.
+ auto weights = ov::test::utils::make_constant(ov::element::f32, ov::Shape{K, K}, ov::test::utils::InputGenerateData(0, 1, 1000, 1));
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(param, weights, false, false);
+ matmul->set_friendly_name("matmul");
+
+ auto result = std::make_shared<ov::op::v0::Result>(matmul);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ // Custom run():
+ // 1. Compile the model on GPU.
+ // 2. For each target static shape do two inferences:
+ // iter 0 – normal input → output.
+ // iter 1 – set the output tensor of iter 0 as the input,
+ // infer, then compare with a TEMPLATE-plugin reference
+ // using the standard calculate_refs() + compare() pipeline.
+ void run() override {
+ compile_model();
+
+ for (const auto& targetStaticShapeVec : targetStaticShapes) {
+ // --- Iteration 0: normal inference -----------------------
+ generate_inputs(targetStaticShapeVec);
+
+ // Use get_plugin_outputs() which is known to work:
+ // it calls infer() internally, then get_tensor() for each output.
+ auto iter0_outputs = get_plugin_outputs();
+ auto& output_tensor_0 = iter0_outputs.front();
+
+ // Deep-copy iter-0 output for the reference computation.
+ // The original tensor will be fed back as input (aliasing).
+ ov::Tensor iter0_copy(output_tensor_0.get_element_type(), output_tensor_0.get_shape());
+ std::memcpy(iter0_copy.data(), output_tensor_0.data(), output_tensor_0.get_byte_size());
+
+ // --- Iteration 1: feed output back as input (aliasing) ---
+ // Use the *same* tensor object that the plugin returned.
+ const auto& input_param = function->get_parameters().front();
+ inferRequest.set_tensor(input_param, output_tensor_0);
+ inferRequest.infer();
+
+ // Collect actual GPU outputs.
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ // Populate the inputs map with the copied iter-0 output so
+ // that calculate_refs() computes the expected result via the
+ // TEMPLATE plugin.
+ inputs.clear();
+ inputs[input_param] = iter0_copy;
+
+ auto expectedOutputs = calculate_refs();
+
+ // Use the standard threshold-aware comparison.
+ compare(expectedOutputs, actualOutputs);
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputAliasingTest, smoke_OutputNotAliasedWithInput) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_deep_chain_test.cpp b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_deep_chain_test.cpp
new file mode 100644
index 00000000000..87650da2290
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_deep_chain_test.cpp
@@ -0,0 +1,505 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Functional tests for zero-copy dynamic output with deep optimized chains.
+//
+// These tests validate that the forward probe in realloc_outputs() correctly
+// walks through arbitrary-depth optimized chains (Reshape, Squeeze, Unsqueeze)
+// to reach an output node with an ext_block, and that the backward walk
+// (invalidate_ext_block_compute_nodes) correctly invalidates the entire chain
+// on double-buffer flip.
+//
+// Test plan reference: dynamic_output_test_plan.md
+
+#include "common_test_utils/node_builders/constant.hpp"
+#include "common_test_utils/ov_plugin_cache.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/test_common.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/runtime/core.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace {
+using ov::test::InputShape;
+
+// ============================================================================
+// Test 1: DeepReshapeChain
+// Parameter{-1,4} → Softmax(axis=1) → Reshape(opt) → Result(opt, ext_block)
+// Validates forward probe depth=1 through a single Reshape.
+//
+// Softmax is used instead of MatMul because it has inherent cross-element
+// dependency: the kernel must read ALL elements along the axis to compute
+// max and sum before writing any output. With input-output aliasing,
+// writing any output element corrupts an input element that other threads
+// still need, unlike MatMul which buffers tiles in scratchpad memory.
+// ============================================================================
+class OVDynamicOutputDeepReshapeChainTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{2, K}, {3, K}, {2, K}}}};
+ init_input_shapes(input_shapes);
+
+ // Build model: Param{-1,4} → Softmax(axis=1) → Reshape(-1,4) → Result
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ auto softmax = std::make_shared<ov::op::v8::Softmax>(param, 1);
+ softmax->set_friendly_name("softmax");
+
+ // Reshape: from {B, 4} to {B, 4} — same logical shape but the Reshape
+ // node should be optimized away since it's a no-op reshape.
+ // Use target shape = {0, K} where 0 means "copy from input".
+ auto target_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(softmax, target_shape, true);
+ reshape->set_friendly_name("reshape");
+
+ auto result = std::make_shared<ov::op::v0::Result>(reshape);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ void run() override {
+ compile_model();
+
+ for (const auto& targetStaticShapeVec : targetStaticShapes) {
+ generate_inputs(targetStaticShapeVec);
+
+ auto iter0_outputs = get_plugin_outputs();
+ auto& output_tensor_0 = iter0_outputs.front();
+
+ // Deep-copy for reference computation.
+ ov::Tensor iter0_copy(output_tensor_0.get_element_type(), output_tensor_0.get_shape());
+ std::memcpy(iter0_copy.data(), output_tensor_0.data(), output_tensor_0.get_byte_size());
+
+ // Feed output back as input (triggers aliasing detection).
+ const auto& input_param = function->get_parameters().front();
+ inferRequest.set_tensor(input_param, output_tensor_0);
+ inferRequest.infer();
+
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ inputs.clear();
+ inputs[input_param] = iter0_copy;
+ auto expectedOutputs = calculate_refs();
+ compare(expectedOutputs, actualOutputs);
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputDeepReshapeChainTest, smoke_DeepReshapeChain) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 2: DeepMultiReshapeChain
+// Parameter{-1,4} → Softmax(axis=1) → Reshape(opt) → Reshape(opt) → Result
+// Validates forward probe depth=2 through two consecutive Reshapes.
+// ============================================================================
+class OVDynamicOutputDeepMultiReshapeChainTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{2, K}, {3, K}, {2, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ auto softmax = std::make_shared<ov::op::v8::Softmax>(param, 1);
+ softmax->set_friendly_name("softmax");
+
+ // Two consecutive reshapes, both should be optimized as no-ops.
+ // Reshape 1: {B, 4} → {B, 4}
+ auto target_shape_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_1 = std::make_shared<ov::op::v1::Reshape>(softmax, target_shape_1, true);
+ reshape_1->set_friendly_name("reshape_1");
+
+ // Reshape 2: {B, 4} → {B, 4}
+ auto target_shape_2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_2 = std::make_shared<ov::op::v1::Reshape>(reshape_1, target_shape_2, true);
+ reshape_2->set_friendly_name("reshape_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(reshape_2);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ void run() override {
+ compile_model();
+
+ for (const auto& targetStaticShapeVec : targetStaticShapes) {
+ generate_inputs(targetStaticShapeVec);
+
+ auto iter0_outputs = get_plugin_outputs();
+ auto& output_tensor_0 = iter0_outputs.front();
+
+ ov::Tensor iter0_copy(output_tensor_0.get_element_type(), output_tensor_0.get_shape());
+ std::memcpy(iter0_copy.data(), output_tensor_0.data(), output_tensor_0.get_byte_size());
+
+ const auto& input_param = function->get_parameters().front();
+ inferRequest.set_tensor(input_param, output_tensor_0);
+ inferRequest.infer();
+
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ inputs.clear();
+ inputs[input_param] = iter0_copy;
+ auto expectedOutputs = calculate_refs();
+ compare(expectedOutputs, actualOutputs);
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputDeepMultiReshapeChainTest, smoke_DeepMultiReshapeChain) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 3: DeepHeterogeneousChain
+// Parameter{-1,1,4} → Softmax(axis=-1) → Squeeze(axis=1, opt)
+// → Unsqueeze(axis=1, opt) → Result
+// Validates forward probe through mixed optimized node types.
+// Squeeze removes dim 1, Unsqueeze adds it back — the pair is a no-op.
+// ============================================================================
+class OVDynamicOutputDeepHeterogeneousChainTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ // Input shape: {-1, 1, K}
+ const auto input_shapes = std::vector<InputShape>{{{-1, 1, K}, {{2, 1, K}, {3, 1, K}, {2, 1, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), 1, K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ // Softmax along last axis: {-1, 1, K} → {-1, 1, K}
+ auto softmax = std::make_shared<ov::op::v8::Softmax>(param, -1);
+ softmax->set_friendly_name("softmax");
+
+ // Squeeze axis=1: {-1, 1, K} → {-1, K}
+ auto squeeze_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto squeeze = std::make_shared<ov::op::v0::Squeeze>(softmax, squeeze_axes);
+ squeeze->set_friendly_name("squeeze");
+
+ // Unsqueeze axis=1: {-1, K} → {-1, 1, K}
+ auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(squeeze, unsqueeze_axes);
+ unsqueeze->set_friendly_name("unsqueeze");
+
+ auto result = std::make_shared<ov::op::v0::Result>(unsqueeze);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ void run() override {
+ compile_model();
+
+ for (const auto& targetStaticShapeVec : targetStaticShapes) {
+ generate_inputs(targetStaticShapeVec);
+
+ auto iter0_outputs = get_plugin_outputs();
+ auto& output_tensor_0 = iter0_outputs.front();
+
+ ov::Tensor iter0_copy(output_tensor_0.get_element_type(), output_tensor_0.get_shape());
+ std::memcpy(iter0_copy.data(), output_tensor_0.data(), output_tensor_0.get_byte_size());
+
+ const auto& input_param = function->get_parameters().front();
+ inferRequest.set_tensor(input_param, output_tensor_0);
+ inferRequest.infer();
+
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ inputs.clear();
+ inputs[input_param] = iter0_copy;
+ auto expectedOutputs = calculate_refs();
+ compare(expectedOutputs, actualOutputs);
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputDeepHeterogeneousChainTest, smoke_DeepHeterogeneousChain) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 4: DeepChainBufferFlip
+// Same topology as Test 2 (Softmax → Reshape → Reshape → Result),
+// but specifically tests that the double-buffer toggle works correctly
+// at depth > 1. The input-output aliasing triggers the buffer flip,
+// and the backward walk must reach the compute node through 2 optimized
+// intermediaries to invalidate its memory.
+//
+// We run multiple iterations with shape changes to stress the flip
+// mechanism across varying buffer sizes.
+// ============================================================================
+class OVDynamicOutputDeepChainBufferFlipTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ // 5 shapes: enough to exercise multiple flips with shape changes.
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{2, K}, {3, K}, {4, K}, {2, K}, {3, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ auto softmax = std::make_shared<ov::op::v8::Softmax>(param, 1);
+ softmax->set_friendly_name("softmax");
+
+ auto target_shape_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_1 = std::make_shared<ov::op::v1::Reshape>(softmax, target_shape_1, true);
+ reshape_1->set_friendly_name("reshape_1");
+
+ auto target_shape_2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_2 = std::make_shared<ov::op::v1::Reshape>(reshape_1, target_shape_2, true);
+ reshape_2->set_friendly_name("reshape_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(reshape_2);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ // This run() intentionally chains ALL iterations with aliasing:
+ // each iteration's output becomes the next iteration's input.
+ // This maximizes the number of buffer flips.
+ void run() override {
+ compile_model();
+
+ // First iteration: use generated input.
+ auto& firstShapeVec = targetStaticShapes.front();
+ generate_inputs(firstShapeVec);
+ const auto& input_param = function->get_parameters().front();
+
+ // Get initial output
+ auto prev_outputs = get_plugin_outputs();
+ auto prev_output = prev_outputs.front();
+
+ // Now chain through ALL remaining shapes, each time feeding
+ // the previous output as input.
+ for (size_t i = 1; i < targetStaticShapes.size(); ++i) {
+ // Deep-copy previous output for reference computation.
+ ov::Tensor prev_copy(prev_output.get_element_type(), prev_output.get_shape());
+ std::memcpy(prev_copy.data(), prev_output.data(), prev_output.get_byte_size());
+
+ // Since shape may change and we're feeding output back as input,
+ // but the feature dimension is the same (K), only batch changes.
+ // Softmax preserves shape — so if we feed a {2,4} output as
+ // input, we get {2,4} output for the next iter.
+ inferRequest.set_tensor(input_param, prev_output);
+ inferRequest.infer();
+
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ // Reference for this iteration
+ inputs.clear();
+ inputs[input_param] = prev_copy;
+ auto expectedOutputs = calculate_refs();
+ compare(expectedOutputs, actualOutputs);
+
+ // Prepare for next iteration
+ prev_output = actualOutputs.front();
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputDeepChainBufferFlipTest, smoke_DeepChainBufferFlip) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 5: ConcatOutput
+// Parameter{-1,2} → [Multiply(const 2.0), Add(const 1.0)] → Concat(axis=1)
+// → Result
+// Validates that when a Concat feeds directly into Result, the ext_block
+// path works correctly (concat's predecessors write into sub-regions).
+// ============================================================================
+class OVDynamicOutputConcatTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 2;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{2, K}, {3, K}, {2, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ // Branch 1: multiply by 2.0
+ auto mul_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {2.0f});
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(param, mul_const);
+ multiply->set_friendly_name("multiply");
+
+ // Branch 2: add 1.0
+ auto add_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {1.0f});
+ auto add = std::make_shared<ov::op::v1::Add>(param, add_const);
+ add->set_friendly_name("add");
+
+ // Concat on axis 1: {-1, 2} + {-1, 2} → {-1, 4}
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{multiply, add}, 1);
+ concat->set_friendly_name("concat");
+
+ auto result = std::make_shared<ov::op::v0::Result>(concat);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+};
+
+TEST_F(OVDynamicOutputConcatTest, smoke_ConcatOutput) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 6: MultiOutputSharedCompute
+// Parameter{-1,4} → MatMul(const 4×4)
+// → [Reshape1(opt) → Result1, Reshape2(opt) → Result2]
+// Validates that when compute node has 2 users, the forward probe can't
+// match (multi-user) and falls back to normal allocation. Both outputs
+// must still be correct.
+// ============================================================================
+class OVDynamicOutputMultiOutputTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{2, K}, {3, K}, {2, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ auto weights = ov::test::utils::make_constant(ov::element::f32,
+ ov::Shape{static_cast<size_t>(K), static_cast<size_t>(K)},
+ ov::test::utils::InputGenerateData(0, 1, 1000, 42));
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(param, weights, false, false);
+ matmul->set_friendly_name("matmul");
+
+ // Two reshape branches from the same MatMul
+ auto target_shape_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_1 = std::make_shared<ov::op::v1::Reshape>(matmul, target_shape_1, true);
+ reshape_1->set_friendly_name("reshape_1");
+
+ auto target_shape_2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_2 = std::make_shared<ov::op::v1::Reshape>(matmul, target_shape_2, true);
+ reshape_2->set_friendly_name("reshape_2");
+
+ auto result_1 = std::make_shared<ov::op::v0::Result>(reshape_1);
+ result_1->set_friendly_name("result_1");
+
+ auto result_2 = std::make_shared<ov::op::v0::Result>(reshape_2);
+ result_2->set_friendly_name("result_2");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result_1, result_2}, ov::ParameterVector{param});
+ }
+};
+
+TEST_F(OVDynamicOutputMultiOutputTest, smoke_MultiOutputSharedCompute) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+// ============================================================================
+// Test 7: VaryingChainDepthStress
+// Parameter{-1,4} → MatMul(const 4×4) → Reshape(opt) → Reshape(opt) → Result
+// Runs many iterations with varying batch sizes to stress the probe mechanism.
+// Each shape change forces re-probing, which exercises the probe at varying
+// effective depths (if the runtime decides to not optimize a reshape).
+// ============================================================================
+class OVDynamicOutputVaryingDepthTest : public ov::test::SubgraphBaseTest {
+protected:
+ static constexpr int64_t K = 4;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ // 6 shapes for stress testing
+ const auto input_shapes = std::vector<InputShape>{{{-1, K}, {{1, K}, {2, K}, {3, K}, {4, K}, {2, K}, {1, K}}}};
+ init_input_shapes(input_shapes);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), K});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ auto weights = ov::test::utils::make_constant(ov::element::f32,
+ ov::Shape{static_cast<size_t>(K), static_cast<size_t>(K)},
+ ov::test::utils::InputGenerateData(0, 1, 1000, 42));
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(param, weights, false, false);
+ matmul->set_friendly_name("matmul");
+
+ auto target_shape_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_1 = std::make_shared<ov::op::v1::Reshape>(matmul, target_shape_1, true);
+ reshape_1->set_friendly_name("reshape_1");
+
+ auto target_shape_2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, K});
+ auto reshape_2 = std::make_shared<ov::op::v1::Reshape>(reshape_1, target_shape_2, true);
+ reshape_2->set_friendly_name("reshape_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(reshape_2);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+};
+
+TEST_F(OVDynamicOutputVaryingDepthTest, smoke_VaryingChainDepth) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_multiop_chain_test.cpp b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_multiop_chain_test.cpp
new file mode 100644
index 00000000000..7fbbf92f74d
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/dynamic_tests/gpu_dyn_output_multiop_chain_test.cpp
@@ -0,0 +1,142 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Functional test for zero-copy dynamic output with a multi-op chain.
+//
+// Verifies that when the output tensor is fed back as input and the model
+// contains multiple data-movement operations between the input and output,
+// the deps_alias_mem guard does NOT trigger (because the output primitive's
+// dependencies are intermediate buffers, not the original input) and
+// zero-copy works end-to-end without data corruption.
+//
+// The model is:
+// Parameter{-1, K} // dynamic batch, static feature
+// → Transpose{1, 0} // {K, B} — real data movement
+// → Split(axis=0, 2 equal parts) // {K/2, B} × 2
+// → Concat(axis=0, reversed halves) // {K, B} — swap top/bottom halves
+// → Transpose{1, 0} // {B, K} — back to original layout
+// → Result
+//
+// The double-transpose + reversed-split/concat is NOT an identity: it swaps
+// the first K/2 and last K/2 columns of the input matrix. This ensures
+// we actually verify the computation, not just a pass-through.
+//
+// Two iterations per shape:
+// iter 0: input = A → output = f(A)
+// iter 1: input = f(A) → output = f(f(A))
+// Compared to TEMPLATE-plugin reference via calculate_refs() + compare().
+
+#include "common_test_utils/node_builders/constant.hpp"
+#include "common_test_utils/ov_plugin_cache.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/test_common.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/runtime/core.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace {
+using ov::test::InputShape;
+
+class OVDynamicOutputMultiOpChainTest : public ov::test::SubgraphBaseTest {
+protected:
+ // K must be even so Split(axis=0, 2) produces equal halves.
+ // 256 is large enough for meaningful data movement, small enough for fast tests.
+ static constexpr size_t K = 256;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ // Dynamic batch, static feature dimension.
+ const auto input_shapes = std::vector<InputShape>{{{-1, static_cast<int64_t>(K)}, {{2, K}, {4, K}}}};
+ init_input_shapes(input_shapes);
+
+ // ---- Build model ----
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{ov::Dimension::dynamic(), static_cast<int64_t>(K)});
+ param->set_friendly_name("input");
+ param->get_output_tensor(0).set_names({"input_tensor"});
+
+ // Transpose {-1, K} → {K, -1} (order = [1, 0])
+ auto transpose_order_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 0});
+ auto transpose_1 = std::make_shared<ov::op::v1::Transpose>(param, transpose_order_1);
+ transpose_1->set_friendly_name("transpose_1");
+
+ // Split along axis 0 (the K dimension) into 2 equal halves.
+ auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto split = std::make_shared<ov::op::v1::Split>(transpose_1, split_axis, 2);
+ split->set_friendly_name("split");
+
+ // Concat in reversed order — swaps the two halves.
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{split->output(1), split->output(0)}, 0);
+ concat->set_friendly_name("concat");
+
+ // Transpose {K, -1} → {-1, K} (order = [1, 0])
+ auto transpose_order_2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 0});
+ auto transpose_2 = std::make_shared<ov::op::v1::Transpose>(concat, transpose_order_2);
+ transpose_2->set_friendly_name("transpose_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(transpose_2);
+ result->set_friendly_name("result");
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ // Custom run():
+ // 1. Compile the model on GPU.
+ // 2. For each target static shape, do two inferences:
+ // iter 0 – normal input → output.
+ // iter 1 – feed iter-0 output back as input, infer,
+ // compare with TEMPLATE-plugin reference.
+ //
+ // If zero-copy works correctly for the multi-op chain, iter 1
+ // should produce correct results without any special handling —
+ // the deps_alias_mem guard should NOT trigger because the output
+ // node's dependencies are intermediate buffers, not the input.
+ void run() override {
+ compile_model();
+
+ for (const auto& targetStaticShapeVec : targetStaticShapes) {
+ // --- Iteration 0: normal inference -----------------------
+ generate_inputs(targetStaticShapeVec);
+
+ auto iter0_outputs = get_plugin_outputs();
+ auto& output_tensor_0 = iter0_outputs.front();
+
+ // Deep-copy iter-0 output for the reference computation.
+ ov::Tensor iter0_copy(output_tensor_0.get_element_type(), output_tensor_0.get_shape());
+ std::memcpy(iter0_copy.data(), output_tensor_0.data(), output_tensor_0.get_byte_size());
+
+ // --- Iteration 1: feed output back as input (aliasing) ---
+ const auto& input_param = function->get_parameters().front();
+ inferRequest.set_tensor(input_param, output_tensor_0);
+ inferRequest.infer();
+
+ // Collect actual GPU outputs.
+ std::vector<ov::Tensor> actualOutputs;
+ for (const auto& output : function->outputs()) {
+ actualOutputs.push_back(inferRequest.get_tensor(output));
+ }
+
+ // Set the copied iter-0 output as the TEMPLATE-plugin input
+ // so calculate_refs() computes the expected result.
+ inputs.clear();
+ inputs[input_param] = iter0_copy;
+
+ auto expectedOutputs = calculate_refs();
+
+ compare(expectedOutputs, actualOutputs);
+ }
+ }
+};
+
+TEST_F(OVDynamicOutputMultiOpChainTest, smoke_MultiOpChainZeroCopy) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ run();
+}
+
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/dynamic_execution/zero_copy_output_test.cpp b/src/plugins/intel_gpu/tests/unit/dynamic_execution/zero_copy_output_test.cpp
new file mode 100644
index 00000000000..4b20d2790b8
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/dynamic_execution/zero_copy_output_test.cpp
@@ -0,0 +1,439 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/gemm.hpp>
+#include <intel_gpu/primitives/input_layout.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+
+#include "intel_gpu/plugin/output_memory_block.hpp"
+#include "openvino/reference/matmul.hpp"
+#include "primitive_inst.h"
+#include "test_utils.h"
+
+using namespace cldnn;
+using namespace ::tests;
+
+// ===================================================================
+// Base fixture: shared constants, weight data, helpers.
+// No network is built here — derived classes define the topology.
+//
+// Subgraph common to all tests:
+// Parameter{dynamic M, K} ---> Gemm ---> ...
+// ^
+// Constant{K, N} ---+
+// All tensors are fp16.
+// ===================================================================
+class ZeroCopyOutputTestBase : public ::testing::Test {
+protected:
+ static constexpr size_t K = 8;
+ static constexpr size_t N = 4;
+
+ cldnn::engine& engine = get_test_engine();
+
+ std::vector<ov::float16> weight_data;
+
+ void SetUp() override {
+ if (!engine.get_device_info().supports_usm) {
+ GTEST_SKIP() << "USM not supported on this device, skipping zero-copy output test";
+ }
+
+ weight_data.resize(K * N);
+ for (size_t i = 0; i < K * N; ++i)
+ weight_data[i] = ov::float16(0.1f * static_cast<float>(i % 7) - 0.3f);
+ }
+
+ // ---- helpers --------------------------------------------------------
+
+ /// Allocate weight memory and fill it with weight_data.
+ cldnn::memory::ptr make_weight_mem() {
+ layout weight_layout{ov::PartialShape{static_cast<int64_t>(K), static_cast<int64_t>(N)}, data_types::f16, format::bfyx};
+ auto mem = engine.allocate_memory(weight_layout);
+ set_values(mem, weight_data);
+ return mem;
+ }
+
+ /// Generate deterministic fp16 input data of shape [M, K].
+ std::vector<ov::float16> make_input(size_t M) const {
+ std::vector<ov::float16> data(M * K);
+ for (size_t i = 0; i < M * K; ++i)
+ data[i] = ov::float16(0.2f * static_cast<float>((i + M) % 11) - 1.0f);
+ return data;
+ }
+
+ /// Compute fp16 reference C[M,N] = A[M,K] * B[K,N] via ov::reference::matmul.
+ std::vector<ov::float16> compute_reference(const std::vector<ov::float16>& input, size_t M) const {
+ std::vector<ov::float16> out(M * N, ov::float16(0.f));
+ ov::reference::matmul(input.data(), weight_data.data(), out.data(), ov::Shape{M, K}, ov::Shape{K, N}, ov::Shape{M, N}, false, false);
+ return out;
+ }
+
+ /// Assert that the primitive's output memory is a zero-copy view over the
+ /// OutputMemoryBlock (same USM host pointer, usm_host allocation type).
+ static void verify_zero_copy(const cldnn::memory::ptr& output_mem, const ov::intel_gpu::OutputMemoryBlock& block) {
+ auto block_mem = block.memory();
+ ASSERT_NE(block_mem, nullptr) << "OutputMemoryBlock should have allocated memory";
+ ASSERT_EQ(block_mem->buffer_ptr(), output_mem->buffer_ptr()) << "Zero-copy failed: primitive output and OutputMemoryBlock pointers differ";
+ ASSERT_EQ(output_mem->get_allocation_type(), allocation_type::usm_host) << "Output memory should be USM host for zero-copy";
+ }
+};
+
+// ===================================================================
+// Direct-output fixture: gemm IS the network output.
+// input_layout("input") ---> gemm("gemm") [output]
+// ===================================================================
+class ZeroCopyOutputTest : public ZeroCopyOutputTestBase {
+protected:
+ cldnn::memory::ptr weight_mem;
+ cldnn::network::ptr net;
+
+ void SetUp() override {
+ ZeroCopyOutputTestBase::SetUp();
+ if (testing::Test::IsSkipped())
+ return;
+
+ weight_mem = make_weight_mem();
+
+ auto input_layout_dyn = layout{ov::PartialShape{ov::Dimension::dynamic(), static_cast<int64_t>(K)}, data_types::f16, format::bfyx};
+
+ topology topo;
+ topo.add(input_layout("input", input_layout_dyn));
+ topo.add(data("weights", weight_mem));
+ topo.add(gemm("gemm", {input_info("input"), input_info("weights")}, data_types::f16, false, false, 1.0f, 0.0f, 2, 2));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+ }
+
+ /// Execute the network with a concrete [M, K] input and return the output map.
+ std::map<primitive_id, network_output> run_gemm(size_t M, const std::vector<ov::float16>& input_data) {
+ auto input_mem = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(M), static_cast<int64_t>(K)}, data_types::f16, format::bfyx});
+ set_values(input_mem, input_data);
+ net->set_input_data("input", input_mem);
+ return net->execute();
+ }
+};
+
+// -------------------------------------------------------------------
+// Correctness: pointer match + numerical comparison for several shapes
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyOutputTest, pointer_match_and_correctness) {
+ ov::intel_gpu::OutputMemoryBlock output_block(engine);
+ net->register_output_memory_block("gemm", &output_block);
+
+ for (size_t M : {1, 5, 10, 3, 7}) {
+ SCOPED_TRACE("M = " + std::to_string(M));
+
+ auto input_data = make_input(M);
+ auto outputs = run_gemm(M, input_data);
+
+ auto output_mem = outputs.at("gemm").get_memory();
+ ASSERT_NE(output_mem, nullptr);
+
+ verify_zero_copy(output_mem, output_block);
+
+ // Numerical correctness
+ auto ref = compute_reference(input_data, M);
+
+ auto out_layout = output_mem->get_layout();
+ ASSERT_GE(out_layout.count(), M * N) << "Output layout should have at least M*N elements";
+
+ cldnn::mem_lock<ov::float16> out_lock(output_mem, get_test_stream());
+ for (size_t i = 0; i < M * N; ++i) {
+ ASSERT_NEAR(static_cast<float>(out_lock[i]), static_cast<float>(ref[i]), 0.05f) << "Mismatch at index " << i << " (M=" << M << ")";
+ }
+ }
+
+ net->clear_output_memory_blocks();
+}
+
+// -------------------------------------------------------------------
+// Buffer reuse: grow-only semantics (reclaim disabled).
+// Pointer must stay identical when the output shrinks and only change
+// when the required size exceeds the current capacity.
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyOutputTest, buffer_reuse_across_shapes) {
+ // threshold=0 disables reclaim -> pure grow-only behaviour
+ ov::intel_gpu::OutputMemoryBlock output_block(engine, 0);
+ net->register_output_memory_block("gemm", &output_block);
+
+ auto run_and_verify = [&](size_t M) {
+ auto input_data = make_input(M);
+ auto outputs = run_gemm(M, input_data);
+
+ auto output_mem = outputs.at("gemm").get_memory();
+ ASSERT_NE(output_mem, nullptr);
+ verify_zero_copy(output_mem, output_block);
+ };
+
+ // M=10: first allocation (40 elements minimum)
+ run_and_verify(10);
+ void* first_ptr = output_block.memory()->buffer_ptr();
+ size_t first_alloc_bytes = output_block.memory()->get_mem_tracker()->size();
+ ASSERT_GE(first_alloc_bytes, size_t(40) * sizeof(ov::float16));
+
+ // M=3: smaller shape -> buffer reused, pointer unchanged
+ run_and_verify(3);
+ ASSERT_EQ(output_block.memory()->buffer_ptr(), first_ptr) << "Buffer should be reused when shape shrinks (reclaim disabled)";
+ ASSERT_EQ(output_block.memory()->get_mem_tracker()->size(), first_alloc_bytes);
+
+ // M=7: still within first capacity -> pointer unchanged
+ run_and_verify(7);
+ ASSERT_EQ(output_block.memory()->buffer_ptr(), first_ptr) << "Buffer should be reused for shapes within existing capacity";
+ ASSERT_EQ(output_block.memory()->get_mem_tracker()->size(), first_alloc_bytes);
+
+ // M=20: 80 elements exceeds first capacity -> must grow
+ run_and_verify(20);
+ size_t grown_alloc_bytes = output_block.memory()->get_mem_tracker()->size();
+ ASSERT_GE(grown_alloc_bytes, size_t(80) * sizeof(ov::float16)) << "Block should have grown to accommodate 80 elements";
+
+ // M=15: back to smaller shape -> pointer unchanged after growth
+ void* grown_ptr = output_block.memory()->buffer_ptr();
+ run_and_verify(15);
+ ASSERT_EQ(output_block.memory()->buffer_ptr(), grown_ptr) << "Buffer should be reused after growth when shape shrinks";
+ ASSERT_EQ(output_block.memory()->get_mem_tracker()->size(), grown_alloc_bytes);
+
+ net->clear_output_memory_blocks();
+}
+
+// -------------------------------------------------------------------
+// Reclaim: oversized buffer is released when ratio exceeds threshold.
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyOutputTest, reclaim_oversized_buffer) {
+ // Default reclaim threshold (2x)
+ ov::intel_gpu::OutputMemoryBlock output_block(engine);
+ net->register_output_memory_block("gemm", &output_block);
+
+ auto run_and_verify = [&](size_t M) {
+ auto input_data = make_input(M);
+ auto outputs = run_gemm(M, input_data);
+
+ auto output_mem = outputs.at("gemm").get_memory();
+ ASSERT_NE(output_mem, nullptr);
+ verify_zero_copy(output_mem, output_block);
+ };
+
+ // M=25: large allocation (100+ elements with predictor padding)
+ run_and_verify(25);
+ void* large_ptr = output_block.memory()->buffer_ptr();
+ size_t large_bytes = output_block.memory()->get_mem_tracker()->size();
+
+ // M=1: 4 elements * 2B = 8 bytes vs 200+ bytes -> reclaim triggers
+ run_and_verify(1);
+ void* small_ptr = output_block.memory()->buffer_ptr();
+ size_t small_bytes = output_block.memory()->get_mem_tracker()->size();
+
+ ASSERT_NE(large_ptr, small_ptr) << "Buffer should be reclaimed when oversized by >2x";
+ ASSERT_LT(small_bytes, large_bytes) << "Reclaimed buffer should be smaller than the original";
+
+ net->clear_output_memory_blocks();
+}
+
+// ===================================================================
+// Optimized-out output fixture: gemm feeds a redundant reorder that
+// becomes the network output and is optimized out at graph-build time.
+// input_layout("input") ---> gemm("gemm") ---> reorder("output")
+// [optimized out]
+// ===================================================================
+class ZeroCopyOptimizedOutputTest : public ZeroCopyOutputTestBase {
+protected:
+ cldnn::memory::ptr weight_mem;
+ cldnn::network::ptr net;
+
+ void SetUp() override {
+ ZeroCopyOutputTestBase::SetUp();
+ if (testing::Test::IsSkipped())
+ return;
+
+ weight_mem = make_weight_mem();
+
+ auto input_layout_dyn = layout{ov::PartialShape{ov::Dimension::dynamic(), static_cast<int64_t>(K)}, data_types::f16, format::bfyx};
+
+ topology topo;
+ topo.add(input_layout("input", input_layout_dyn));
+ topo.add(data("weights", weight_mem));
+ topo.add(gemm("gemm", {input_info("input"), input_info("weights")}, data_types::f16, false, false, 1.0f, 0.0f, 2, 2));
+ // Redundant reorder: same format and data type → will be optimized out
+ topo.add(reorder("output", input_info("gemm"), format::bfyx, data_types::f16));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+ }
+
+ /// Execute the network with a concrete [M, K] input and return the output map.
+ std::map<primitive_id, network_output> run_gemm(size_t M, const std::vector<ov::float16>& input_data) {
+ auto input_mem = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(M), static_cast<int64_t>(K)}, data_types::f16, format::bfyx});
+ set_values(input_mem, input_data);
+ net->set_input_data("input", input_mem);
+ return net->execute();
+ }
+};
+
+// -------------------------------------------------------------------
+// Optimized-out output node: the ext_block is registered on the
+// reorder (output) id. The compute node must look ahead through the
+// optimized-out user and write directly into the ext_block.
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyOptimizedOutputTest, optimized_out_output_node) {
+ // Verify the reorder is indeed optimized out
+ auto reorder_inst = net->get_primitive("output");
+ ASSERT_TRUE(reorder_inst->can_be_optimized()) << "Reorder should be optimized out (same format/type as input)";
+
+ // Register the ext_block on the output (reorder) primitive id
+ ov::intel_gpu::OutputMemoryBlock output_block(engine);
+ net->register_output_memory_block("output", &output_block);
+
+ for (size_t M : {1, 5, 10, 3, 7}) {
+ SCOPED_TRACE("M = " + std::to_string(M));
+
+ auto input_data = make_input(M);
+ auto outputs = run_gemm(M, input_data);
+
+ auto output_mem = outputs.at("output").get_memory();
+ ASSERT_NE(output_mem, nullptr);
+
+ // The gemm (compute) node should have written directly into the
+ // ext_block's buffer, even though it is registered on the reorder.
+ auto block_mem = output_block.memory();
+ ASSERT_NE(block_mem, nullptr) << "OutputMemoryBlock should have allocated memory";
+
+ // Verify the compute node's output IS the ext_block buffer
+ auto gemm_output = net->get_primitive("gemm")->output_memory_ptr();
+ ASSERT_EQ(gemm_output->buffer_ptr(), block_mem->buffer_ptr()) << "Compute node (gemm) should write directly into the ext_block "
+ "when its sole user is an optimized-out output node";
+
+ // Also verify the network output points to the same buffer
+ ASSERT_EQ(output_mem->buffer_ptr(), block_mem->buffer_ptr()) << "Network output should be the ext_block buffer";
+
+ ASSERT_EQ(output_mem->get_allocation_type(), allocation_type::usm_host) << "Output memory should be USM host for zero-copy";
+
+ // Numerical correctness
+ auto ref = compute_reference(input_data, M);
+ cldnn::mem_lock<ov::float16> out_lock(output_mem, get_test_stream());
+ for (size_t i = 0; i < M * N; ++i) {
+ ASSERT_NEAR(static_cast<float>(out_lock[i]), static_cast<float>(ref[i]), 0.05f) << "Mismatch at index " << i << " (M=" << M << ")";
+ }
+ }
+
+ net->clear_output_memory_blocks();
+}
+
+// ===================================================================
+// Multi-user output fixture: gemm feeds TWO consumers — a redundant
+// reorder (optimized out, network output) and a type-converting
+// reorder (NOT optimized, also a network output). Because gemm has
+// more than one user, the look-ahead adoption (users.size()==1 guard)
+// is skipped. The optimized reorder hits the can_be_optimized()
+// early return and never touches the ext_block.
+//
+// The test verifies graceful fallback: no crash, the ext_block is
+// never populated, and outputs are still numerically correct.
+//
+// input_layout("input") ---> gemm("gemm") ---> reorder("output", bfyx, f16) [optimized out]
+// \-> reorder("other_output", bfyx, f32) [executed]
+// ===================================================================
+class ZeroCopyMultiUserOutputTest : public ZeroCopyOutputTestBase {
+protected:
+ cldnn::memory::ptr weight_mem;
+ cldnn::network::ptr net;
+
+ void SetUp() override {
+ ZeroCopyOutputTestBase::SetUp();
+ if (testing::Test::IsSkipped())
+ return;
+
+ weight_mem = make_weight_mem();
+
+ auto input_layout_dyn = layout{ov::PartialShape{ov::Dimension::dynamic(), static_cast<int64_t>(K)}, data_types::f16, format::bfyx};
+
+ topology topo;
+ topo.add(input_layout("input", input_layout_dyn));
+ topo.add(data("weights", weight_mem));
+ topo.add(gemm("gemm", {input_info("input"), input_info("weights")}, data_types::f16, false, false, 1.0f, 0.0f, 2, 2));
+ // Same format/type → will be optimized out
+ topo.add(reorder("output", input_info("gemm"), format::bfyx, data_types::f16));
+ // Different data type → will NOT be optimized out, creates a second user of gemm
+ topo.add(reorder("other_output", input_info("gemm"), format::bfyx, data_types::f32));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+ }
+
+ /// Execute the network with a concrete [M, K] input and return the output map.
+ std::map<primitive_id, network_output> run_gemm(size_t M, const std::vector<ov::float16>& input_data) {
+ auto input_mem = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(M), static_cast<int64_t>(K)}, data_types::f16, format::bfyx});
+ set_values(input_mem, input_data);
+ net->set_input_data("input", input_mem);
+ return net->execute();
+ }
+};
+
+// -------------------------------------------------------------------
+// Multi-user fallback: when the compute node has multiple users the
+// look-ahead adoption is skipped. The ext_block registered on the
+// optimized-out output is never populated. The system must fall back
+// to the normal memory pool path without crashing, and the outputs
+// must remain numerically correct.
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyMultiUserOutputTest, fallback_when_multiple_users) {
+ // Verify preconditions: the reorder is optimized out and gemm has >1 user
+ auto reorder_inst = net->get_primitive("output");
+ ASSERT_TRUE(reorder_inst->can_be_optimized()) << "Reorder should be optimized out (same format/type as input)";
+
+ auto gemm_inst = net->get_primitive("gemm");
+ ASSERT_GT(gemm_inst->get_user_insts().size(), 1u) << "gemm should have more than one user in this topology";
+
+ // Register the ext_block on the optimized-out output
+ ov::intel_gpu::OutputMemoryBlock output_block(engine);
+ net->register_output_memory_block("output", &output_block);
+
+ for (size_t M : {1, 5, 10, 3, 7}) {
+ SCOPED_TRACE("M = " + std::to_string(M));
+
+ auto input_data = make_input(M);
+ auto outputs = run_gemm(M, input_data);
+
+ // The ext_block should NOT have been populated because the look-ahead
+ // adoption was blocked by users.size() != 1, and the optimized reorder
+ // hit the can_be_optimized() early return without reaching ext_block code.
+ ASSERT_EQ(output_block.memory(), nullptr) << "OutputMemoryBlock should NOT be allocated when the compute node "
+ "has multiple users (zero-copy look-ahead is disabled)";
+
+ // Both outputs should still be available and correct
+ auto output_mem = outputs.at("output").get_memory();
+ ASSERT_NE(output_mem, nullptr);
+
+ auto other_output_mem = outputs.at("other_output").get_memory();
+ ASSERT_NE(other_output_mem, nullptr);
+
+ // Verify f16 output ("output") correctness
+ auto ref = compute_reference(input_data, M);
+ {
+ cldnn::mem_lock<ov::float16> lock(output_mem, get_test_stream());
+ for (size_t i = 0; i < M * N; ++i) {
+ ASSERT_NEAR(static_cast<float>(lock[i]), static_cast<float>(ref[i]), 0.05f) << "f16 output mismatch at index " << i << " (M=" << M << ")";
+ }
+ }
+
+ // Verify f32 output ("other_output") correctness
+ {
+ cldnn::mem_lock<float> lock(other_output_mem, get_test_stream());
+ for (size_t i = 0; i < M * N; ++i) {
+ ASSERT_NEAR(lock[i], static_cast<float>(ref[i]), 0.05f) << "f32 output mismatch at index " << i << " (M=" << M << ")";
+ }
+ }
+ }
+
+ net->clear_output_memory_blocks();
+}