Skip to content

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

[GPU] Handle caller-owned USM-host memory directly for dynamic outputs on iGPUs (#37934)

Bartlomiej Filipeke96dddb8ca49
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 b769926b55a..b1ca6d9fbad 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
@@ -171,6 +171,8 @@ public:
void set_arguments();
// Implementation specific calls
bool does_node_need_lockable_output(const primitive_id& id) const;
+ // Returns whether the buffer of network output `output_id` may be the buffer of network input `input_id`.
+ bool may_alias(const primitive_id& output_id, const primitive_id& input_id) const;
std::shared_ptr<primitive_inst> get_primitive(const primitive_id& id);
std::shared_ptr<const primitive_inst> get_primitive(const primitive_id& id) const;
std::string get_primitive_info(const primitive_id& id) const;
@@ -203,6 +205,10 @@ public:
/// Invalidates cached output memory so the graph falls back to its normal memory pool.
void unregister_output_memory_block(const primitive_id& id);
+ /// @brief Detach output `id` from memory bound by an earlier set_output_memory(..., is_remote=true),
+ /// e.g. by another infer request sharing this network, so its writers re-acquire their memory.
+ void release_user_output_memory(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;
@@ -258,6 +264,8 @@ private:
memory::ptr _shape_info_ptr;
std::unordered_map<primitive_id, memory::ptr> _output_remote_mem_ptrs;
+ // Unlike _output_remote_mem_ptrs, kept after wait(): primitives still hold this memory until released.
+ std::unordered_map<primitive_id, memory::ptr> _bound_user_output_memory;
// 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;
@@ -267,6 +275,8 @@ private:
std::vector<std::shared_ptr<primitive_inst>> _inputs;
std::vector<std::shared_ptr<primitive_inst>> _outputs;
std::list<std::shared_ptr<primitive_inst>> _exec_order;
+ // First position of each primitive in _exec_order.
+ std::unordered_map<const primitive_inst*, size_t> _exec_positions;
std::list<std::shared_ptr<primitive_inst>> _data_outputs;
ov::intel_gpu::VariablesMap _variables_states;
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 b2f7b8427be..4c5cd72bf54 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
@@ -183,6 +183,22 @@ private:
void init_mappings();
bool is_batched_input(const ov::Output<const ov::Node>& port) const;
+
+ // Reject partial/offset or multiple exact overlaps; compare host tensors and RemoteTensorImpl by GPU memory range.
+ // Validate a single exact overlap downstream; output_capacity_bytes covers tail space after shrink/grow.
+ bool can_use_caller_output_memory(const std::shared_ptr<ov::ITensor>& output_tensor, size_t output_capacity_bytes);
+ // Checks the exact overlap left by can_use_caller_output_memory() against the graph via network::may_alias().
+ bool may_bind_caller_output(const std::string& output_id, const void* output_ptr) const;
+
+ struct InputAliasRange {
+ const void* ptr;
+ size_t size;
+ size_t port_idx;
+ };
+ // Rebuilt every enqueue(): a host tensor may reallocate on set_shape() without set_tensor().
+ std::vector<InputAliasRange> m_input_alias_ranges;
+ bool m_input_alias_ranges_valid = false;
+
uint64_t total_output_bytes = 0;
// Per-output-port OutputMemoryBlock for zero-copy dynamic output.
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp
index 9dad5551ff4..3929719aca6 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp
@@ -98,7 +98,7 @@ public:
#endif
/// Checks whether two memory objects represents the same physical memory
- virtual bool is_the_same_buffer(const memory& mem1, const memory& mem2) = 0;
+ virtual bool is_the_same_buffer(const memory& mem1, const memory& mem2) const = 0;
bool check_allocatable(const layout& layout, allocation_type type);
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/basic_memory_dependencies.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/basic_memory_dependencies.cpp
index 1325634fe48..188ed77a4e1 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/basic_memory_dependencies.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/basic_memory_dependencies.cpp
@@ -7,6 +7,7 @@
#include "intel_gpu/graph/program.hpp"
#include "intel_gpu/primitives/mutable_data.hpp"
#include "program_helpers.h"
+#include "stateless_kv_inst.h"
#include "intel_gpu/runtime/itt.hpp"
#include <vector>
@@ -25,10 +26,27 @@ void basic_memory_dependencies::run(program& p) {
continue;
}
+ // stateless_kv may update input 0 (`past`) in place.
+ const bool inplace_kv = node->is_type<stateless_kv>();
+
// add my dependencies to restriction list (can't share input.output buffers)
- for (const auto& it : node->get_dependencies()) {
- add_memory_dependency(node, it.first);
- add_memory_dependency(it.first, node);
+ const auto& deps = node->get_dependencies();
+ for (size_t i = 0; i < deps.size(); ++i) {
+ if (inplace_kv && i == 0) {
+ continue;
+ }
+ add_memory_dependency(node, deps[i].first);
+ add_memory_dependency(deps[i].first, node);
+ }
+
+ if (inplace_kv) {
+ // As for the oneDNN sum post-op: keep both ends of the alias out of pool sharing.
+ node->can_share_buffer(false);
+ auto* root = &node->get_dependency(0);
+ while (root->can_be_optimized() && !root->get_dependencies().empty()) {
+ root = &root->get_dependency(0);
+ }
+ root->can_share_buffer(false);
}
// LoRA can reuse the memory of the previous node, but not be optimized
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 46518de7230..d2a1f7fa444 100644
--- a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
@@ -390,6 +390,8 @@ public:
virtual void update_output_memory() {}
void clear_output_memory();
+ // Unlike clear_output_memory(), also returns pool-owned output memory so the next allocation can reuse it.
+ void release_and_clear_output_memory();
virtual int32_t get_prealloc_iter_num() { return -1; }
virtual void update_shape_info_tensor(const kernel_impl_params& params);
diff --git a/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h b/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
index c448db2b8ab..58145398e82 100644
--- a/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
@@ -69,9 +69,15 @@ public:
typed_primitive_inst(network& network, const stateless_kv_node& desc);
typed_primitive_inst(network& network) : parent(network) {}
+ // Kept across executions while present can't be written into the Result buffer in place.
+ memory::ptr& private_present() {
+ return m_private_present;
+ }
+
private:
void on_execute() override;
bool m_is_inplace = false;
+ memory::ptr m_private_present;
};
using stateless_kv_inst = typed_primitive_inst<stateless_kv>;
diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cpp
index 66a9814acae..631ddb0298b 100644
--- a/src/plugins/intel_gpu/src/graph/network.cpp
+++ b/src/plugins/intel_gpu/src/graph/network.cpp
@@ -12,6 +12,7 @@
#include <set>
#include <stack>
#include <string>
+#include <unordered_set>
#include <utility>
#include <vector>
@@ -628,20 +629,31 @@ std::vector<event::ptr> network::set_output_memory(const primitive_id& id, memor
}
auto& eng = get_engine();
- if (is_remote) {
- _output_remote_mem_ptrs[id] = mem_new;
- } else {
- _output_remote_mem_ptrs.erase(id);
- }
-
// Remote outputs need a conservative chain because a runtime-skippable
// permute may become executable after shape inference.
+ // Build before invalidation: the chain is filtered by the output's current buffer.
auto& output_chains = is_remote ? _remote_output_chains : _output_chains;
auto o_iter = output_chains.find(id);
if (o_iter == output_chains.end()) {
o_iter = output_chains.emplace(id, build_output_chain(p_inst, is_remote)).first;
}
+ if (is_remote && p_inst->is_dynamic()) {
+ const auto bound_it = _bound_user_output_memory.find(id);
+ if (bound_it == _bound_user_output_memory.end()) {
+ invalidate_ext_block_compute_nodes(id);
+ } else if (!eng.is_the_same_buffer(*bound_it->second, *mem_new) || bound_it->second->size() != mem_new->size()) {
+ release_user_output_memory(id);
+ }
+ }
+ if (is_remote) {
+ _output_remote_mem_ptrs[id] = mem_new;
+ _bound_user_output_memory[id] = mem_new;
+ } else {
+ _output_remote_mem_ptrs.erase(id);
+ _bound_user_output_memory.erase(id);
+ }
+
for (auto& prim : o_iter->second) {
auto mem = mem_new;
if (!prim->is_dynamic() && mem_new && prim->output_memory_ptr()) {
@@ -702,6 +714,65 @@ bool network::does_node_need_lockable_output(const primitive_id& id) const {
return prim_inst->get_impl() ? prim_inst->get_impl()->is_cpu() : true;
}
+bool network::may_alias(const primitive_id& output_id, const primitive_id& input_id) const {
+ const auto output = find_primitive(output_id);
+ const auto input = find_primitive(input_id);
+ if (!output->is_output() || !input->is_input())
+ return false;
+
+ // Processing order doesn't serialize independent readers of the input with the writer on an out-of-order queue.
+ if (get_stream().get_queue_type() == QueueTypes::out_of_order)
+ return false;
+
+ const auto input_pos_it = _exec_positions.find(input.get());
+ if (input_pos_it == _exec_positions.end())
+ return false;
+
+ // Walk back from the output to the primitives that actually write its buffer; none of them
+ // may be restricted from sharing a buffer with the input.
+ const auto input_uid = static_cast<uint32_t>(input->get_node().get_unique_id());
+ std::unordered_set<const primitive_inst*> visited;
+ std::stack<const primitive_inst*> pending;
+ pending.push(output.get());
+ while (!pending.empty()) {
+ const auto* inst = pending.top();
+ pending.pop();
+ if (!visited.insert(inst).second)
+ continue;
+ // A pure pass-through of the input is conservatively rejected.
+ if (inst == input.get())
+ return false;
+ // Relies on oooq_memory_dependencies to mark primitives that must not share memory with the input.
+ // Known gap: that pass skips the first non-constant node in processing order (usually an input). Will be fixed later.
+ if (inst->get_runtime_memory_dependencies().contains(input_uid))
+ return false;
+ // The input holds data from the start of execution, so anything running before it would
+ // overwrite data that its readers still need; restrictions only cover the range after it.
+ const auto pos_it = _exec_positions.find(inst);
+ if (pos_it == _exec_positions.end() || pos_it->second < input_pos_it->second)
+ return false;
+ const auto& node = inst->get_node();
+ if (!node.can_be_optimized() && !node.is_runtime_skippable())
+ continue;
+ // May borrow its buffer from a producer; if it still executes, it was already checked as a writer above.
+ const auto shape_deps = node.get_shape_infer_dependencies();
+ const auto& deps = inst->dependencies();
+ bool has_data_dep = false;
+ for (size_t i = 0; i < deps.size(); ++i) {
+ if (std::find(shape_deps.begin(), shape_deps.end(), i) != shape_deps.end())
+ continue;
+ // Restrictions are per node, so a buffer coming from a non-primary output can't be proven.
+ if (deps[i].second != 0)
+ return false;
+ pending.push(deps[i].first);
+ has_data_dep = true;
+ }
+ if (!has_data_dep)
+ return false;
+ }
+ return true;
+}
+
std::string network::get_implementation_info(const primitive_id& id) const {
try {
auto it = _primitives.find(id);
@@ -900,8 +971,8 @@ void network::invalidate_ext_block_compute_nodes(const primitive_id& output_id)
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();
+ if (!cursor->is_input() && !cursor->has_inner_networks() && !cursor->can_be_optimized()) {
+ cursor->release_and_clear_output_memory();
GPU_DEBUG_TRACE_DETAIL << "[double-buffer] cleared output memory on compute node " << cursor->id() << std::endl;
}
}
@@ -916,6 +987,9 @@ void network::register_output_memory_block(const primitive_id& id, ov::intel_gpu
}
it->second = block;
}
+ // Writers may still hold another request's memory; with unchanged shapes nothing else reallocates them.
+ invalidate_ext_block_compute_nodes(id);
+
invalidate_recording();
}
@@ -928,6 +1002,27 @@ void network::unregister_output_memory_block(const primitive_id& id) {
}
}
+void network::release_user_output_memory(const primitive_id& id) {
+ auto bound_it = _bound_user_output_memory.find(id);
+ if (bound_it == _bound_user_output_memory.end())
+ return;
+ const auto bound = std::move(bound_it->second);
+ _bound_user_output_memory.erase(bound_it);
+
+ auto chain_it = _remote_output_chains.find(id);
+ if (chain_it != _remote_output_chains.end()) {
+ for (auto* prim : chain_it->second) {
+ // Only dynamic primitives re-acquire a cleared output; inputs keep their own binding.
+ if (!prim->is_dynamic() || prim->is_input() || prim->has_inner_networks())
+ continue;
+ if (prim->output_memory_ptr() && get_engine().is_the_same_buffer(*prim->output_memory_ptr(), *bound))
+ prim->clear_output_memory();
+ }
+ }
+ // Also covers a producer that borrowed the bound memory in realloc_outputs().
+ 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;
@@ -946,6 +1041,7 @@ void network::clear_output_memory_blocks() {
void network::add_to_exec_order(const primitive_id& id) {
auto inst = get_primitive(id);
+ _exec_positions.emplace(inst.get(), _exec_order.size());
_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 b9c9401a8c5..152b6122ca6 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -285,9 +285,14 @@ void primitive_inst::check_memory_compatibility(const memory& mem, const layout&
event::ptr primitive_inst::set_output_memory(memory::ptr mem_new, bool check, size_t idx) {
auto& eng = get_network().get_engine();
+ // A dynamic output bound at the same pointer may still change capacity, e.g. a smaller caller view.
+ const auto same_capacity = [&]() {
+ const auto& new_layout = mem_new->get_layout();
+ return new_layout.data_type == _outputs[idx]->get_layout().data_type && new_layout.get_linear_size() == _max_output_layout_count[idx];
+ };
// skip all the buzz if no action actually required
event::ptr ev = nullptr;
- if (_outputs[idx] && eng.is_the_same_buffer(*mem_new, *_outputs[idx])) {
+ if (_outputs[idx] && eng.is_the_same_buffer(*mem_new, *_outputs[idx]) && (!is_dynamic() || same_capacity())) {
// The remote permute alias is stored only for the primary output owned by this primitive.
if (idx == 0)
_remote_permute_output_alias.reset();
@@ -704,6 +709,13 @@ void primitive_inst::clear_output_memory() {
_remote_permute_output_alias.reset();
}
+void primitive_inst::release_and_clear_output_memory() {
+ if (_mem_allocated && _outputs[0])
+ get_network().get_memory_pool().release_memory(_outputs[0].get(), get_node().get_unique_id(), id(), get_network_id());
+ _mem_allocated = false;
+ clear_output_memory();
+}
+
void primitive_inst::realloc_intermediates() {
OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("realloc_intermediates: " + id()));
GPU_DEBUG_PROFILED_STAGE(instrumentation::pipeline_stage::memory_allocation);
@@ -840,10 +852,53 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
OPENVINO_ASSERT(past_tensor, "[GPU] Input memory is not prepared for stateless_kv node ", id());
const auto present_tensor = result.output_memory_ptr();
OPENVINO_ASSERT(present_tensor, "[GPU] Output memory of ", result.id(), " is not prepared for stateless_kv node ", id());
- const auto is_same = _network.get_engine().is_the_same_buffer(*present_tensor, *past_tensor);
+ auto& engine = _network.get_engine();
+ const auto is_same = engine.is_the_same_buffer(*present_tensor, *past_tensor);
const auto& present_layout = result._impl_params->get_output_layout();
- if (mid_layout == present_layout) {
- result.set_can_be_optimized(true);
+ const auto same_placement = [&]() {
+ return past_layout.data_type == mid_layout.data_type && past_layout.format == mid_layout.format &&
+ past_layout.get_pitches() == mid_layout.get_pitches() && past_layout.get_linear_offset() == mid_layout.get_linear_offset();
+ };
+ // The Result buffer may be a caller buffer that is also one of our inputs; check our own restrictions.
+ const auto aliases_restricted_input = [&]() {
+ const auto& deps = dependencies();
+ for (size_t i = 0; i < deps.size() && i < inputs_memory_count(); ++i) {
+ const auto dep_memory = input_memory_ptr(i);
+ if (!dep_memory || !engine.is_the_same_buffer(*present_tensor, *dep_memory))
+ continue;
+ for (const auto* dep = deps[i].first; dep != nullptr;) {
+ if (_runtime_memory_dependencies.contains(static_cast<uint32_t>(dep->get_node().get_unique_id())))
+ return true;
+ dep = dep->can_be_optimized() && !dep->dependencies().empty() ? dep->dependencies().front().first : nullptr;
+ }
+ }
+ return false;
+ };
+ // Write present into a private buffer when the Result buffer can't hold our output in place:
+ // a different element type or format, a restricted input, or past whose elements would move.
+ const auto use_private_present = present_layout.data_type != mid_layout.data_type || present_layout.format != mid_layout.format ||
+ aliases_restricted_input() || (is_same && !same_placement());
+ auto kv_present = present_tensor;
+ auto& private_present = downcast<stateless_kv_inst>(*this).private_present();
+ if (use_private_present) {
+ const bool can_reuse = private_present && private_present->size() >= mid_layout.bytes_count();
+ auto& sp = *get_network().get_shape_predictor();
+ const auto prealloc = sp.predict_preallocation_shape(id(), mid_layout, can_reuse);
+ if (!can_reuse) {
+ auto alloc_layout = mid_layout;
+ if (prealloc.first && sp.can_preallocate(ov::shape_size(prealloc.second) * data_type_traits::size_of(mid_layout.data_type)))
+ alloc_layout = mid_layout.clone_with_other_shape(prealloc.second);
+ if (alloc_layout.bytes_count() < mid_layout.bytes_count())
+ alloc_layout = mid_layout;
+ private_present = engine.allocate_memory(alloc_layout, engine.get_preferred_memory_allocation_type(), false);
+ }
+ kv_present = engine.reinterpret_buffer(*private_present, mid_layout);
+ // The Result stays a real reorder and copies the private present into its own buffer.
+ result.set_can_be_optimized(false);
+ } else {
+ private_present.reset();
+ if (mid_layout == present_layout)
+ result.set_can_be_optimized(true);
}
GPU_DEBUG_TRACE_DETAIL << id() << ": input[" << past_tensor->buffer_ptr() << "](" << past_tensor->get_layout().to_short_string() << ") and output["
<< present_tensor->buffer_ptr() << "](" << present_tensor->get_layout().to_short_string() << ")(" << result.id()
@@ -855,8 +910,8 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
if (_outputs[0]) {
OPENVINO_ASSERT(!_mem_allocated, "stateless_kv should never allocate output[0] for itself");
}
- _outputs[0] = present_tensor;
- _outputs[1] = get_network().get_engine().reinterpret_buffer(*present_tensor, target_layout);
+ _outputs[0] = kv_present;
+ _outputs[1] = engine.reinterpret_buffer(*kv_present, target_layout);
this->_mem_allocated = false;
}
@@ -905,7 +960,8 @@ void primitive_inst::realloc_outputs(bool prev_execution_skipped) {
_remote_permute_output_alias.reset();
}
- if (users.size() == 1 && users.front()->get_node().is_type<reorder>() && users.front()->can_be_optimized()) {
+ // stateless_kv picks both outputs from its Result in realloc_outputs_for_stateless_kv().
+ if (!get_node().is_type<stateless_kv>() && users.size() == 1 && users.front()->get_node().is_type<reorder>() && users.front()->can_be_optimized()) {
auto* reorder_inst = users.front();
if (reorder_inst->is_output() && reorder_inst->output_memory_ptr() && get_network().has_output_remote_memory_ptr(reorder_inst->id()) &&
get_network().get_engine().is_the_same_buffer(get_network().get_output_remote_memory(reorder_inst->id()), reorder_inst->output_memory())) {
diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cpp
index 7aa04ef0f57..bfad75b34f5 100644
--- a/src/plugins/intel_gpu/src/graph/program.cpp
+++ b/src/plugins/intel_gpu/src/graph/program.cpp
@@ -802,8 +802,7 @@ const std::vector<primitive_id>& program::get_allocating_order(bool forced_updat
}
void program::prepare_memory_dependencies() {
- if (!_config.get_enable_memory_pool())
- return;
+ // Computed even without the memory pool: network::may_alias() relies on these restrictions.
for (const auto& node : get_processing_order()) {
node->add_memory_dependency(*node);
}
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 929893d62da..3802f91cce3 100644
--- a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
+++ b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
@@ -5,6 +5,7 @@
#include "intel_gpu/plugin/sync_infer_request.hpp"
#include <algorithm>
+#include <cstdint>
#include <functional>
#include <iterator>
#include <map>
@@ -47,6 +48,35 @@ bool same_host_mem(cldnn::memory::cptr memory, const uint8_t* host_ptr) {
return device_ptr == host_ptr;
}
+bool byte_ranges_overlap(const void* lhs_ptr, size_t lhs_size, const void* rhs_ptr, size_t rhs_size) {
+ if (lhs_ptr == nullptr || rhs_ptr == nullptr || lhs_size == 0 || rhs_size == 0)
+ return false;
+
+ const auto lhs_begin = reinterpret_cast<uintptr_t>(lhs_ptr);
+ const auto rhs_begin = reinterpret_cast<uintptr_t>(rhs_ptr);
+ return lhs_begin < rhs_begin ? rhs_begin - lhs_begin < lhs_size : lhs_begin - rhs_begin < rhs_size;
+}
+
+// Byte range backing a tensor for aliasing checks: host tensor -> data()/byte_size; RemoteTensorImpl
+// -> cldnn memory, but only if usm_host (device pointers aren't comparable to host ones). Else {nullptr, 0}.
+std::pair<const void*, size_t> tensor_alias_range(const std::shared_ptr<ov::ITensor>& tensor) {
+ if (!tensor)
+ return {nullptr, 0};
+ if (auto remote = std::dynamic_pointer_cast<ov::intel_gpu::RemoteTensorImpl>(tensor)) {
+ // get_memory() builds a reinterpreted memory object, so filter by allocation type first.
+ const auto original = remote->get_original_memory();
+ if (!original || original->get_allocation_type() != cldnn::allocation_type::usm_host)
+ return {nullptr, 0};
+ auto memory = remote->get_memory();
+ if (memory && memory->get_allocation_type() == cldnn::allocation_type::usm_host)
+ return {memory->buffer_ptr(), memory->size()};
+ return {nullptr, 0};
+ }
+ if (std::dynamic_pointer_cast<ov::IRemoteTensor>(tensor))
+ return {nullptr, 0};
+ return {tensor->data(), tensor->get_byte_size()};
+}
+
inline bool all_remote_buffers(const std::vector<ov::SoPtr<ov::ITensor>>& tensors) {
return std::all_of(tensors.begin(), tensors.end(), [](const ov::SoPtr<ov::ITensor>& tensor) {
if (auto remote_ptr = std::dynamic_pointer_cast<ov::intel_gpu::RemoteTensorImpl>(tensor._ptr)) {
@@ -404,6 +434,7 @@ void SyncInferRequest::enqueue() {
}
}
+ m_input_alias_ranges_valid = false;
for (const auto& it : m_output_ports_map) {
size_t port_idx = it.first;
const auto& port = it.second;
@@ -1193,8 +1224,8 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
auto device_tensor_et = convert_to_supported_device_type(element_type);
bool convert_needed = is_convert_required(device_tensor_et, element_type);
- // Even if the network is dynamic, if user tensor's shape is static, remote tensor can be set as plugin's output tensor
if (is_remote_tensor_impl && !convert_needed) {
+ // Even if the network is dynamic, if user tensor's shape is static, remote tensor can be set as plugin's output tensor
m_plugin_outputs[output_idx] = user_tensor_wrapper;
}
@@ -1202,7 +1233,8 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
bool need_lockable_mem = network->does_node_need_lockable_output(internal_name);
bool has_device_buffer = m_plugin_outputs.count(output_idx) > 0;
bool update_device_tensor =
- !has_device_buffer || is_generic_remote || (m_plugin_outputs[output_idx].owner == TensorOwner::USER && !is_remote_tensor_impl);
+ !has_device_buffer || is_generic_remote ||
+ (m_plugin_outputs[output_idx].owner == TensorOwner::USER && !is_remote_tensor_impl);
if (update_device_tensor) {
if (!is_remote_tensor_impl) {
m_plugin_outputs[output_idx] =
@@ -1211,10 +1243,84 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
m_plugin_outputs[output_idx] = {create_device_tensor(pshape, device_tensor_et, need_lockable_mem || convert_needed), TensorOwner::PLUGIN};
}
}
+ } else if (is_generic_remote) {
+ // A generic remote output cannot reuse a previous dynamic binding.
+ m_plugin_outputs.erase(output_idx);
+ }
+
+ if (is_dynamic && user_tensor_wrapper.owner == TensorOwner::USER) {
+ // Caller-owned memory and the plugin-owned OutputMemoryBlock are mutually exclusive.
+ network->unregister_output_memory_block(internal_name);
+
+ if (!is_remote_tensor_impl && !is_generic_remote) {
+ const bool had_caller_owned_output_buffer =
+ m_plugin_outputs.count(output_idx) > 0 && m_plugin_outputs[output_idx].owner == TensorOwner::USER;
+ auto& engine = m_graph->get_engine();
+ // Caller output memory is only bound directly on iGPU; elsewhere the graph never writes into it.
+ const bool is_igpu = engine.get_device_info().dev_type == cldnn::device_type::integrated_gpu;
+ const bool overlap_unsupported = is_igpu && !can_use_caller_output_memory(user_tensor, user_tensor_wrapper.actual_size);
+ // Import a caller USM-host pointer as a shared remote tensor so the graph writes into it directly.
+ // Non-contiguous views stay on the copy path, so stride handling lives in one place.
+ const bool can_share_user_usm_host =
+ is_igpu && !convert_needed && !overlap_unsupported && user_tensor->is_continuous() &&
+ engine.detect_usm_allocation_type(user_tensor->data()) == cldnn::allocation_type::usm_host &&
+ can_use_usm_host(engine, total_output_bytes);
+ const bool need_lockable_mem = network->does_node_need_lockable_output(internal_name);
+ auto create_plugin_output = [&]() -> TensorWrapper {
+ auto tensor_shape = user_tensor->get_shape();
+ auto actual_memory_shape = predict_shape(internal_name,
+ cldnn::layout(tensor_shape,
+ device_tensor_et,
+ cldnn::format::get_default_format(tensor_shape.size())),
+ *m_shape_predictor);
+ // Check if an existing plugin output can be reused, otherwise create a new one.
+ auto existing = m_plugin_outputs.find(output_idx);
+ if (existing != m_plugin_outputs.end() && existing->second.owner == TensorOwner::PLUGIN) {
+ auto existing_tensor = std::dynamic_pointer_cast<RemoteTensorImpl>(existing->second.ptr);
+ auto required_layout = cldnn::layout(actual_memory_shape,
+ device_tensor_et,
+ cldnn::format::get_default_format(actual_memory_shape.size()));
+ if (existing_tensor && existing_tensor->get_element_type() == device_tensor_et &&
+ existing_tensor->get_original_memory()->get_layout().format == required_layout.format &&
+ existing_tensor->get_original_memory()->count() >= ov::shape_size(actual_memory_shape) &&
+ existing_tensor->get_original_memory()->size() >= required_layout.bytes_count() &&
+ ((!need_lockable_mem && !convert_needed) ||
+ existing_tensor->get_original_memory()->get_allocation_type() != cldnn::allocation_type::usm_device)) {
+ existing_tensor->set_shape(actual_memory_shape);
+ return existing->second;
+ }
+ }
+ return {create_device_tensor(actual_memory_shape, device_tensor_et, need_lockable_mem || convert_needed), TensorOwner::PLUGIN};
+ };
+ if (can_share_user_usm_host) {
+ // Bind the caller's full recorded capacity: wait() may have shrunk the tensor's logical shape.
+ const ov::Shape capacity_shape{user_tensor_wrapper.actual_size * 8 / device_tensor_et.bitwidth()};
+ TensorWrapper candidate{std::make_shared<RemoteTensorImpl>(m_context,
+ capacity_shape,
+ ::data_type_for_remote_tensor(device_tensor_et),
+ TensorType::BT_USM_SHARED,
+ user_tensor->data()),
+ TensorOwner::USER};
+ auto candidate_tensor = std::dynamic_pointer_cast<RemoteTensorImpl>(candidate.ptr);
+ if (candidate_tensor && candidate_tensor->get_memory() && candidate_tensor->get_memory()->size() != 0 &&
+ may_bind_caller_output(internal_name, user_tensor->data())) {
+ m_plugin_outputs[output_idx] = std::move(candidate);
+ } else {
+ m_plugin_outputs[output_idx] = create_plugin_output();
+ }
+ } else if (overlap_unsupported || had_caller_owned_output_buffer) {
+ // Unsafe input overlap, or a stale caller binding to drop: use plugin-owned memory, copied out in wait().
+ m_plugin_outputs[output_idx] = create_plugin_output();
+ }
+ }
}
// 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()) {
+ // Requests on one stream share the network: drop a caller buffer bound by another request.
+ if (is_dynamic) {
+ network->release_user_output_memory(internal_name);
+ }
// 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) {
@@ -1222,16 +1328,13 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
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();
+ // A dynamic output binds the full allocation: its logical shape follows each run, writers reinterpret it anyway.
+ auto output_memory = is_dynamic ? output_tensor->get_original_memory() : output_tensor->get_memory();
GPU_DEBUG_TRACE_DETAIL << internal_name << " with index " << output_idx << " prepare output: " << output_memory->buffer_ptr() << std::endl;
return network->set_output_memory(internal_name, output_memory, is_dynamic && (is_remote_tensor_impl || user_tensor));
}
@@ -1253,4 +1356,53 @@ bool SyncInferRequest::is_batched_input(const ov::Output<const ov::Node>& port)
return m_batched_tensors.count(port.get_tensor_ptr()) > 0;
}
+bool SyncInferRequest::can_use_caller_output_memory(const std::shared_ptr<ov::ITensor>& output_tensor,
+ size_t output_capacity_bytes) {
+ const auto [output_ptr, output_logical_size] = tensor_alias_range(output_tensor);
+ if (output_ptr == nullptr)
+ return true;
+ // wait() can shrink the output tensor's logical shape while the caller keeps the larger allocation,
+ // so use the recorded capacity: a later growth would write the full span and could hit an input in the tail.
+ const size_t output_size = std::max(output_logical_size, output_capacity_bytes);
+
+ if (!m_input_alias_ranges_valid) {
+ m_input_alias_ranges.clear();
+ auto inputs = m_user_inputs.read();
+ for (const auto& entry : *inputs) {
+ const auto& wrapper = entry.second;
+ const auto [input_ptr, input_logical_size] = tensor_alias_range(wrapper.ptr);
+ if (input_ptr == nullptr)
+ continue;
+ // Like the output span, use recorded capacity to catch outputs starting in an input's unused tail.
+ m_input_alias_ranges.push_back({input_ptr, std::max(input_logical_size, wrapper.actual_size), entry.first});
+ }
+ m_input_alias_ranges_valid = true;
+ }
+
+ size_t overlapping_inputs = 0;
+ for (const auto& input : m_input_alias_ranges) {
+ if (!byte_ranges_overlap(output_ptr, output_size, input.ptr, input.size))
+ continue;
+ // A partial/offset overlap is never safe; an exact-address overlap is left to may_bind_caller_output().
+ if (input.ptr != output_ptr)
+ return false;
+ if (++overlapping_inputs > 1)
+ return false;
+ }
+ return true;
+}
+
+bool SyncInferRequest::may_bind_caller_output(const std::string& output_id, const void* output_ptr) const {
+ for (const auto& input : m_input_alias_ranges) {
+ if (input.ptr != output_ptr)
+ continue;
+ // An input copied into plugin memory isn't the graph's buffer, so the output can't clobber it.
+ const auto plugin_input = m_plugin_inputs.find(input.port_idx);
+ if (plugin_input != m_plugin_inputs.end() && tensor_alias_range(plugin_input->second.ptr).first != output_ptr)
+ continue;
+ return m_graph->get_network()->may_alias(output_id, m_graph->input_port_index_to_internal(input.port_idx)[0]);
+ }
+ return true;
+}
+
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.cpp b/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.cpp
index f57a9d44581..cf10f72b530 100644
--- a/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.cpp
@@ -325,7 +325,7 @@ memory::ptr ocl_engine::reinterpret_handle(const layout& new_layout, shared_mem_
}
}
-bool ocl_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) {
+bool ocl_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) const {
if (mem1.get_engine() != this || mem2.get_engine() != this) {
return false;
}
diff --git a/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.hpp b/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.hpp
index 0d25e4c4003..803320353d4 100644
--- a/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ocl/ocl_engine.hpp
@@ -30,7 +30,7 @@ public:
memory_ptr create_hostbuffer(const void* cpu_address, size_t data_size, allocation_type _allocation_type, const layout output_layout, bool host_read_only = false) override;
memory_ptr reinterpret_buffer(const memory& memory, const layout& new_layout) override;
memory_ptr import_buffer(const layout&, ov::intel_gpu::os_handle_param external_handle) override;
- bool is_the_same_buffer(const memory& mem1, const memory& mem2) override;
+ bool is_the_same_buffer(const memory& mem1, const memory& mem2) const override;
void release_external_memory(cl_mem) const;
void* get_user_context(runtime_types rt_type) const override;
diff --git a/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.cpp b/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.cpp
index 8d1b09313d8..33dd2a8d135 100644
--- a/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.cpp
+++ b/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.cpp
@@ -221,7 +221,7 @@ memory::ptr sycl_engine::reinterpret_handle(const layout& new_layout, shared_mem
}
}
-bool sycl_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) {
+bool sycl_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) const {
if (mem1.get_engine() != this || mem2.get_engine() != this)
return false;
if (mem1.get_allocation_type() != mem2.get_allocation_type())
diff --git a/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.hpp b/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.hpp
index 1603a624454..643a969ece6 100644
--- a/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.hpp
+++ b/src/plugins/intel_gpu/src/runtime/sycl/sycl_engine.hpp
@@ -34,7 +34,7 @@ public:
memory_ptr create_hostbuffer(const void* cpu_address, size_t data_size, allocation_type _allocation_type, const layout output_layout, bool host_read_only = false) override;
memory_ptr reinterpret_buffer(const memory& memory, const layout& new_layout) override;
memory_ptr import_buffer(const layout& layout, ov::intel_gpu::os_handle_param external_handle) override;
- bool is_the_same_buffer(const memory& mem1, const memory& mem2) override;
+ bool is_the_same_buffer(const memory& mem1, const memory& mem2) const override;
void* get_user_context(runtime_types rt_type) const override;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_engine.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_engine.cpp
index f062f7be3f6..10e5d5e2b25 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_engine.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_engine.cpp
@@ -277,7 +277,7 @@ memory_ptr ze_engine::create_hostbuffer_impl(void* cpu_address,
return std::make_shared<ze::gpu_usm>(this, output_layout, imported_buffer, allocation, mem_tracker);
}
-bool ze_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) {
+bool ze_engine::is_the_same_buffer(const memory& mem1, const memory& mem2) const {
if (mem1.get_engine() != this || mem2.get_engine() != this)
return false;
if (mem1.get_allocation_type() != mem2.get_allocation_type())
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_engine.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_engine.hpp
index 775e8b529be..4aeb92cd59f 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_engine.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_engine.hpp
@@ -30,7 +30,7 @@ public:
memory_ptr create_hostbuffer(void* cpu_address, size_t data_size, allocation_type _allocation_type, const layout output_layout) override;
memory_ptr create_hostbuffer(const void* cpu_address, size_t data_size, allocation_type _allocation_type, const layout output_layout, bool host_read_only = false) override;
memory_ptr reinterpret_buffer(const memory& memory, const layout& new_layout) override;
- bool is_the_same_buffer(const memory& mem1, const memory& mem2) override;
+ bool is_the_same_buffer(const memory& mem1, const memory& mem2) const override;
void* get_user_context(runtime_types rt_type) const override;
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 3f8fe06afb0..e686f09d7b1 100644
--- a/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp
+++ b/src/plugins/intel_gpu/tests/functional/behavior/infer_request.cpp
@@ -22,8 +22,11 @@
#include "common_test_utils/subgraph_builders/read_concat_split_assign.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/runtime/intel_gpu/ocl/ocl.hpp"
#include "openvino/runtime/intel_gpu/ocl/ocl_wrapper.hpp"
+#include "openvino/runtime/intel_gpu/properties.hpp"
namespace {
typedef std::tuple<
@@ -106,6 +109,15 @@ static std::shared_ptr<ov::Model> makeStaticInputModel(ov::Shape& shape_out) {
return std::make_shared<ov::Model>(results, ov::ParameterVector{param});
}
+// Caller-owned USM-host output sharing needs an integrated GPU whose driver actually exposes USM;
+// RemoteContextImpl rejects USM_HOST allocation when unified shared memory is unsupported/disabled.
+static bool gpu_supports_usm_host_output_sharing(ov::Core& core) {
+ if (core.get_property(ov::test::utils::DEVICE_GPU, ov::device::type) != ov::device::Type::INTEGRATED)
+ return false;
+ const auto caps = core.get_property(ov::test::utils::DEVICE_GPU, ov::device::capabilities);
+ return std::find(caps.begin(), caps.end(), ov::intel_gpu::capability::USM_MEMORY) != caps.end();
+}
+
// Static input must be inferable when set_tensor() is never called.
TEST(TensorTest, smoke_lazyAllocStaticInputInferWithoutSetTensor) {
ov::Shape shape;
@@ -167,10 +179,809 @@ TEST(TensorTest, smoke_lazyAllocStaticOutputReusesUserTensor) {
}
}
+// Dynamic output bound to a caller-owned iGPU USM-host buffer produces correct values.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHost) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 4});
+ auto relu = std::make_shared<ov::op::v0::Relu>(input);
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{relu}, ov::ParameterVector{input});
+
+ auto remote_context = core.get_default_context(ov::test::utils::DEVICE_GPU);
+ auto compiled_model = core.compile_model(model, remote_context);
+
+ const ov::Shape shape{2, 4};
+ ov::Tensor input_tensor(ov::element::f32, shape);
+ const std::vector<float> input_values{-4.0f, -3.0f, -2.0f, -1.0f, 1.0f, 2.0f, 3.0f, 4.0f};
+ std::copy(input_values.begin(), input_values.end(), input_tensor.data<float>());
+
+ auto gpu_context = remote_context.as<ov::intel_gpu::ocl::ClContext>();
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ ov::Tensor output_tensor(ov::element::f32, shape, usm_allocation.get());
+ ASSERT_FALSE(output_tensor.is<ov::intel_gpu::ocl::USMTensor>());
+ std::fill_n(output_tensor.data<float>(), output_tensor.get_size(), -1.0f);
+
+ auto request = compiled_model.create_infer_request();
+ request.set_input_tensor(input_tensor);
+ request.set_output_tensor(output_tensor);
+ OV_ASSERT_NO_THROW(request.infer());
+
+ const std::vector<float> expected{0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 2.0f, 3.0f, 4.0f};
+ auto actual = request.get_output_tensor();
+ // Verifies caller-pointer identity and values, not zero-copy: data() stays caller-owned even on the copy path.
+ // Graph-level zero-copy is asserted in unit/dynamic_execution/zero_copy_output_test.cpp.
+ ASSERT_EQ(actual.data(), usm_allocation.get());
+ ASSERT_EQ(actual.get_size(), expected.size());
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_FLOAT_EQ(actual.data<const float>()[i], expected[i]);
+ }
+}
+
+static std::shared_ptr<ov::Model> makeDynamicReluModel() {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 4});
+ auto relu = std::make_shared<ov::op::v0::Relu>(input);
+ return std::make_shared<ov::Model>(ov::OutputVector{relu}, ov::ParameterVector{input});
+}
+
+static std::shared_ptr<ov::Model> makeDynamicMatMulModel(const size_t k, std::vector<float>& weights_data) {
+ weights_data.resize(k * k);
+ for (size_t i = 0; i < weights_data.size(); ++i) {
+ weights_data[i] = static_cast<float>((i % 7) + 1) * 0.01f;
+ }
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, static_cast<int64_t>(k)});
+ auto weights = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{k, k}, weights_data);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(param, weights, false, false);
+ return std::make_shared<ov::Model>(ov::OutputVector{matmul}, ov::ParameterVector{param});
+}
+
+static std::vector<float> reference_matmul(const ov::Shape& shape,
+ const size_t k,
+ const std::vector<float>& input_values,
+ const std::vector<float>& weights_data) {
+ std::vector<float> expected(ov::shape_size(shape), 0.0f);
+ for (size_t r = 0; r < shape[0]; ++r) {
+ for (size_t c = 0; c < k; ++c) {
+ float acc = 0.0f;
+ for (size_t col = 0; col < k; ++col) {
+ acc += input_values[r * k + col] * weights_data[col * k + c];
+ }
+ expected[r * k + c] = acc;
+ }
+ }
+ return expected;
+}
+
+static int64_t gpu_mem_in_use(const ov::Core& core) {
+ int64_t total = 0;
+ for (const auto& [type, bytes] : core.get_property(ov::test::utils::DEVICE_GPU, ov::intel_gpu::memory_statistics)) {
+ total += static_cast<int64_t>(bytes);
+ }
+ return total;
+}
+
+static int64_t f32_bytes(const ov::Shape& shape) {
+ return static_cast<int64_t>(ov::shape_size(shape) * sizeof(float));
+}
+
+// Imported caller USM isn't engine-tracked, so a copy fallback shows up as >= one extra output buffer.
+// Half an output buffer of margin absorbs run-to-run variance but still catches a full extra buffer.
+static void expect_extra_output_buffer(int64_t growth, int64_t baseline_growth, int64_t output_bytes) {
+ EXPECT_GE(growth - baseline_growth, output_bytes - output_bytes / 2)
+ << "growth=" << growth << " B, baseline=" << baseline_growth << " B, output=" << output_bytes
+ << " B: expected a plugin-owned output buffer (copy fallback)";
+}
+
+static void expect_no_extra_output_buffer(int64_t growth, int64_t baseline_growth, int64_t output_bytes) {
+ EXPECT_LT(growth - baseline_growth, output_bytes / 2)
+ << "growth=" << growth << " B, baseline=" << baseline_growth << " B, output=" << output_bytes
+ << " B: caller USM-host output likely fell back to a plugin-owned copy";
+}
+
+// Small integers stay exact through the default f16 inference precision.
+static float relu_test_input(size_t i) {
+ return static_cast<float>(i % 17) - 8.0f;
+}
+
+static void fill_relu_test_input(ov::Tensor& tensor) {
+ auto* data = tensor.data<float>();
+ for (size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = relu_test_input(i);
+ }
+}
+
+static bool matches_relu_of_test_input(const ov::Tensor& tensor) {
+ const auto* data = tensor.data<const float>();
+ for (size_t i = 0; i < tensor.get_size(); ++i) {
+ const float in = relu_test_input(i);
+ if (data[i] != (in > 0.0f ? in : 0.0f)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Experimental: zero-copy must allocate ~one output buffer less than the same run with an ordinary
+// host output (copy fallback).
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostAllocatesLessThanCopyFallback) {
+ {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+ }
+
+ // makeDynamicReluModel is [?, 4]; 262144 rows makes a 4 MB f32 output so it dominates noise.
+ const ov::Shape shape{262144, 4};
+ constexpr size_t kIterations = 3;
+
+ // Each variant uses its own Core so graph-held buffers from the other variant can't leak in.
+ auto measure = [&](bool usm_output) -> int64_t {
+ auto core = ov::Core();
+ auto remote_context = core.get_default_context(ov::test::utils::DEVICE_GPU);
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), remote_context);
+ auto gpu_context = remote_context.as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ // Allocated in both variants so the caller buffer's own tracked bytes don't skew the delta.
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ std::vector<float> host_output(ov::shape_size(shape));
+ ov::Tensor input_tensor(ov::element::f32, shape);
+ fill_relu_test_input(input_tensor);
+ void* output_ptr = usm_output ? usm_allocation.get() : static_cast<void*>(host_output.data());
+ request.set_input_tensor(input_tensor);
+ request.set_output_tensor(ov::Tensor(ov::element::f32, shape, output_ptr));
+
+ const int64_t before = gpu_mem_in_use(core);
+ for (size_t iter = 0; iter < kIterations; ++iter) {
+ request.infer();
+ }
+ const int64_t delta = gpu_mem_in_use(core) - before;
+
+ auto actual = request.get_output_tensor();
+ EXPECT_EQ(actual.data(), output_ptr);
+ EXPECT_TRUE(matches_relu_of_test_input(actual)) << "usm_output=" << usm_output;
+ return delta;
+ };
+
+ const int64_t zero_copy_delta = measure(true);
+ const int64_t copy_delta = measure(false);
+ expect_extra_output_buffer(copy_delta, zero_copy_delta, f32_bytes(shape));
+}
+
+// A caller buffer sized for the max shape stays bound and correct across smaller/larger runtime shapes.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostGrowthWithinCapacity) {
+ {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+ }
+
+ // Rows are scaled so the max output (8 MB) dominates allocation noise.
+ constexpr size_t kRowScale = 65536;
+ const ov::Shape max_shape{8 * kRowScale, 4};
+
+ // Same run with a caller USM-host output vs an ordinary host output (copy fallback), each in its own Core.
+ auto measure = [&](bool usm_output) -> int64_t {
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, max_shape);
+ std::vector<float> host_output(ov::shape_size(max_shape));
+ void* output_ptr = usm_output ? usm_allocation.get() : static_cast<void*>(host_output.data());
+
+ // Bind the max-capacity caller buffer exactly once; the loop varies only the input shape.
+ request.set_output_tensor(ov::Tensor(ov::element::f32, max_shape, output_ptr));
+
+ const int64_t before = gpu_mem_in_use(core);
+ for (const size_t rows : {size_t{2}, size_t{8}, size_t{4}}) {
+ const ov::Shape shape{rows * kRowScale, 4};
+ // The first bind (pre-shrink) fixes capacity at max_shape and same-pointer rebinds are
+ // no-ops (is_the_same_buffer), so the caller buffer stays zero-copy across all shapes.
+
+ ov::Tensor input_tensor(ov::element::f32, shape);
+ fill_relu_test_input(input_tensor);
+ request.set_input_tensor(input_tensor);
+ request.infer();
+
+ auto actual = request.get_output_tensor();
+ EXPECT_EQ(actual.data(), output_ptr);
+ EXPECT_EQ(actual.get_shape(), shape);
+ EXPECT_TRUE(matches_relu_of_test_input(actual)) << "rows=" << shape[0] << " usm_output=" << usm_output;
+ }
+ return gpu_mem_in_use(core) - before;
+ };
+
+ const int64_t zero_copy_growth = measure(true);
+ const int64_t copy_growth = measure(false);
+ expect_extra_output_buffer(copy_growth, zero_copy_growth, f32_bytes(max_shape));
+}
+
+// wait() shrinks a dynamic RemoteTensor output's shape; a later growth must still fit its full allocation.
+TEST(TensorTest, smoke_dynamicOutputRemoteTensorGrowthAfterShrinkWithinCapacity) {
+ {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "USM-host remote tensors require an iGPU with USM support";
+ }
+ }
+
+ constexpr size_t kRowScale = 65536;
+ const ov::Shape max_shape{8 * kRowScale, 4};
+
+ auto core = ov::Core();
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, max_shape);
+ request.set_output_tensor(usm_allocation);
+
+ auto run = [&](size_t rows) {
+ const ov::Shape shape{rows * kRowScale, 4};
+ ov::Tensor input_tensor(ov::element::f32, shape);
+ fill_relu_test_input(input_tensor);
+ request.set_input_tensor(input_tensor);
+ request.infer();
+
+ EXPECT_EQ(request.get_output_tensor().get_shape(), shape);
+ EXPECT_TRUE(matches_relu_of_test_input(ov::Tensor(ov::element::f32, shape, usm_allocation.get()))) << "rows=" << rows;
+ };
+
+ // Warm up at the max shape so input and intermediate buffers already have their final size.
+ run(8);
+ const int64_t before = gpu_mem_in_use(core);
+ // The 8-row run follows a shrink to 2 rows; a fallback buffer is freed again on the next rebind, so check each run.
+ int64_t max_growth = 0;
+ for (const size_t rows : {size_t{2}, size_t{8}, size_t{4}}) {
+ run(rows);
+ max_growth = std::max(max_growth, gpu_mem_in_use(core) - before);
+ }
+ expect_no_extra_output_buffer(max_growth, 0, f32_bytes(max_shape));
+}
+
+// Runtime output exceeding the caller buffer fails safely (throws) without corrupting caller memory.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostGrowthBeyondCapacityIsSafe) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ const ov::Shape small_shape{2, 4};
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, small_shape);
+ ov::Tensor output_tensor(ov::element::f32, small_shape, usm_allocation.get());
+ request.set_output_tensor(output_tensor);
+
+ ov::Tensor small_input(ov::element::f32, small_shape);
+ std::fill_n(small_input.data<float>(), small_input.get_size(), 1.0f);
+ request.set_input_tensor(small_input);
+ OV_ASSERT_NO_THROW(request.infer());
+ ASSERT_EQ(request.get_output_tensor().data(), usm_allocation.get());
+
+ // Sentinel detects any out-of-bounds write into the caller buffer during the oversized run.
+ constexpr float sentinel = -17.0f;
+ std::fill_n(static_cast<float*>(usm_allocation.get()), ov::shape_size(small_shape), sentinel);
+
+ ov::Tensor large_input(ov::element::f32, ov::Shape{8, 4});
+ std::fill_n(large_input.data<float>(), large_input.get_size(), 1.0f);
+ request.set_input_tensor(large_input);
+ ASSERT_ANY_THROW(request.infer());
+
+ const auto* caller_data = static_cast<const float*>(usm_allocation.get());
+ for (size_t i = 0; i < ov::shape_size(small_shape); ++i) {
+ ASSERT_FLOAT_EQ(caller_data[i], sentinel);
+ }
+}
+
+// Rebinding a smaller view at the same pointer must shrink the bound capacity, so the GPU never writes past the new view.
+// f32 keeps the Result a skipped reorder; f16 makes it a converting reorder that writes the caller buffer itself.
+class TensorSmallerViewSamePointer : public ::testing::TestWithParam<ov::element::Type> {};
+
+TEST_P(TensorSmallerViewSamePointer, smoke_dynamicOutputCallerOwnedUsmHostSmallerViewSamePointerIsSafe) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model = core.compile_model(makeDynamicReluModel(),
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(GetParam()));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ const ov::Shape large_shape{8, 4};
+ const ov::Shape small_shape{2, 4};
+ const ov::Shape run_shape{4, 4};
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, large_shape);
+ auto* caller_data = static_cast<float*>(usm_allocation.get());
+
+ request.set_output_tensor(ov::Tensor(ov::element::f32, large_shape, caller_data));
+ ov::Tensor large_input(ov::element::f32, large_shape);
+ std::fill_n(large_input.data<float>(), large_input.get_size(), 1.0f);
+ request.set_input_tensor(large_input);
+ OV_ASSERT_NO_THROW(request.infer());
+
+ request.set_output_tensor(ov::Tensor(ov::element::f32, small_shape, caller_data));
+ constexpr float sentinel = -19.0f;
+ std::fill_n(caller_data, ov::shape_size(large_shape), sentinel);
+
+ // The run exceeds the small view but fits the first binding's capacity; wait() then throws as the view can't grow.
+ ov::Tensor run_input(ov::element::f32, run_shape);
+ std::fill_n(run_input.data<float>(), run_input.get_size(), 1.0f);
+ request.set_input_tensor(run_input);
+ ASSERT_ANY_THROW(request.infer());
+
+ for (size_t i = ov::shape_size(small_shape); i < ov::shape_size(large_shape); ++i) {
+ ASSERT_FLOAT_EQ(caller_data[i], sentinel) << "write past the caller's view at element " << i;
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ TensorSmallerViewSamePointer,
+ ::testing::Values(ov::element::f32, ov::element::f16),
+ [](const ::testing::TestParamInfo<ov::element::Type>& info) { return info.param.get_type_name(); });
+
+// Rebinding to a different caller USM-host allocation writes the new buffer, leaves the old untouched.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostRebindsAllocation) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+ // Large enough that an extra plugin-owned output buffer stands out in tracked memory.
+ const ov::Shape shape{262144, 4};
+
+ auto first_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto second_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ ov::Tensor input_tensor(ov::element::f32, shape);
+
+ std::fill_n(input_tensor.data<float>(), input_tensor.get_size(), 1.0f);
+ request.set_input_tensor(input_tensor);
+ request.set_output_tensor(ov::Tensor(ov::element::f32, shape, first_allocation.get()));
+ OV_ASSERT_NO_THROW(request.infer());
+
+ constexpr float sentinel = -23.0f;
+ std::fill_n(static_cast<float*>(first_allocation.get()), ov::shape_size(shape), sentinel);
+ std::fill_n(input_tensor.data<float>(), input_tensor.get_size(), 2.0f);
+ request.set_output_tensor(ov::Tensor(ov::element::f32, shape, second_allocation.get()));
+ const int64_t before_rebind = gpu_mem_in_use(core);
+ OV_ASSERT_NO_THROW(request.infer());
+ expect_no_extra_output_buffer(gpu_mem_in_use(core) - before_rebind, 0, f32_bytes(shape));
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.data(), second_allocation.get());
+ const auto* first_data = static_cast<const float*>(first_allocation.get());
+ const auto* second_data = static_cast<const float*>(second_allocation.get());
+ for (size_t i = 0; i < ov::shape_size(shape); ++i) {
+ ASSERT_FLOAT_EQ(first_data[i], sentinel);
+ ASSERT_FLOAT_EQ(second_data[i], 2.0f);
+ }
+}
+
+// Switching from an imported caller USM-host output to ordinary host memory must stop using the
+// previous USM allocation and fall back to a plugin-owned output followed by a host copy.
+TEST(TensorTest, smoke_dynamicOutputSwitchesFromUsmHostToCopyFallback) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model = core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+ // Large enough that the plugin-owned fallback allocation stands out in memory statistics.
+ const ov::Shape shape{262144, 4};
+
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ ov::Tensor input_tensor(ov::element::f32, shape);
+ std::fill_n(input_tensor.data<float>(), input_tensor.get_size(), 1.0f);
+ request.set_input_tensor(input_tensor);
+ request.set_output_tensor(ov::Tensor(ov::element::f32, shape, usm_allocation.get()));
+ OV_ASSERT_NO_THROW(request.infer());
+
+ constexpr float sentinel = -31.0f;
+ std::fill_n(static_cast<float*>(usm_allocation.get()), ov::shape_size(shape), sentinel);
+ std::vector<float> host_output(ov::shape_size(shape), sentinel);
+ std::fill_n(input_tensor.data<float>(), input_tensor.get_size(), 3.0f);
+ request.set_output_tensor(ov::Tensor(ov::element::f32, shape, host_output.data()));
+
+ const int64_t before_switch = gpu_mem_in_use(core);
+ OV_ASSERT_NO_THROW(request.infer());
+ expect_extra_output_buffer(gpu_mem_in_use(core) - before_switch, 0, f32_bytes(shape));
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.data(), host_output.data());
+ const auto* usm_data = static_cast<const float*>(usm_allocation.get());
+ for (size_t i = 0; i < ov::shape_size(shape); ++i) {
+ ASSERT_FLOAT_EQ(usm_data[i], sentinel);
+ ASSERT_FLOAT_EQ(host_output[i], 3.0f);
+ }
+}
+
+// Requests on one stream share a network; a caller buffer bound by one must not receive another's output.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostNotUsedByOtherRequest) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model =
+ core.compile_model(makeDynamicReluModel(), core.get_default_context(ov::test::utils::DEVICE_GPU), ov::num_streams(1));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ const ov::Shape shape{16, 4};
+ const size_t size = ov::shape_size(shape);
+
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto* caller_data = static_cast<float*>(usm_allocation.get());
+ auto caller_request = compiled_model.create_infer_request();
+ ov::Tensor caller_input(ov::element::f32, shape);
+ std::fill_n(caller_input.data<float>(), size, 1.0f);
+ caller_request.set_input_tensor(caller_input);
+ caller_request.set_output_tensor(ov::Tensor(ov::element::f32, shape, caller_data));
+
+ // false: plugin-owned output; true: caller host memory that is copied out rather than imported.
+ for (const bool host_output : {false, true}) {
+ auto other_request = compiled_model.create_infer_request();
+ ov::Tensor other_input(ov::element::f32, shape);
+ other_request.set_input_tensor(other_input);
+ std::vector<float> host_buffer(size);
+ if (host_output) {
+ other_request.set_output_tensor(ov::Tensor(ov::element::f32, shape, host_buffer.data()));
+ }
+
+ // Unchanged shapes, so nothing but the binding itself can redirect the writer.
+ for (const float value : {2.0f, 3.0f}) {
+ OV_ASSERT_NO_THROW(caller_request.infer());
+ for (size_t i = 0; i < size; ++i) {
+ ASSERT_FLOAT_EQ(caller_data[i], 1.0f) << "host_output=" << host_output << " index=" << i;
+ }
+
+ constexpr float sentinel = -41.0f;
+ std::fill_n(caller_data, size, sentinel);
+ std::fill_n(other_input.data<float>(), size, value);
+ OV_ASSERT_NO_THROW(other_request.infer());
+
+ auto actual = other_request.get_output_tensor();
+ ASSERT_EQ(actual.get_size(), size);
+ for (size_t i = 0; i < size; ++i) {
+ ASSERT_FLOAT_EQ(actual.data<const float>()[i], value) << "host_output=" << host_output << " index=" << i;
+ ASSERT_FLOAT_EQ(caller_data[i], sentinel) << "host_output=" << host_output << " index=" << i;
+ }
+ }
+ }
+}
+
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostRebindsAcrossRequests) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto compiled_model = core.compile_model(makeDynamicReluModel(),
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::num_streams(1),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ const ov::Shape shape{16, 4};
+ const size_t size = ov::shape_size(shape);
+ auto first_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto second_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto* first_data = static_cast<float*>(first_allocation.get());
+ auto* second_data = static_cast<float*>(second_allocation.get());
+
+ auto first_request = compiled_model.create_infer_request();
+ auto second_request = compiled_model.create_infer_request();
+ ov::Tensor first_input(ov::element::f32, shape);
+ ov::Tensor second_input(ov::element::f32, shape);
+ std::fill_n(first_input.data<float>(), size, 1.0f);
+ std::fill_n(second_input.data<float>(), size, 2.0f);
+ first_request.set_input_tensor(first_input);
+ second_request.set_input_tensor(second_input);
+ first_request.set_output_tensor(ov::Tensor(ov::element::f32, shape, first_data));
+ second_request.set_output_tensor(ov::Tensor(ov::element::f32, shape, second_data));
+
+ constexpr float sentinel = -41.0f;
+ for (int iter = 0; iter < 2; ++iter) {
+ std::fill_n(first_data, size, sentinel);
+ std::fill_n(second_data, size, sentinel);
+ OV_ASSERT_NO_THROW(first_request.infer());
+ for (size_t i = 0; i < size; ++i) {
+ ASSERT_FLOAT_EQ(first_data[i], 1.0f) << "iteration=" << iter << " index=" << i;
+ ASSERT_FLOAT_EQ(second_data[i], sentinel) << "iteration=" << iter << " index=" << i;
+ }
+
+ std::fill_n(first_data, size, sentinel);
+ OV_ASSERT_NO_THROW(second_request.infer());
+ for (size_t i = 0; i < size; ++i) {
+ ASSERT_FLOAT_EQ(second_data[i], 2.0f) << "iteration=" << iter << " index=" << i;
+ ASSERT_FLOAT_EQ(first_data[i], sentinel) << "iteration=" << iter << " index=" << i;
+ }
+ }
+}
+
+// One caller buffer as dynamic input/output must reject zero-copy: tiled MatMul may overwrite unread input.
+// Verify fallback uses a private output and copy-out, preserving input until the kernel finishes reading.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostInputOutputAliasIsSafe) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ // K must be large enough to force tiled MatMul execution so reads/writes to the same
+ // buffer interleave; square weights let the output be fed back as input.
+ constexpr size_t K = 1024;
+ const ov::Shape shape{2, K};
+
+ // Known weights so the reference can be computed by hand.
+ std::vector<float> weights_data;
+ auto model = makeDynamicMatMulModel(K, weights_data);
+
+ // Use f32 so input reaches MatMul directly; default f16 inserts Convert/reorder buffers that hide aliasing.
+ // This keeps the test exercising the intended in-place input/output case.
+ auto compiled_model = core.compile_model(model, core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ // Single USM-host allocation used as BOTH input and output (the aliasing pattern).
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto* buffer = static_cast<float*>(usm_allocation.get());
+ std::vector<float> input_values(ov::shape_size(shape));
+ for (size_t i = 0; i < input_values.size(); ++i) {
+ input_values[i] = static_cast<float>((i % 5)) - 2.0f;
+ }
+
+ const auto expected = reference_matmul(shape, K, input_values, weights_data);
+
+ ov::Tensor aliased(ov::element::f32, shape, usm_allocation.get());
+ request.set_input_tensor(aliased);
+ request.set_output_tensor(aliased);
+
+ // In-place aliasing corruption is a nondeterministic GPU data race: with the fix every run is
+ // correct, without it a run is expected to diverge. Repeat so a regression is caught reliably.
+ constexpr int kIterations = 16;
+ for (int iter = 0; iter < kIterations; ++iter) {
+ std::copy(input_values.begin(), input_values.end(), buffer); // a prior corrupted run may have overwritten the input
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.get_size(), expected.size());
+ const auto* actual_data = actual.data<const float>();
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_NEAR(actual_data[i], expected[i], 1e-2f)
+ << "aliased input/output corrupted at element " << i << " on iteration " << iter;
+ }
+ }
+}
+
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostRemoteInputAliasIsSafe) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ constexpr size_t K = 1024;
+ const ov::Shape shape{2, K};
+ std::vector<float> weights_data;
+ auto model = makeDynamicMatMulModel(K, weights_data);
+ auto compiled_model = core.compile_model(model,
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ auto remote_input = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto* buffer = static_cast<float*>(remote_input.get());
+ std::vector<float> input_values(ov::shape_size(shape));
+ for (size_t i = 0; i < input_values.size(); ++i) {
+ input_values[i] = static_cast<float>((i % 5)) - 2.0f;
+ }
+ const auto expected = reference_matmul(shape, K, input_values, weights_data);
+
+ ov::Tensor output_wrapper(ov::element::f32, shape, remote_input.get());
+ request.set_input_tensor(remote_input);
+ request.set_output_tensor(output_wrapper);
+
+ constexpr int kIterations = 16;
+ for (int iter = 0; iter < kIterations; ++iter) {
+ std::copy(input_values.begin(), input_values.end(), buffer);
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.get_size(), expected.size());
+ const auto* actual_data = actual.data<const float>();
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_NEAR(actual_data[i], expected[i], 1e-2f)
+ << "remote aliased input/output corrupted at element " << i << " on iteration " << iter;
+ }
+ }
+}
+
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostPartialInputAliasFallsBack) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ constexpr size_t K = 1024;
+ const ov::Shape shape{2, K};
+ std::vector<float> weights_data;
+ auto model = makeDynamicMatMulModel(K, weights_data);
+ auto compiled_model = core.compile_model(model,
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, ov::Shape{shape[0], shape[1] + 1});
+ auto* usm_data = static_cast<float*>(usm_allocation.get());
+ auto output_ptr = usm_data + 1;
+ ov::Tensor input_tensor(ov::element::f32, shape, usm_data);
+ ov::Tensor output_tensor(ov::element::f32, shape, output_ptr);
+
+ std::vector<float> input_values(ov::shape_size(shape));
+ for (size_t i = 0; i < input_values.size(); ++i) {
+ input_values[i] = static_cast<float>((i % 5)) - 2.0f;
+ }
+ const auto expected = reference_matmul(shape, K, input_values, weights_data);
+
+ request.set_input_tensor(input_tensor);
+ request.set_output_tensor(output_tensor);
+
+ constexpr int kIterations = 16;
+ for (int iter = 0; iter < kIterations; ++iter) {
+ std::copy(input_values.begin(), input_values.end(), usm_data);
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.data(), output_ptr);
+ ASSERT_EQ(actual.get_size(), expected.size());
+ const auto* actual_data = actual.data<const float>();
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_NEAR(actual_data[i], expected[i], 1e-2f)
+ << "partially aliased input/output corrupted at element " << i << " on iteration " << iter;
+ }
+ }
+}
+
+// Check caller-buffer capacity, not the possibly shrunk logical shape, so growth detects tail aliases.
+// Bind large -> shrink -> park input in tail -> grow; fallback must preserve the aliased input.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostShrinkThenGrowTailAliasIsSafe) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ constexpr size_t K = 1024;
+ constexpr size_t capacity_rows = 4;
+ std::vector<float> weights_data;
+ auto model = makeDynamicMatMulModel(K, weights_data);
+ auto compiled_model = core.compile_model(model,
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ // One allocation of capacity_rows x K; the output view starts at row 0, the aliasing input at row 1.
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, ov::Shape{capacity_rows, K});
+ auto* usm_data = static_cast<float*>(usm_allocation.get());
+
+ // Bind the output at full capacity first so its recorded actual_size is capacity_rows x K.
+ ov::Tensor output_tensor(ov::element::f32, ov::Shape{capacity_rows, K}, usm_data);
+ request.set_output_tensor(output_tensor);
+
+ // Warm-up at capacity, then shrink the output to a single row via a 1-row inference.
+ {
+ ov::Tensor warm_input(ov::element::f32, ov::Shape{capacity_rows, K});
+ std::fill_n(warm_input.data<float>(), warm_input.get_size(), 1.0f);
+ request.set_input_tensor(warm_input);
+ OV_ASSERT_NO_THROW(request.infer());
+
+ ov::Tensor shrink_input(ov::element::f32, ov::Shape{1, K});
+ std::fill_n(shrink_input.data<float>(), shrink_input.get_size(), 1.0f);
+ request.set_input_tensor(shrink_input);
+ OV_ASSERT_NO_THROW(request.infer()); // wait() shrinks the output tensor to {1, K}
+ }
+
+ // Park a 2-row input in the tail (rows 1..3): disjoint from the shrunk 1-row output span, but the
+ // output grows to 2 rows during execution and overwrites row 1 unless the guard uses capacity.
+ const ov::Shape grow_shape{2, K};
+ auto* input_ptr = usm_data + K; // row 1
+ ov::Tensor tail_input(ov::element::f32, grow_shape, input_ptr);
+ request.set_input_tensor(tail_input);
+
+ std::vector<float> input_values(ov::shape_size(grow_shape));
+ for (size_t i = 0; i < input_values.size(); ++i) {
+ input_values[i] = static_cast<float>((i % 5)) - 2.0f;
+ }
+ const auto expected = reference_matmul(grow_shape, K, input_values, weights_data);
+
+ constexpr int kIterations = 16;
+ for (int iter = 0; iter < kIterations; ++iter) {
+ std::copy(input_values.begin(), input_values.end(), input_ptr);
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.data(), usm_data);
+ ASSERT_EQ(actual.get_size(), expected.size());
+ const auto* actual_data = actual.data<const float>();
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_NEAR(actual_data[i], expected[i], 1e-2f)
+ << "tail-aliased input corrupted after shrink-then-grow at element " << i << " on iteration " << iter;
+ }
+ }
+}
+
+// The output may reuse an input's buffer once that input has no reader left (Relu runs before Add writes).
+// Whether zero-copy is granted depends on graph fusions, so only correctness is asserted.
+TEST(TensorTest, smoke_dynamicOutputCallerOwnedUsmHostReusesDeadInputBuffer) {
+ auto core = ov::Core();
+ if (!gpu_supports_usm_host_output_sharing(core)) {
+ GTEST_SKIP() << "Caller-owned USM-host output sharing requires an iGPU with USM support";
+ }
+
+ auto in0 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 4});
+ auto in1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 4});
+ auto relu = std::make_shared<ov::op::v0::Relu>(in0);
+ auto add = std::make_shared<ov::op::v1::Add>(relu, in1);
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{add}, ov::ParameterVector{in0, in1});
+ auto compiled_model = core.compile_model(model,
+ core.get_default_context(ov::test::utils::DEVICE_GPU),
+ ov::hint::inference_precision(ov::element::f32));
+ auto gpu_context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>();
+ auto request = compiled_model.create_infer_request();
+
+ const ov::Shape shape{2, 4};
+ auto usm_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, shape);
+ auto* buffer = static_cast<float*>(usm_allocation.get());
+ ov::Tensor in0_tensor(ov::element::f32, shape, buffer);
+ ov::Tensor output_tensor(ov::element::f32, shape, buffer);
+ ov::Tensor in1_tensor(ov::element::f32, shape);
+ request.set_input_tensor(0, in0_tensor);
+ request.set_input_tensor(1, in1_tensor);
+ request.set_output_tensor(output_tensor);
+
+ std::vector<float> expected(ov::shape_size(shape));
+ for (int iter = 0; iter < 4; ++iter) {
+ auto* in1_data = in1_tensor.data<float>();
+ for (size_t i = 0; i < expected.size(); ++i) {
+ const float in = relu_test_input(i) + static_cast<float>(iter);
+ buffer[i] = in;
+ in1_data[i] = static_cast<float>(i) * 0.5f;
+ expected[i] = (in > 0.0f ? in : 0.0f) + in1_data[i];
+ }
+
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor();
+ ASSERT_EQ(actual.data(), buffer);
+ ASSERT_EQ(actual.get_size(), expected.size());
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ ASSERT_FLOAT_EQ(actual.data<const float>()[i], expected[i]) << "element " << i << " on iteration " << iter;
+ }
+ }
+}
+
// 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;
+TEST(TensorTest, smoke_lazyAllocAutoBatchUsesBatchedShapeNotSlotShape) { constexpr int kBatch = 4;
ov::Shape shape;
auto model = makeStaticInputModel(shape);
diff --git a/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp b/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
index 010d6b5b804..229e6e7a38f 100644
--- a/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
@@ -4,6 +4,18 @@
#include "test_utils.h"
+#include "intel_gpu/op/stateless_kv.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/runtime/core.hpp"
+#include "openvino/runtime/intel_gpu/ocl/ocl.hpp"
+#include "openvino/runtime/intel_gpu/properties.hpp"
+
+#include <algorithm>
+#include <numeric>
+
+#include <intel_gpu/primitives/eltwise.hpp>
#include <intel_gpu/primitives/input_layout.hpp>
#include <intel_gpu/primitives/stateless_kv.hpp>
#include <intel_gpu/primitives/reorder.hpp>
@@ -23,6 +35,39 @@ struct stateless_kv_runtime_params {
class stateless_kv_runtime : public testing::TestWithParam<stateless_kv_runtime_params> {};
+namespace {
+
+topology make_stateless_kv_topology(const layout& new_token_layout, data_types result_type = data_types::f32) {
+ auto kv = stateless_kv("stateless_kv", {input_info("past"), input_info("new_token"), input_info("present_len")}, 2, true);
+ kv.num_outputs = 2;
+ kv.output_data_types = {data_types::f32, data_types::f32};
+ return topology(input_layout("past", layout{ov::PartialShape{1, 2, -1, 4}, data_types::f32, format::bfyx}),
+ input_layout("new_token", new_token_layout),
+ input_layout("present_len", layout{ov::PartialShape{1}, data_types::i64, format::bfyx}),
+ kv,
+ reorder("result", input_info("stateless_kv", 0), format::bfyx, result_type));
+}
+
+std::vector<float> expected_concatenated_cache(const std::vector<float>& past_values, const std::vector<float>& token_values,
+ const ov::Shape& past_shape, size_t output_capacity, size_t logical_past_len) {
+ const size_t planes = past_shape[0] * past_shape[1];
+ const size_t past_capacity = past_shape[2];
+ const size_t head_size = past_shape[3];
+ const size_t token_len = token_values.size() / (planes * head_size);
+ std::vector<float> expected(planes * output_capacity * head_size);
+ for (size_t plane = 0; plane < planes; ++plane) {
+ std::copy_n(past_values.begin() + plane * past_capacity * head_size,
+ past_capacity * head_size,
+ expected.begin() + plane * output_capacity * head_size);
+ std::copy_n(token_values.begin() + plane * token_len * head_size,
+ token_len * head_size,
+ expected.begin() + (plane * output_capacity + logical_past_len) * head_size);
+ }
+ return expected;
+}
+
+} // namespace
+
TEST_P(stateless_kv_runtime, output_memory_reuse) {
const auto& params = GetParam();
auto& engine = get_test_engine();
@@ -87,16 +132,7 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
std::iota(pos_idx_values.begin(), pos_idx_values.end(), static_cast<int32_t>(logical_past_len));
set_values(pos_idx, pos_idx_values);
- std::vector<float> expected(static_cast<size_t>(batch * heads * output_capacity * head_size));
- for (int64_t head = 0; head < heads; ++head) {
- const auto past_head_offset = head * past_capacity * head_size;
- const auto output_head_offset = head * output_capacity * head_size;
- const auto token_head_offset = head * params.new_token_len * head_size;
- std::copy_n(past_values.begin() + past_head_offset, past_capacity * head_size, expected.begin() + output_head_offset);
- std::copy_n(new_token_values.begin() + token_head_offset,
- params.new_token_len * head_size,
- expected.begin() + output_head_offset + logical_past_len * head_size);
- }
+ const auto expected = expected_concatenated_cache(past_values, new_token_values, past_layout.get_shape(), output_capacity, logical_past_len);
network.set_input_data("past", past);
network.set_input_data("new_token", new_token);
@@ -165,21 +201,13 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
const auto new_token_layout = layout{ov::PartialShape{batch, heads, new_token_len, head_size}, data_types::f32, format::bfyx};
const auto seq_len_layout = layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
- auto stateless_kv_prim = stateless_kv("stateless_kv", {input_info("past"), input_info("new_token"), input_info("present_len")}, 2, true);
- stateless_kv_prim.num_outputs = 2;
- stateless_kv_prim.output_data_types = {data_types::f32, data_types::f32};
-
- topology topology(input_layout("past", layout{ov::PartialShape{1, 2, -1, 4}, data_types::f32, format::bfyx}),
- input_layout("new_token", new_token_layout),
- input_layout("present_len", seq_len_layout),
- stateless_kv_prim,
- reorder("result", input_info("stateless_kv", 0), format::bfyx, data_types::f32));
+ auto topo = make_stateless_kv_topology(new_token_layout);
ExecutionConfig config = get_test_default_config(engine);
config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
config.set_property(ov::intel_gpu::optimize_data(true));
- network network(engine, topology, config);
+ network network(engine, topo, config);
auto current_past = engine.allocate_memory(initial_past_layout);
auto new_token = engine.allocate_memory(new_token_layout);
auto seq_len = engine.allocate_memory(seq_len_layout);
@@ -201,16 +229,8 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
set_values(new_token, new_token_values);
set_values<int64_t>(seq_len, {present_len});
- std::vector<float> expected(static_cast<size_t>(batch * heads * output_capacity * head_size));
- for (int64_t head = 0; head < heads; ++head) {
- const auto past_head_offset = head * current_capacity * head_size;
- const auto output_head_offset = head * output_capacity * head_size;
- const auto token_head_offset = head * new_token_len * head_size;
- std::copy_n(current_values.begin() + past_head_offset, current_capacity * head_size, expected.begin() + output_head_offset);
- std::copy_n(new_token_values.begin() + token_head_offset,
- new_token_len * head_size,
- expected.begin() + output_head_offset + logical_past_len * head_size);
- }
+ auto expected = expected_concatenated_cache(current_values, new_token_values, current_past->get_layout().get_shape(),
+ output_capacity, logical_past_len);
network.set_input_data("past", current_past);
network.set_input_data("new_token", new_token);
@@ -247,6 +267,399 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
run_and_verify(17, 3000.0f, true);
run_and_verify(20, 4000.0f, false);
}
+
+TEST(stateless_kv_runtime, caller_output_binding_respects_inplace_contract) {
+ auto& engine = get_test_engine();
+ const layout past_layout{ov::Shape{1, 2, 16, 4}, data_types::f32, format::bfyx};
+ const layout token_layout{ov::Shape{1, 2, 1, 4}, data_types::f32, format::bfyx};
+ const layout seq_len_layout{ov::Shape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(token_layout);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ // network::may_alias() always rejects on out-of-order queues.
+ config.set_property(ov::intel_gpu::queue_type(QueueTypes::in_order));
+ network net(engine, topo, config);
+
+ auto past = engine.allocate_memory(past_layout, allocation_type::usm_host);
+ auto token = engine.allocate_memory(token_layout, allocation_type::usm_host);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ std::vector<float> expected(past_layout.count(), 1.0f);
+ set_values(past, expected);
+ set_values(token, std::vector<float>(token_layout.count(), 3.0f));
+ set_values<int64_t>(seq_len, {5});
+ net.set_input_data("past", past);
+ net.set_input_data("new_token", token);
+ net.set_input_data("present_len", seq_len);
+
+ EXPECT_TRUE(net.may_alias("result", "past"));
+ EXPECT_FALSE(net.may_alias("result", "new_token"));
+
+ net.set_output_memory("result", past, true);
+ auto outputs = net.execute();
+ auto result = outputs.at("result").get_memory();
+ auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+ ASSERT_NE(result, nullptr);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_TRUE(engine.is_the_same_buffer(*result, *past));
+ EXPECT_TRUE(engine.is_the_same_buffer(*kv_output, *past));
+
+ for (size_t head = 0; head < 2; ++head)
+ std::fill_n(expected.begin() + head * 16 * 4 + 4 * 4, 4, 3.0f);
+ mem_lock<float, mem_lock_type::read> actual(past, get_test_stream());
+ EXPECT_THAT(std::vector<float>(actual.begin(), actual.begin() + expected.size()), testing::ElementsAreArray(expected));
+}
+
+// A reader of past scheduled after stateless_kv restricts it from sharing past's buffer, so a Result bound
+// to past (bypassing network::may_alias()) must not make stateless_kv update past in place.
+TEST(stateless_kv_runtime, restricted_past_forces_private_present) {
+ auto& engine = get_test_engine();
+ const layout past_layout{ov::Shape{1, 2, 16, 4}, data_types::f32, format::bfyx};
+ const layout token_layout{ov::Shape{1, 2, 1, 4}, data_types::f32, format::bfyx};
+ const layout seq_len_layout{ov::Shape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(token_layout);
+ // Reading output 1 orders this reader of past after stateless_kv.
+ topo.add(eltwise("late_reader", input_info("past"), input_info("stateless_kv", 1), eltwise_mode::sum));
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::queue_type(QueueTypes::in_order));
+ network net(engine, topo, config);
+
+ auto past = engine.allocate_memory(past_layout, allocation_type::usm_host);
+ auto token = engine.allocate_memory(token_layout);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ set_values(past, std::vector<float>(past_layout.count(), 1.0f));
+ set_values(token, std::vector<float>(token_layout.count(), 3.0f));
+ // Full capacity keeps output 1 the same shape as past for the eltwise.
+ set_values<int64_t>(seq_len, {16});
+ net.set_input_data("past", past);
+ net.set_input_data("new_token", token);
+ net.set_input_data("present_len", seq_len);
+ EXPECT_FALSE(net.may_alias("result", "past"));
+
+ net.set_output_memory("result", past, true);
+ net.execute();
+ auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_FALSE(engine.is_the_same_buffer(*kv_output, *past));
+}
+
+// Growing present over a caller buffer that also backs past changes the head pitch, so stateless_kv must not
+// update in place: it computes into its own buffer and result copies that into the caller buffer.
+TEST(stateless_kv_runtime, concat_growth_with_aliased_caller_buffer) {
+ auto& engine = get_test_engine();
+
+ constexpr int64_t heads = 2;
+ constexpr int64_t head_size = 4;
+ constexpr int64_t past_capacity = 16;
+ constexpr int64_t new_token_len = 2;
+ constexpr int64_t present_len = past_capacity + new_token_len;
+ const layout past_layout{ov::PartialShape{1, heads, past_capacity, head_size}, data_types::f32, format::bfyx};
+ const layout present_layout{ov::PartialShape{1, heads, present_len, head_size}, data_types::f32, format::bfyx};
+ const layout token_layout{ov::PartialShape{1, heads, new_token_len, head_size}, data_types::f32, format::bfyx};
+ const layout seq_len_layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(token_layout);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ network net(engine, topo, config);
+
+ auto caller_buffer = engine.allocate_memory(present_layout, allocation_type::usm_host);
+ auto past = engine.reinterpret_buffer(*caller_buffer, past_layout);
+ auto new_token = engine.allocate_memory(token_layout);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ std::vector<float> past_values(past_layout.count());
+ std::iota(past_values.begin(), past_values.end(), 0.0f);
+ std::vector<float> token_values(token_layout.count());
+ std::iota(token_values.begin(), token_values.end(), 1000.0f);
+ set_values(past, past_values);
+ set_values(new_token, token_values);
+ set_values<int64_t>(seq_len, {present_len});
+
+ const auto expected = expected_concatenated_cache(past_values, token_values, past_layout.get_shape(), present_len, past_capacity);
+
+ net.set_input_data("past", past);
+ net.set_input_data("new_token", new_token);
+ net.set_input_data("present_len", seq_len);
+ net.set_output_memory("result", caller_buffer, true);
+
+ auto outputs = net.execute();
+ auto result = outputs.at("result").get_memory();
+ auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+ ASSERT_NE(result, nullptr);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_TRUE(engine.is_the_same_buffer(*result, *caller_buffer));
+ EXPECT_FALSE(engine.is_the_same_buffer(*kv_output, *caller_buffer));
+
+ mem_lock<float, mem_lock_type::read> actual(caller_buffer, get_test_stream());
+ EXPECT_THAT(std::vector<float>(actual.begin(), actual.begin() + expected.size()), testing::ElementsAreArray(expected));
+}
+
+// stateless_kv must not write f32 present into the f16 buffer of a converting Result.
+TEST(stateless_kv_runtime, converting_result_does_not_share_present_buffer) {
+ auto& engine = get_test_engine();
+
+ constexpr int64_t heads = 2;
+ constexpr int64_t capacity = 16;
+ constexpr int64_t head_size = 4;
+ constexpr int64_t present_len = 5;
+ const layout past_layout{ov::PartialShape{1, heads, capacity, head_size}, data_types::f32, format::bfyx};
+ const layout token_layout{ov::PartialShape{1, heads, 1, head_size}, data_types::f32, format::bfyx};
+ const layout seq_len_layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(token_layout, data_types::f16);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ network net(engine, topo, config);
+
+ auto past = engine.allocate_memory(past_layout);
+ auto new_token = engine.allocate_memory(token_layout);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ std::vector<float> past_values(past_layout.count());
+ std::iota(past_values.begin(), past_values.end(), 0.0f);
+ set_values(past, past_values);
+ set_values(new_token, std::vector<float>(token_layout.count(), 1000.0f));
+ set_values<int64_t>(seq_len, {present_len});
+
+ auto expected = past_values;
+ for (int64_t head = 0; head < heads; ++head)
+ std::fill_n(expected.begin() + (head * capacity + present_len - 1) * head_size, head_size, 1000.0f);
+
+ net.set_input_data("past", past);
+ net.set_input_data("new_token", new_token);
+ net.set_input_data("present_len", seq_len);
+
+ auto outputs = net.execute();
+ auto result = outputs.at("result").get_memory();
+ auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+ ASSERT_NE(result, nullptr);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_FALSE(engine.is_the_same_buffer(*kv_output, *result));
+
+ mem_lock<ov::float16, mem_lock_type::read> actual(result, get_test_stream());
+ for (int64_t head = 0; head < heads; ++head) {
+ for (int64_t i = 0; i < present_len * head_size; ++i) {
+ const auto offset = static_cast<size_t>(head * capacity * head_size + i);
+ ASSERT_FLOAT_EQ(static_cast<float>(actual[offset]), expected[offset]) << "index=" << offset;
+ }
+ }
+}
+
+// The private present buffer of a converting Result is kept across executions while it is large enough.
+TEST(stateless_kv_runtime, converting_result_reuses_private_present_buffer) {
+ auto& engine = get_test_engine();
+
+ constexpr int64_t heads = 2;
+ constexpr int64_t head_size = 4;
+ const layout token_layout{ov::PartialShape{1, heads, 1, head_size}, data_types::f32, format::bfyx};
+ const layout seq_len_layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(token_layout, data_types::f16);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ network net(engine, topo, config);
+
+ auto new_token = engine.allocate_memory(token_layout);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ net.set_input_data("new_token", new_token);
+ net.set_input_data("present_len", seq_len);
+
+ auto run = [&](int64_t capacity, int64_t present_len) -> memory::ptr {
+ const layout past_layout{ov::PartialShape{1, heads, capacity, head_size}, data_types::f32, format::bfyx};
+ auto past = engine.allocate_memory(past_layout);
+ std::vector<float> past_values(past_layout.count());
+ std::iota(past_values.begin(), past_values.end(), 0.0f);
+ set_values(past, past_values);
+ const float token_value = 1000.0f + static_cast<float>(present_len);
+ set_values(new_token, std::vector<float>(token_layout.count(), token_value));
+ set_values<int64_t>(seq_len, {present_len});
+ net.set_input_data("past", past);
+
+ auto outputs = net.execute();
+ auto result = outputs.at("result").get_memory();
+ auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+ EXPECT_NE(result, nullptr);
+ EXPECT_NE(kv_output, nullptr);
+ if (!result || !kv_output)
+ return nullptr;
+ EXPECT_FALSE(engine.is_the_same_buffer(*kv_output, *result));
+
+ auto expected = past_values;
+ for (int64_t head = 0; head < heads; ++head)
+ std::fill_n(expected.begin() + (head * capacity + present_len - 1) * head_size, head_size, token_value);
+ mem_lock<ov::float16, mem_lock_type::read> actual(result, get_test_stream());
+ for (int64_t head = 0; head < heads; ++head) {
+ for (int64_t i = 0; i < present_len * head_size; ++i) {
+ const auto offset = static_cast<size_t>(head * capacity * head_size + i);
+ EXPECT_FLOAT_EQ(static_cast<float>(actual[offset]), expected[offset])
+ << "capacity=" << capacity << " present_len=" << present_len << " index=" << offset;
+ }
+ }
+ return kv_output;
+ };
+
+ auto first = run(16, 5);
+ ASSERT_NE(first, nullptr);
+ for (int64_t present_len : {6, 7}) {
+ auto kv_output = run(16, present_len);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_TRUE(engine.is_the_same_buffer(*kv_output, *first)) << "present_len=" << present_len;
+ }
+
+ // A larger cache needs a larger buffer; shrinking back must keep using it.
+ auto grown = run(32, 20);
+ ASSERT_NE(grown, nullptr);
+ auto shrunk = run(16, 8);
+ ASSERT_NE(shrunk, nullptr);
+ EXPECT_TRUE(engine.is_the_same_buffer(*shrunk, *grown));
+}
+
+namespace {
+
+bool gpu_supports_usm(ov::Core& core) {
+ const auto caps = core.get_property("GPU", ov::device::capabilities);
+ return std::find(caps.begin(), caps.end(), ov::intel_gpu::capability::USM_MEMORY) != caps.end();
+}
+
+// Output 0 is present; with_past_reader adds output 1 = past * 2, a second reader of past.
+std::shared_ptr<ov::Model> make_stateless_kv_model(size_t new_token_len, bool with_past_reader = false) {
+ auto past = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 2, -1, 4});
+ auto token = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 2, new_token_len, 4});
+ auto present_len = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
+ auto kv = std::make_shared<ov::intel_gpu::op::StatelessKV>(past, token, present_len, 2, true);
+ ov::OutputVector outputs{kv->output(0)};
+ if (with_past_reader) {
+ auto scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {2.0f});
+ outputs.push_back(std::make_shared<ov::op::v1::Multiply>(past, scale));
+ }
+ return std::make_shared<ov::Model>(outputs, ov::ParameterVector{past, token, present_len});
+}
+
+} // namespace
+
+class stateless_kv_caller_host_output : public testing::TestWithParam<bool> {};
+
+// The caller output shares past's USM-host allocation, whether past is a remote or plain host tensor.
+TEST_P(stateless_kv_caller_host_output, repeated_inference) {
+ ov::Core core;
+ if (!gpu_supports_usm(core)) {
+ GTEST_SKIP() << "USM is not supported";
+ }
+
+ auto context = core.get_default_context("GPU");
+ auto compiled_model = core.compile_model(make_stateless_kv_model(1), context, ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled_model.create_infer_request();
+
+ const ov::Shape cache_shape{1, 2, 16, 4};
+ auto gpu_context = context.as<ov::intel_gpu::ocl::ClContext>();
+ auto cache_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, cache_shape);
+ auto* cache = static_cast<float*>(cache_allocation.get());
+ ov::Tensor past_tensor(ov::element::f32, cache_shape, cache);
+ ov::Tensor present_tensor(ov::element::f32, cache_shape, cache);
+ ov::Tensor token_tensor(ov::element::f32, {1, 2, 1, 4});
+ ov::Tensor length_tensor(ov::element::i64, {1});
+ std::vector<float> expected(ov::shape_size(cache_shape), 1.0f);
+ std::copy(expected.begin(), expected.end(), cache);
+ if (GetParam()) {
+ request.set_input_tensor(0, cache_allocation);
+ } else {
+ request.set_input_tensor(0, past_tensor);
+ }
+ request.set_input_tensor(1, token_tensor);
+ request.set_input_tensor(2, length_tensor);
+ request.set_output_tensor(0, present_tensor);
+
+ for (int64_t length : {5, 6, 7}) {
+ const float token_value = static_cast<float>(length);
+ std::fill_n(token_tensor.data<float>(), token_tensor.get_size(), token_value);
+ length_tensor.data<int64_t>()[0] = length;
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto actual = request.get_output_tensor(0);
+ ASSERT_FALSE(actual.is<ov::intel_gpu::ocl::USMTensor>());
+ ASSERT_EQ(actual.data(), cache);
+ ASSERT_EQ(actual.get_shape(), cache_shape);
+ for (size_t head = 0; head < 2; ++head)
+ std::fill_n(expected.begin() + head * 16 * 4 + static_cast<size_t>(length - 1) * 4, 4, token_value);
+ // Rows at or beyond present_len are undefined when the plugin falls back to a copy.
+ for (size_t head = 0; head < 2; ++head) {
+ for (size_t i = 0; i < static_cast<size_t>(length) * 4; ++i) {
+ const size_t offset = head * 16 * 4 + i;
+ ASSERT_FLOAT_EQ(actual.data<const float>()[offset], expected[offset]) << "length=" << length << " index=" << offset;
+ }
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ stateless_kv_caller_host_output,
+ testing::Bool(),
+ [](const testing::TestParamInfo<bool>& info) { return info.param ? "RemotePast" : "CallerHostPast"; });
+
+// Another reader of past must still see the original past, whether or not present is bound over it.
+TEST(stateless_kv_runtime, infer_request_aliased_past_with_another_reader) {
+ ov::Core core;
+ if (!gpu_supports_usm(core)) {
+ GTEST_SKIP() << "USM is not supported";
+ }
+
+ auto context = core.get_default_context("GPU");
+ auto compiled_model = core.compile_model(make_stateless_kv_model(1, true), context, ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled_model.create_infer_request();
+
+ const ov::Shape cache_shape{1, 2, 16, 4};
+ auto gpu_context = context.as<ov::intel_gpu::ocl::ClContext>();
+ auto cache_allocation = gpu_context.create_usm_host_tensor(ov::element::f32, cache_shape);
+ auto* cache = static_cast<float*>(cache_allocation.get());
+ ov::Tensor past_tensor(ov::element::f32, cache_shape, cache);
+ ov::Tensor present_tensor(ov::element::f32, cache_shape, cache);
+ ov::Tensor token_tensor(ov::element::f32, {1, 2, 1, 4});
+ ov::Tensor length_tensor(ov::element::i64, {1});
+ request.set_input_tensor(0, past_tensor);
+ request.set_input_tensor(1, token_tensor);
+ request.set_input_tensor(2, length_tensor);
+ request.set_output_tensor(0, present_tensor);
+
+ std::vector<float> original(ov::shape_size(cache_shape));
+ for (size_t i = 0; i < original.size(); ++i)
+ original[i] = static_cast<float>(i % 13 + 1);
+ constexpr int64_t length = 5;
+ constexpr float token_value = 100.0f;
+ std::fill_n(token_tensor.data<float>(), token_tensor.get_size(), token_value);
+ length_tensor.data<int64_t>()[0] = length;
+
+ auto expected_present = original;
+ for (size_t head = 0; head < 2; ++head)
+ std::fill_n(expected_present.begin() + head * 16 * 4 + static_cast<size_t>(length - 1) * 4, 4, token_value);
+
+ // An unsafe in-place update would race with the past reader, so repeat to catch it reliably.
+ for (int iter = 0; iter < 8; ++iter) {
+ std::copy(original.begin(), original.end(), cache);
+ OV_ASSERT_NO_THROW(request.infer());
+
+ auto present = request.get_output_tensor(0);
+ auto scaled_past = request.get_output_tensor(1);
+ ASSERT_EQ(present.data(), cache);
+ ASSERT_EQ(scaled_past.get_shape(), cache_shape);
+ // Rows at or beyond present_len are undefined when the plugin falls back to a copy.
+ for (size_t head = 0; head < 2; ++head) {
+ for (size_t i = 0; i < static_cast<size_t>(length) * 4; ++i) {
+ const size_t offset = head * 16 * 4 + i;
+ ASSERT_FLOAT_EQ(present.data<const float>()[offset], expected_present[offset]) << "iter=" << iter << " index=" << offset;
+ }
+ }
+ for (size_t i = 0; i < original.size(); ++i) {
+ ASSERT_FLOAT_EQ(scaled_past.data<const float>()[i], original[i] * 2.0f) << "iter=" << iter << " index=" << i;
+ }
+ }
+}
+
// Compressed KV caches (u8 also carries packed i4, f8e4m3) must have a stateless_kv implementation.
class stateless_kv_compressed_runtime : public testing::TestWithParam<data_types> {};
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
index 43bfded0245..515a122a52e 100644
--- 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
@@ -329,6 +329,41 @@ TEST_F(ZeroCopyOptimizedOutputTest, optimized_out_output_node) {
net->clear_output_memory_blocks();
}
+// -------------------------------------------------------------------
+// Alternating between a caller binding and the pool-backed copy path
+// (as two requests sharing the network do) must return the compute
+// node's pool memory each time instead of pinning a new record.
+// -------------------------------------------------------------------
+TEST_F(ZeroCopyOptimizedOutputTest, alternating_caller_binding_does_not_grow_pool) {
+ constexpr size_t M = 6;
+ auto caller_mem = engine.allocate_memory(
+ layout{ov::PartialShape{static_cast<int64_t>(M), static_cast<int64_t>(N)}, data_types::f16, format::bfyx},
+ allocation_type::usm_host);
+ const auto input_data = make_input(M);
+
+ auto run_copy_path = [&]() {
+ net->release_user_output_memory("output");
+ run_gemm(M, input_data);
+ };
+ auto run_caller_binding = [&]() {
+ net->set_output_memory("output", caller_mem, true);
+ run_gemm(M, input_data);
+ };
+
+ run_copy_path();
+ run_caller_binding();
+ run_copy_path();
+ const auto pool_size = net->get_memory_pool().get_non_padded_pool_size();
+ ASSERT_GT(pool_size, 0u) << "Precondition: the copy path allocates gemm output from the pool";
+
+ for (int round = 0; round < 3; ++round) {
+ SCOPED_TRACE("round = " + std::to_string(round));
+ run_caller_binding();
+ run_copy_path();
+ ASSERT_EQ(net->get_memory_pool().get_non_padded_pool_size(), pool_size);
+ }
+}
+
// ===================================================================
// Multi-user output fixture: gemm feeds TWO consumers — a redundant
// reorder (optimized out, network output) and a type-converting
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/input_output_alias_test.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/input_output_alias_test.cpp
new file mode 100644
index 00000000000..8ac77933c95
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/input_output_alias_test.cpp
@@ -0,0 +1,251 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include "intel_gpu/graph/network.hpp"
+#include "intel_gpu/graph/topology.hpp"
+#include "intel_gpu/primitives/activation.hpp"
+#include "intel_gpu/primitives/data.hpp"
+#include "intel_gpu/primitives/eltwise.hpp"
+#include "intel_gpu/primitives/input_layout.hpp"
+#include "intel_gpu/primitives/reorder.hpp"
+#include "intel_gpu/primitives/stateless_kv.hpp"
+#include "intel_gpu/runtime/layout.hpp"
+#include "test_utils.h"
+
+#include <string>
+#include <vector>
+
+using namespace cldnn;
+using namespace ::tests;
+
+namespace {
+
+constexpr auto past = "past";
+constexpr auto new_token = "new_token";
+constexpr auto present_len = "present_len";
+constexpr auto producer = "producer";
+constexpr auto net_output = "net_output";
+
+class InputOutputAliasTest : public ::testing::Test {
+protected:
+ layout past_layout{ov::PartialShape{1, 2, 16, 4}, data_types::f32, format::bfyx};
+ layout new_token_layout{ov::PartialShape{1, 2, 2, 4}, data_types::f32, format::bfyx};
+ layout present_len_layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
+
+ topology make_topology(int output_port = 0,
+ bool converting_output = false,
+ bool other_reader = false,
+ bool intermediate = false,
+ bool late_reader = false) {
+ auto stateless_kv_prim = stateless_kv(producer, {input_info(past), input_info(new_token), input_info(present_len)}, 2, true);
+ stateless_kv_prim.num_outputs = 2;
+ stateless_kv_prim.output_data_types = {data_types::f32, data_types::f32};
+ auto present_len_memory = get_test_engine().allocate_memory(present_len_layout);
+ set_values<int64_t>(present_len_memory, {16});
+
+ topology topo{
+ input_layout(past, past_layout),
+ input_layout(new_token, new_token_layout),
+ data(present_len, present_len_memory),
+ stateless_kv_prim,
+ };
+ if (other_reader)
+ topo.add(reorder("other_reader", input_info(past), format::bfyx, data_types::f16));
+ // Reading stateless_kv's output 1 forces this reader of past to run after stateless_kv.
+ if (late_reader)
+ topo.add(eltwise("late_reader", input_info(past), input_info(producer, 1), eltwise_mode::sum));
+
+ if (intermediate) {
+ topo.add(activation("middle", input_info(producer, 0), activation_func::relu));
+ topo.add(reorder(net_output, input_info("middle"), format::bfyx, data_types::f32));
+ } else {
+ topo.add(reorder(net_output,
+ input_info(producer, output_port),
+ format::bfyx,
+ converting_output ? data_types::f16 : data_types::f32));
+ }
+ return topo;
+ }
+
+ // Build the real stateless_kv graph and query whether an output buffer may reuse one of its inputs.
+ // Present length 16 and a two-token update produce a 16-element cache.
+ bool query(topology& topo, const primitive_id& output_id, const primitive_id& input_id) {
+ ExecutionConfig config = get_test_default_config(get_test_engine());
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ // network::may_alias() always rejects on out-of-order queues.
+ config.set_property(ov::intel_gpu::queue_type(QueueTypes::in_order));
+ network net(get_test_engine(), topo, config);
+ return net.may_alias(output_id, input_id);
+ }
+};
+
+TEST_F(InputOutputAliasTest, stateless_kv_accepts_its_past_buffer_for_output_zero) {
+ auto topo = make_topology();
+
+ EXPECT_TRUE(query(topo, net_output, past));
+}
+
+TEST_F(InputOutputAliasTest, stateless_kv_rejects_other_input_buffers) {
+ auto topo = make_topology();
+
+ EXPECT_FALSE(query(topo, net_output, new_token));
+}
+
+TEST_F(InputOutputAliasTest, stateless_kv_rejects_unsupported_output_port) {
+ auto topo = make_topology(1);
+
+ EXPECT_FALSE(query(topo, net_output, past));
+}
+
+// The other reader of past is scheduled before stateless_kv, so the in-place update can't affect it.
+TEST_F(InputOutputAliasTest, earlier_reader_of_past_keeps_in_place_binding) {
+ auto topo = make_topology(0, false, true);
+
+ EXPECT_TRUE(query(topo, net_output, past));
+}
+
+TEST_F(InputOutputAliasTest, later_reader_of_past_disables_in_place_binding) {
+ auto topo = make_topology(0, false, false, false, true);
+
+ EXPECT_FALSE(query(topo, net_output, past));
+}
+
+// past has no reader left once the output is written; stateless_kv then computes into its own buffer.
+TEST_F(InputOutputAliasTest, converting_output_reorder_after_last_past_reader_is_aliasable) {
+ auto topo = make_topology(0, true);
+
+ EXPECT_TRUE(query(topo, net_output, past));
+}
+
+TEST_F(InputOutputAliasTest, intermediate_writer_after_last_past_reader_is_aliasable) {
+ auto topo = make_topology(0, false, false, true);
+
+ EXPECT_TRUE(query(topo, net_output, past));
+}
+
+TEST_F(InputOutputAliasTest, ordinary_reorder_rejects_input_alias) {
+ topology topo{
+ input_layout(past, past_layout),
+ reorder(net_output, input_info(past), format::bfyx, data_types::f16),
+ };
+
+ EXPECT_FALSE(query(topo, net_output, past));
+}
+
+constexpr auto in0 = "in0";
+constexpr auto in1 = "in1";
+
+class InputOutputAliasGenericTest : public ::testing::TestWithParam<bool> {
+protected:
+ layout data_layout{ov::PartialShape{1, 4}, data_types::f32, format::bfyx};
+
+ // The parameter toggles the memory pool: aliasing decisions must not depend on it.
+ bool may_alias(topology& topo,
+ const primitive_id& output_id,
+ const primitive_id& input_id,
+ std::vector<std::string> outputs = {},
+ QueueTypes queue_type = QueueTypes::in_order,
+ bool* queue_type_supported = nullptr) {
+ ExecutionConfig config = get_test_default_config(get_test_engine());
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::enable_memory_pool(GetParam()));
+ config.set_property(ov::intel_gpu::queue_type(queue_type));
+ // oneDNN forces an in-order queue; it must be user-set to stay disabled on XMX devices.
+ if (queue_type == QueueTypes::out_of_order)
+ config.set_user_property(ov::intel_gpu::use_onednn(false));
+ if (!outputs.empty())
+ config.set_property(ov::intel_gpu::custom_outputs(outputs));
+ network net(get_test_engine(), topo, config);
+ const bool queue_type_matches = net.get_stream().get_queue_type() == queue_type;
+ if (queue_type_supported) {
+ *queue_type_supported = queue_type_matches;
+ if (!queue_type_matches)
+ return false;
+ } else {
+ EXPECT_EQ(net.get_stream().get_queue_type(), queue_type);
+ }
+ return net.may_alias(output_id, input_id);
+ }
+};
+
+// The output writer reads the input, so it can't write into the input's buffer.
+TEST_P(InputOutputAliasGenericTest, writer_reading_input_is_not_aliasable) {
+ topology topo{
+ input_layout(in0, data_layout),
+ input_layout(in1, data_layout),
+ eltwise(net_output, input_info(in0), input_info(in1), eltwise_mode::sum),
+ };
+
+ EXPECT_FALSE(may_alias(topo, net_output, in0));
+ EXPECT_FALSE(may_alias(topo, net_output, in1));
+}
+
+TEST_P(InputOutputAliasGenericTest, converting_reorder_of_input_is_not_aliasable) {
+ topology topo{
+ input_layout(in0, data_layout),
+ reorder(net_output, input_info(in0), format::bfyx, data_types::f16),
+ };
+
+ EXPECT_FALSE(may_alias(topo, net_output, in0));
+}
+
+TEST_P(InputOutputAliasGenericTest, pass_through_of_input_is_not_aliasable) {
+ topology topo{
+ input_layout(in0, layout{ov::PartialShape{1, -1}, data_types::f32, format::bfyx}),
+ reorder(net_output, input_info(in0), format::bfyx, data_types::f32),
+ };
+
+ EXPECT_FALSE(may_alias(topo, net_output, in0));
+}
+
+// in0 has no reader left once the output writer runs, so the writer may reuse in0's buffer.
+TEST_P(InputOutputAliasGenericTest, writer_after_last_input_reader_is_aliasable) {
+ topology topo{
+ input_layout(in0, data_layout),
+ input_layout(in1, data_layout),
+ activation("reader", input_info(in0), activation_func::relu),
+ eltwise(net_output, input_info("reader"), input_info(in1), eltwise_mode::sum),
+ };
+
+ EXPECT_TRUE(may_alias(topo, net_output, in0));
+ EXPECT_FALSE(may_alias(topo, net_output, in1));
+}
+
+// Independent readers of an input aren't ordered before the writer on an out-of-order queue.
+TEST_P(InputOutputAliasGenericTest, out_of_order_queue_is_not_aliasable) {
+ topology topo{
+ input_layout(in0, data_layout),
+ input_layout(in1, data_layout),
+ activation("reader", input_info(in0), activation_func::relu),
+ eltwise(net_output, input_info("reader"), input_info(in1), eltwise_mode::sum),
+ };
+
+ bool out_of_order_queue_supported = false;
+ const auto aliasable = may_alias(topo, net_output, in0, {}, QueueTypes::out_of_order, &out_of_order_queue_supported);
+ if (!out_of_order_queue_supported)
+ GTEST_SKIP() << "Out-of-order queues are unavailable for this device/configuration";
+
+ EXPECT_FALSE(aliasable);
+}
+
+// A later reader of in0 still needs its data after the output writer ran, wherever in0 sits in the processing order.
+TEST_P(InputOutputAliasGenericTest, writer_before_last_input_reader_is_not_aliasable) {
+ topology topo{
+ input_layout(in0, data_layout),
+ input_layout(in1, data_layout),
+ activation(net_output, input_info(in1), activation_func::relu),
+ eltwise("late_reader", input_info(in0), input_info(net_output), eltwise_mode::sum),
+ };
+
+ EXPECT_FALSE(may_alias(topo, net_output, in0, {net_output, "late_reader"}));
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke, InputOutputAliasGenericTest, ::testing::Bool(), [](const ::testing::TestParamInfo<bool>& info) {
+ return info.param ? "MemoryPool" : "NoMemoryPool";
+});
+
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmake
index e78a64f018c..1aeaf23ba13 100644
--- a/src/plugins/intel_gpu/tests/unit/sources.cmake
+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake
@@ -66,6 +66,7 @@ set(GPU_UNIT_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/module_tests/graph_manipulation_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/impls_registry_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/impls_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/module_tests/input_output_alias_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/jitter_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/kernel_impl_params_relevance_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/layout_test.cpp