Skip to content

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

[GPU] Add stream recording with Level Zero regular command list (#37255)

Jakub Kasprzak7d81aad55a53
diff --git a/src/common/zero_loader/include/openvino/zero_api.hpp b/src/common/zero_loader/include/openvino/zero_api.hpp
index 4bcbb8dc78e..e0219874d0c 100644
--- a/src/common/zero_loader/include/openvino/zero_api.hpp
+++ b/src/common/zero_loader/include/openvino/zero_api.hpp
@@ -107,7 +107,8 @@ namespace ov {
symbol_statement(zeCommandQueueSetPriorityExt) \
symbol_statement(zeEventCounterBasedCreate) \
symbol_statement(zeCommandQueueSetQosExt) \
- symbol_statement(zeCommandQueueGetQosExt)
+ symbol_statement(zeCommandQueueGetQosExt) \
+ symbol_statement(zeCommandListImmediateAppendCommandListsWithParameters)
// clang-format on
/**
diff --git a/src/plugins/intel_gpu/docs/gpu_record_replay.md b/src/plugins/intel_gpu/docs/gpu_record_replay.md
new file mode 100644
index 00000000000..ba0ed9ca645
--- /dev/null
+++ b/src/plugins/intel_gpu/docs/gpu_record_replay.md
@@ -0,0 +1,49 @@
+# [Experimental] Level Zero command list record and replay
+
+Sometimes, preparing and submitting a GPU kernel can take more time than actually executing it. Running an AI model consisting of many such kernels can result in GPU underutilization as the CPU is not able to submit work fast enough and becomes the bottleneck. Record and replay feature based on Level Zero command list can improve average performance of such models by recording GPU commands during first iteration and then replaying them on subsequent iterations.
+
+Please note that this is an internal option currently, and support in the future is not guaranteed.
+
+## How to enable Level Zero command list record and replay
+
+By default GPU record and replay is disabled and user must set `OV_GPU_RECORD_REPLAY=1` environment variable to enable it for supported static models. Additional debug option `OV_GPU_RECORD_REPLAY_DYNAMIC=1` enables the feature on all models but may produce incorrect results and requires OpenVINO build with `ENABLE_DEBUG_CAPS=ON`.
+
+Learn how to set OpenVINO options here `src/plugins/intel_gpu/docs/gpu_debug_utils.md`.
+
+## What models are supported
+
+Currently record and replay feature supports only some static models and in-order streams with `SyncMethods::none`. When network created for the model contains primitives that does not support replay then exception is thrown. Please check `supports_replay()` in the primitives.
+
+Support check can be skipped by setting `OV_GPU_RECORD_REPLAY_DYNAMIC=1` option. This option is added to understand performance status with command list.
+
+## How recording works
+
+Recording iteration can be divided into 2 phases.
+
+1. Capture phase
+
+ During this phase GPU commands are not submitted to the device but instead they are captured to Level Zero command list. Once all network primitives are processed OpenVINO advances to submit phase. This phase can be interrupted when executing dynamic network and any of the executed primitives requires GPU to host synchronization. When interrupted, all commands captured up to this point are submitted, the remaining primitives are executed with immediate command list and re-recording is attempted on the next iteration.
+
+2. Submit phase
+
+ During this phase all captured commands are submitted to the device at once and the network enqueue concludes.
+
+Inference latency during recording (capture phase + submit phase + wait) can be up to 2 times longer than immediate execution.
+
+## How replay works
+
+During replay iteration OpenVINO submits all recorded commands at once and skips the usual primitive preparation and execution phases performed on CPU - preventing situations in which the GPU remains idle while waiting for CPU to submit next kernel.
+
+Inference latency during replay (submit phase + wait) should not be worse than immediate execution.
+
+## Recording invalidation
+
+Command list is recorded at network level and captures input and output memory pointers. Changing input or output of the network will cause recording invalidation and forces network to record again on the next iteration. Repeated re-recording will result in performance degradation and for such use cases it is advised to disable this feature.
+
+## Multiple inference requests
+
+Using record and replay feature with more than 1 inference request can lead to recording invalidation as inference requests can bind to any available stream and update the network.
+
+## Synchronization method
+
+Currently record and replay supports only in-order execution with `SyncMethods::none` (which is the default configuration for OpenVINO builds with OneDNN enabled). Using `SyncMethods::barriers` or `SyncMethods::events` may result in application hang as signal-wait sequence might not be correctly captured for some events.
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 81095dca44c..b769926b55a 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
@@ -8,6 +8,7 @@
#include "intel_gpu/graph/topology.hpp"
#include "intel_gpu/graph/program.hpp"
+#include "intel_gpu/graph/record_replay_session.hpp"
#include "intel_gpu/graph/serialization/binary_buffer.hpp"
#include "intel_gpu/runtime/memory.hpp"
#include "intel_gpu/runtime/engine.hpp"
@@ -244,6 +245,7 @@ private:
program::ptr _program;
engine& _engine;
stream::ptr _stream;
+ record_replay_session::ptr _record_replay_session = nullptr;
std::unique_ptr<memory_pool> _memory_pool;
bool _internal;
bool _is_primary_stream;
@@ -280,6 +282,11 @@ private:
std::shared_ptr<ShapePredictor> _shape_predictor;
+ /// @brief Invalidate the recording of the previous iteration
+ void invalidate_recording();
+ /// @brief Prepares record and replay session
+ /// @note expects that exec_order is constructed
+ void prepare_record_replay();
void build_exec_order();
void allocate_primitive_instance(program_node const& node);
void transfer_memory_to_device(std::shared_ptr<primitive_inst> instance, program_node const& node);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/graph/record_replay_session.hpp b/src/plugins/intel_gpu/include/intel_gpu/graph/record_replay_session.hpp
new file mode 100644
index 00000000000..46faf6f94c4
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/record_replay_session.hpp
@@ -0,0 +1,56 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "intel_gpu/runtime/debug_configuration.hpp"
+
+#include <memory>
+#include <list>
+#include <vector>
+
+namespace cldnn {
+
+class stream;
+class command_recorder;
+class command_list;
+class primitive_inst;
+struct event;
+
+/// @brief Manages the record and replay of GPU command streams for a network execution session.
+class record_replay_session {
+public:
+ using ptr = std::shared_ptr<record_replay_session>;
+ explicit record_replay_session(stream& s);
+
+ /// @brief Start recording commands on the associated stream.
+ /// @param deps Events that must complete before recorded commands are executed.
+ /// @note Events from deps are not added to the command list.
+ /// @note For each begin_recording() there must be corresponding call to end_recording().
+ void begin_recording(const std::vector<std::shared_ptr<event>>& deps);
+
+ /// @brief Ends the current recording session and executes recorded commands.
+ void end_recording();
+
+ /// @brief Attempt to replay previously recorded command list.
+ /// @param deps Events that must complete before commands are replayed.
+ /// @param primitives A list of primitives to replay. Must be the same as the list used for the recording.
+ /// @return True if replay was successful, false otherwise.
+ bool replay(const std::vector<std::shared_ptr<event>>& deps,
+ const std::list<std::shared_ptr<primitive_inst>>& primitives);
+
+ /// @brief Invalidates the recorded command list.
+ void invalidate() {
+ _valid = false;
+ GPU_DEBUG_TRACE_DETAIL << "[REC] Recorded command list was invalidated";
+ }
+
+private:
+ stream& _stream;
+ command_recorder& _recorder;
+ std::shared_ptr<command_list> _cmd_list;
+ bool _valid = false;
+};
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/command_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/command_list.hpp
new file mode 100644
index 00000000000..043e94ba7bb
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/command_list.hpp
@@ -0,0 +1,72 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/core/except.hpp"
+
+#include <memory>
+
+namespace cldnn {
+enum class command_list_status {
+ open = 0,
+ closed = 1,
+ enqueued = 2,
+};
+
+/// @brief Commands that can be recorded and executed
+/// @note Concurrent operations on the same command list are not allowed.
+class command_list {
+public:
+ using ptr = std::shared_ptr<command_list>;
+ virtual ~command_list() = default;
+
+ command_list_status get_status() const { return _status; }
+
+ /// @brief Reset command list to initial empty state.
+ void reset() {
+ if (_status == command_list_status::enqueued) {
+ wait();
+ }
+ reset_impl();
+ _status = command_list_status::open;
+ }
+
+ /// @brief Close command list and make it ready for execution.
+ void close() {
+ OPENVINO_ASSERT(_status == command_list_status::open, "[GPU] Can't close command list that is not open");
+ close_impl();
+ _status = command_list_status::closed;
+ }
+
+ /// @brief Enqueue command list on associated stream.
+ /// @note Resources referenced by the command list must remain valid during command list execution.
+ void enqueue() {
+ OPENVINO_ASSERT(_status != command_list_status::open, "[GPU] Can't enqueue command list that is open");
+ if (_status == command_list_status::enqueued) {
+ wait();
+ }
+ enqueue_impl();
+ _status = command_list_status::enqueued;
+ }
+
+ /// @brief Wait for command list execution to finish.
+ void wait() {
+ OPENVINO_ASSERT(_status != command_list_status::open, "[GPU] Can't wait on command list that is open");
+ if (_status == command_list_status::closed) {
+ return;
+ }
+ wait_impl();
+ _status = command_list_status::closed;
+ }
+protected:
+ virtual void reset_impl() = 0;
+ virtual void close_impl() = 0;
+ virtual void enqueue_impl() = 0;
+ virtual void wait_impl() = 0;
+
+ command_list_status _status = command_list_status::open;
+};
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/command_recorder.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/command_recorder.hpp
new file mode 100644
index 00000000000..e6ca1ae2c1a
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/command_recorder.hpp
@@ -0,0 +1,58 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "command_list.hpp"
+#include "openvino/core/except.hpp"
+
+#include <memory>
+#include <mutex>
+
+namespace cldnn {
+/// @brief Interface for recording commands on associated stream.
+/// @note command_recorder interface is not thread safe and must be used from the same thread as the associated stream
+class command_recorder {
+public:
+ using ptr = std::shared_ptr<command_recorder>;
+ command_recorder() = default;
+ virtual ~command_recorder() = default;
+ // Delete copy ctor to prevent sharing active command list
+ command_recorder(const command_recorder& other) = delete;
+
+ /// @brief Create command list for recording executed commands.
+ /// @return Command list object.
+ virtual command_list::ptr create_command_list() const = 0;
+
+ /// @brief Start recording operations executed on the associated stream.
+ /// Executed commands are not submitted to the device during recording.
+ /// @param cmd_list Open command list to record executed commands.
+ void start_recording(command_list::ptr cmd_list) {
+ OPENVINO_ASSERT(cmd_list->get_status() == command_list_status::open, "Can't start recording command list that is not open");
+ OPENVINO_ASSERT(_active_cmd_list == nullptr, "Can't start recording while another recording is in progress");
+ _active_cmd_list = cmd_list;
+ }
+ /// @brief Get command list that is currently being recorded.
+ /// @return Command list that is currently being recorded or nullptr.
+ command_list::ptr get_active_command_list() const {
+ return _active_cmd_list;
+ }
+
+ /// @brief Stop recording and submit all recorded commands to the device.
+ /// @return Command list with recorded commands or nullptr if stream was not recording.
+ command_list::ptr stop_recording() {
+ command_list::ptr ret = nullptr;
+ _active_cmd_list.swap(ret);
+ if (ret != nullptr) {
+ ret->close();
+ ret->enqueue();
+ }
+ return ret;
+ }
+
+protected:
+ command_list::ptr _active_cmd_list;
+};
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
index f1a73b0c286..08d40fc70e6 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
@@ -143,6 +143,7 @@ static constexpr Property<size_t, PropertyMutability::RW> max_kernels_per_batch{
static constexpr Property<bool, PropertyMutability::RW> use_onednn{"GPU_USE_ONEDNN"};
static constexpr Property<bool, PropertyMutability::RW> use_cm{"GPU_USE_CM"};
static constexpr Property<bool, PropertyMutability::RW> enable_zero_copy_cache_load{"GPU_ENABLE_ZERO_COPY_CACHE_LOAD"};
+static constexpr Property<bool, PropertyMutability::RW> record_replay{"GPU_RECORD_REPLAY"};
/**
* @brief [EXPERIMENTAL] Enables MLIR-based Graph Compiler execution for supported subgraphs.
@@ -230,6 +231,7 @@ static constexpr Property<bool, ov::PropertyMutability::RW> print_input_data_sha
static constexpr Property<bool, ov::PropertyMutability::RW> pa_integrity_check{"GPU_PA_INTEGRITY_CHECK"};
static constexpr Property<std::vector<int>, ov::PropertyMutability::RW> micro_sdpa_workgroup_config{"GPU_MICRO_SDPA_WORKGROUP_CONFIG"};
static constexpr Property<std::string, ov::PropertyMutability::RW> pa_mixed_route_mode{"GPU_PA_MIXED_ROUTE_MODE"};
+static constexpr Property<bool, PropertyMutability::RW> record_replay_dynamic{"GPU_RECORD_REPLAY_DYNAMIC"};
} // namespace ov::intel_gpu
namespace cldnn {
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
index 065031dc2ec..d8d0d395d02 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
@@ -83,6 +83,7 @@ OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_gpu_mask_gen_prefill, f
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_grouped_gemm_prefill, true, "MoE 3GEMM: use a single OneDNN grouped matmul per GEMM layer for the prefill path. Takes priority over micro-kernel GEMM")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_batched_gemv_threshold, 32, "MoE 3-GEMM: token count (<=) that selects the batched GEMV decode path instead of the prefill path")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_disable_fusion, false, "Disable fusion of MoE subgraph to composite MoE operation")
+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, record_replay, false, "Enable level-zero command list through record and replay for static models")
OV_CONFIG_DEBUG_GLOBAL_OPTION(ov::intel_gpu, help, false, "Print help message for all config options")
OV_CONFIG_DEBUG_GLOBAL_OPTION(ov::intel_gpu, verbose, 0, "Enable logging for debugging purposes. The higher value the more verbose output. 0 - Disabled, 4 - Maximum verbosity")
@@ -130,3 +131,4 @@ OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, list_layers, false, "Print layers list")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, print_input_data_shapes, false, "print input data shapes")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, pa_integrity_check, false, "Enable in-kernel SDPA micro-GEMM integrity checks (per-row K^T*Q and V*S reference comparisons)")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, micro_sdpa_workgroup_config, std::vector<int>{}, "Override SDPA micro-kernel workgroup config: 4 ints [wg_m_kq wg_n_kq wg_m_vs wg_n_vs]")
+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, record_replay_dynamic, false, "Enable level-zero command list through record and replay for all (static and dynamic) models. Feature is work in progress and may produce incorrect results.")
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/stream.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/stream.hpp
index 3088d095068..767ec610a33 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/stream.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/stream.hpp
@@ -8,6 +8,7 @@
#include "kernel.hpp"
#include "kernel_args.hpp"
#include "execution_config.hpp"
+#include "command_recorder.hpp"
#include <memory>
#include <vector>
@@ -55,6 +56,10 @@ public:
virtual void finish() const = 0;
virtual void wait() = 0;
+ /// @brief Get the command recorder associated with the stream.
+ /// @return Command recorder object or nullptr if not supported.
+ virtual command_recorder::ptr get_recorder() const { return nullptr; }
+
virtual void set_arguments(kernel& kernel, const kernel_arguments_desc& args_desc, const kernel_arguments_data& args) = 0;
virtual event::ptr enqueue_kernel(kernel& kernel,
const kernel_arguments_desc& args_desc,
@@ -62,7 +67,10 @@ public:
std::vector<event::ptr> const& deps,
bool is_output_event = false) = 0;
virtual event::ptr enqueue_marker(std::vector<event::ptr> const& deps, bool is_output_event = false) = 0;
- virtual void enqueue_barrier() = 0;
+ /// @brief Enqueue a barrier that blocks all following commands.
+ /// @param deps A vector of events that the barrier should wait for.
+ /// @note If deps is empty, the barrier will wait for all previously enqueued commands to complete.
+ virtual void enqueue_barrier(const std::vector<event::ptr>& deps = {}) = 0;
virtual event::ptr group_events(std::vector<event::ptr> const& deps) = 0;
virtual void wait_for_events(const std::vector<event::ptr>& events) = 0;
virtual event::ptr create_user_event(bool set) = 0;
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
index ece8e2f9a8d..3bc3a6c8843 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
@@ -78,6 +78,11 @@ class PagedAttentionCmImpl : public PrimitiveImplCM {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::cm::PagedAttentionCmImpl)
+ // Dispatch is decided by reading sequence-length/block-mapping tensor contents on the host
+ bool supports_replay() const override {
+ return false;
+ }
+
Stage::Ptr kv_cache_update = make_stage<PagedAttentionGeneratorKVCacheUpdate>();
Stage::Ptr pa_single_token = make_stage<PagedAttentionGeneratorSingleToken>();
Stage::Ptr pa_single_token_finalization = make_stage<PagedAttentionGeneratorSingleTokenFinalization>();
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/vl_sdpa_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/vl_sdpa_opt.cpp
index 6f4ba156aea..f57ecacd7b7 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/vl_sdpa_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/vl_sdpa_opt.cpp
@@ -233,6 +233,11 @@ class VLSDPAOptImpl : public PrimitiveImplCM {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::cm::VLSDPAOptImpl)
+ // Dispatch is decided by reading cu_seqlens tensor contents on the host
+ bool supports_replay() const override {
+ return false;
+ }
+
Stage::Ptr vl_sdpa = make_stage<VLSDPAGenerator>();
VLSDPAOptImpl() : PrimitiveImplOCL(VLSDPAOptImplementationManager::get_type_info_static()) {}
diff --git a/src/plugins/intel_gpu/src/graph/impls/common/wait_for_events.cpp b/src/plugins/intel_gpu/src/graph/impls/common/wait_for_events.cpp
index 1fef5e2b1fe..dc27516065d 100644
--- a/src/plugins/intel_gpu/src/graph/impls/common/wait_for_events.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/common/wait_for_events.cpp
@@ -29,6 +29,9 @@ public:
return std::make_unique<wait_for_events_impl>(*this);
}
+ // execute() only aggregates input events and enqueues no GPU commands
+ bool supports_replay() const override { return true; }
+
void init_kernels(const kernels_cache&, const kernel_impl_params&) override {}
void set_arguments(primitive_inst& /*instance*/) override {}
void set_arguments(primitive_inst& /*instance*/, kernel_arguments_data& /*args*/) override {}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
index 50dd60c6b70..05a746e4441 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
@@ -597,6 +597,12 @@ static int64_t get_bytes_count(int64_t element_count, const cldnn::layout& layou
class moe_3gemm_swiglu_opt_impl : public PrimitiveImplOCL {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoE3GemmSwigluImpl)
+
+ // Routing/expert selection is read back to the host (topk_ids, expert masks)
+ bool supports_replay() const override {
+ return false;
+ }
+
Stage::Ptr gather = make_stage<MoE3GemmSwigluGather>();
Stage::Ptr scatter = make_stage<MoE3GemmSwigluScatter>();
Stage::Ptr mlp_gate_up = make_stage<MoE3GemmSwigluMLPGateUp>();
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
index 1906d35a63d..af221de9d41 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
@@ -1323,6 +1323,11 @@ class PagedAttentionOptImpl : public SDPAImplBase {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::PagedAttentionOptImpl)
+ // Dispatch (e.g. PREFILL vs MIXED stage) is decided by reading past_lens/subsequence_begins contents
+ bool supports_replay() const override {
+ return false;
+ }
+
Stage::Ptr kv_cache_update = make_stage<KVCacheUpdateGenerator>();
Stage::Ptr pa_single_token = make_stage<PagedAttentionGeneratorSingleToken>();
Stage::Ptr pa_gqa_single_token = make_stage<PagedAttentionGeneratorGQASingleToken>();
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
index f4bdd3848e4..d9d7f811c2e 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
@@ -44,6 +44,12 @@ bool SDPAOpt::has_per_channel_compressed_kv(const kernel_impl_params& params) {
class SDPAOptImpl : public SDPAImplBase {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::SDPAOptImpl)
+
+ // The micro-kernel stage (SDPAMicroGenerator) dispatches based on subsequence_begins/max_context_len contents
+ bool supports_replay() const override {
+ return false;
+ }
+
static constexpr bool indirect = true;
static constexpr bool prefill = true;
diff --git a/src/plugins/intel_gpu/src/graph/impls/sycl/primitive_sycl_base.h b/src/plugins/intel_gpu/src/graph/impls/sycl/primitive_sycl_base.h
index b86746f2968..02406881f80 100644
--- a/src/plugins/intel_gpu/src/graph/impls/sycl/primitive_sycl_base.h
+++ b/src/plugins/intel_gpu/src/graph/impls/sycl/primitive_sycl_base.h
@@ -31,6 +31,7 @@ struct typed_primitive_sycl_impl : public typed_primitive_impl<PType> {
bool is_cpu() const override { return false; }
bool is_onednn() const override { return false; }
+ bool supports_replay() const override { return false; }
protected:
void init_kernels(const kernels_cache&, const kernel_impl_params&) override { }
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 758e7f0e8fa..46518de7230 100644
--- a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
@@ -82,6 +82,14 @@ struct primitive_impl {
virtual bool is_cpu() const { return true; }
virtual bool is_onednn() const { return false; }
+ // Recording captures GPU API calls made during execute()
+ // Implementation supports replay only when captured calls remain valid and host side logic can be skipped.
+ // This function should return false when:
+ // * Kernel dispatch logic depends on the tensor data instead of tensor shape
+ // * Results are calculated on the CPU
+ // By default non-cpu implementations are considered to support replay.
+ virtual bool supports_replay() const { return !is_cpu(); }
+
// Whether this impl needs its inputs to be in host-accessible (lockable) memory.
// Defaults to is_cpu(), because CPU impls typically read/write tensor data from the host.
// Impls whose execute path only performs GPU-side USM operations (e.g. an enqueue_memcpy
@@ -303,7 +311,8 @@ public:
// Defers output memory invalidation until prepare_primitive(), after runtime shapes are known.
void request_output_reallocation() { _output_reallocation_requested = true; }
- void reset_events();
+ void clear_events();
+ void reset_out_event();
void prepare_primitive();
void execute();
diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cpp
index 397987fe60d..66a9814acae 100644
--- a/src/plugins/intel_gpu/src/graph/network.cpp
+++ b/src/plugins/intel_gpu/src/graph/network.cpp
@@ -63,6 +63,31 @@
namespace cldnn {
namespace {
+// Check if layouts are the same after expanding the lower-rank shape with ones
+bool compare_expanded_layout(layout left, layout right) {
+ auto left_shape = left.get_partial_shape();
+ auto right_shape = right.get_partial_shape();
+
+ // Fall back to strict equality for dynamic shapes
+ if (left_shape.rank().is_dynamic() || right_shape.rank().is_dynamic()) {
+ return left == right;
+ }
+
+ const size_t max_rank = std::max(left_shape.size(), right_shape.size());
+ auto expand_with_trailing_ones = [max_rank](ov::PartialShape& shape) {
+ while (shape.size() < max_rank) {
+ shape.push_back(ov::Dimension(1));
+ }
+ };
+ expand_with_trailing_ones(left_shape);
+ expand_with_trailing_ones(right_shape);
+
+ left.set_partial_shape(left_shape);
+ right.set_partial_shape(right_shape);
+
+ return left == right;
+}
+
#ifdef GPU_DEBUG_CONFIG
void dump_perf_data_raw(std::string dump_path, bool per_iter_mode, const std::list<std::shared_ptr<primitive_inst>>& exec_order) {
auto layouts_to_str = [](const std::vector<layout>& layouts) -> std::string {
@@ -249,6 +274,7 @@ network::network(program::ptr program, stream::ptr stream, bool is_internal, boo
validate_primitives();
preallocate_shape_info_buffers();
add_default_output_chains();
+ prepare_record_replay();
}
network::network(program::ptr program, bool is_internal, bool is_primary_stream)
@@ -413,9 +439,17 @@ event::ptr network::set_input_data(const primitive_id& id, memory::ptr data, boo
CLDNN_ERROR_MESSAGE(id, "primitive " + id + " is not an input");
}
auto input = std::static_pointer_cast<input_layout_inst>(primitive_inst);
- const bool was_unallocated = !input->output_memory_ptr();
+ const auto prev_mem = input->output_memory_ptr();
+ const bool was_unallocated = !prev_mem;
auto ev = input->set_data(data, need_to_check_memory_to_set);
+ const auto new_mem = input->output_memory_ptr();
+ const bool same_buffer = prev_mem && new_mem &&
+ get_engine().is_the_same_buffer(*prev_mem, *new_mem) &&
+ compare_expanded_layout(prev_mem->get_layout(), new_mem->get_layout());
+ if (!same_buffer)
+ invalidate_recording();
+
if (was_unallocated) {
// The initial set_arguments() skipped nodes whose dep buffer was null —
// force a fresh rebind now that the buffer is available.
@@ -581,6 +615,13 @@ std::vector<event::ptr> network::set_output_memory(const primitive_id& id, memor
std::vector<event::ptr> ret_ev;
std::shared_ptr<primitive_inst> p_inst = find_primitive(id);
+ const auto prev_out = p_inst->output_memory_ptr();
+ const bool same_buffer = prev_out && mem_new &&
+ get_engine().is_the_same_buffer(*prev_out, *mem_new) &&
+ compare_expanded_layout(prev_out->get_layout(), mem_new->get_layout());
+ if (!same_buffer)
+ invalidate_recording();
+
auto iter = std::find(_outputs.begin(), _outputs.end(), p_inst);
if (iter == _outputs.end()) {
throw std::runtime_error("primitive: " + id + " is not a network output");
@@ -875,11 +916,13 @@ void network::register_output_memory_block(const primitive_id& id, ov::intel_gpu
}
it->second = block;
}
+ invalidate_recording();
}
void network::unregister_output_memory_block(const primitive_id& id) {
auto it = _output_memory_blocks.find(id);
if (it != _output_memory_blocks.end()) {
+ invalidate_recording();
_output_memory_blocks.erase(it);
invalidate_ext_block_compute_nodes(id);
}
@@ -891,6 +934,9 @@ ov::intel_gpu::OutputMemoryBlock* network::get_output_memory_block(const primiti
}
void network::clear_output_memory_blocks() {
+ if (!_output_memory_blocks.empty()) {
+ invalidate_recording();
+ }
// Move map out first so _output_memory_blocks is empty even if invalidation throws.
auto blocks = std::move(_output_memory_blocks);
for (auto& [prim_id, block_ptr] : blocks) {
@@ -978,32 +1024,54 @@ bool network::has_event(const primitive_id& id) const {
}
void network::execute_impl(const std::vector<event::ptr>& events) {
- set_arguments();
-
- // This extra flush command is needed for dynamic models in both cases of out_of_order / in_order operating mode
- // since it reduces `bubbles` number in pipeline and GPU's idle time by timely flushing new kernels to device.
- // The freqency of flushing (16) is selected empirically, see details in tickets 116365, 116287, 139931.
- const bool needs_flushing = _is_dynamic;
- const size_t flush_frequency = needs_flushing ? 16 : 0;
- size_t executed_prims = 0;
-
- for (auto& inst : _exec_order) {
- NODE_DEBUG(*inst);
- OV_ITT_SCOPED_TASK_BASE(ov::intel_gpu::itt::domains::intel_gpu_op, openvino::itt::handle(inst->id()));
-
- inst->reset_events();
-
- if (inst->is_input()) {
- inst->add_dep_events(events);
+ bool is_recording = false;
+ if (_record_replay_session) {
+ if (_record_replay_session->replay(events, _exec_order)) {
+ return;
}
+ _record_replay_session->begin_recording(events);
+ is_recording = true;
+ }
+ try {
+ set_arguments();
+
+ // This extra flush command is needed for dynamic models in both cases of out_of_order / in_order operating mode
+ // since it reduces `bubbles` number in pipeline and GPU's idle time by timely flushing new kernels to device.
+ // The freqency of flushing (16) is selected empirically, see details in tickets 116365, 116287, 139931.
+ const bool needs_flushing = _is_dynamic;
+ const size_t flush_frequency = needs_flushing ? 16 : 0;
+ size_t executed_prims = 0;
+
+ for (auto& inst : _exec_order) {
+ NODE_DEBUG(*inst);
+ OV_ITT_SCOPED_TASK_BASE(ov::intel_gpu::itt::domains::intel_gpu_op, openvino::itt::handle(inst->id()));
+
+ inst->clear_events();
+
+ // Dependency events should not be recorded to the command list
+ // As they could propagate to the subsequent replay iteration
+ // Instead events were passed to begin_recording()
+ if (!is_recording && inst->is_input()) {
+ inst->add_dep_events(events);
+ }
- inst->prepare_primitive();
- inst->execute();
+ inst->prepare_primitive();
+ inst->execute();
- executed_prims++;
- if (needs_flushing && executed_prims % flush_frequency == 0) {
- get_stream().flush();
+ executed_prims++;
+ if (needs_flushing && executed_prims % flush_frequency == 0) {
+ get_stream().flush();
+ }
}
+ } catch (...) {
+ if (is_recording) {
+ _record_replay_session->end_recording();
+ _record_replay_session->invalidate();
+ }
+ throw;
+ }
+ if (is_recording) {
+ _record_replay_session->end_recording();
}
// Using output of previous network as input to another one may cause hazard (in OOOQ mode) if user would not
@@ -1017,6 +1085,53 @@ void network::execute_impl(const std::vector<event::ptr>& events) {
}
}
+void network::invalidate_recording() {
+ if (_record_replay_session) {
+ _record_replay_session->invalidate();
+ }
+}
+
+void network::prepare_record_replay() {
+ bool use_record_replay = get_config().get_record_replay();
+ bool skip_model_check = GPU_DEBUG_VALUE_OR(get_config().get_record_replay_dynamic(), false);
+ bool should_use_record_replay = !_internal && (use_record_replay || skip_model_check);
+ if (!should_use_record_replay) {
+ return;
+ }
+ OPENVINO_ASSERT(_stream->get_recorder() != nullptr, "[GPU] Stream recording is not supported by the current stream implementation");
+ auto check_model_support = [this]() {
+ // Record & replay re-submits a fixed sequence of GPU commands.
+ // Only safe when recording iteration produces self-contained GPU command stream that remains valid across iterations.
+
+ // Event/barrier based synchronization can cause hangs during replay
+ if (_stream->get_queue_type() != QueueTypes::in_order || _stream->get_sync_method() != cldnn::SyncMethods::none)
+ return false;
+
+ // When model is dynamic it is not safe to fully skip prepare_primitive and execute logic on replay iterations
+ if (_is_dynamic)
+ return false;
+ // Variable state might invalidate recording when updated
+ if (!_variables_state_info.empty())
+ return false;
+ for (const auto& inst : _exec_order) {
+ // Inner network execution (loop/condition primitives) is based on host-side logic
+ if (inst->has_inner_networks())
+ return false;
+ // Check for any implementations that are not replay safe
+ const auto* impl = inst->get_impl();
+ if (impl == nullptr)
+ return false;
+ if (!impl->supports_replay())
+ return false;
+ }
+ return true;
+ };
+ if (!skip_model_check) {
+ OPENVINO_ASSERT(check_model_support(), "[GPU] Record and replay is not supported on the provided model");
+ }
+ _record_replay_session = std::make_shared<record_replay_session>(*_stream);
+}
+
std::vector<primitive_id> network::get_input_ids() const {
std::vector<primitive_id> ret;
ret.reserve(_inputs.size());
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index 7248c615ac2..b9c9401a8c5 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -2293,7 +2293,13 @@ void primitive_inst::set_out_event(event::ptr&& ev) {
_impl_params->out_event = ev;
}
-void primitive_inst::reset_events() {
+void primitive_inst::reset_out_event() {
+ if (_impl_params->out_event) {
+ _impl_params->out_event->reset();
+ }
+}
+
+void primitive_inst::clear_events() {
_impl_params->dep_events.clear();
_impl_params->out_event = nullptr;
}
@@ -2519,7 +2525,8 @@ void primitive_inst::prepare_primitive() {
// Use marker to ensure proper synchronization for both events and barriers
auto dep_events = out_of_order_queue ? std::vector<event::ptr>{get_network().get_stream().enqueue_marker(_impl_params->dep_events)}
: std::vector<event::ptr>{};
- add_dep_event(output->fill(get_network().get_stream(), dep_events));
+ // Add dependency event for the output fill operation but do not sync with host
+ add_dep_event(output->fill(get_network().get_stream(), dep_events, false));
}
}
}
diff --git a/src/plugins/intel_gpu/src/graph/record_replay_session.cpp b/src/plugins/intel_gpu/src/graph/record_replay_session.cpp
new file mode 100644
index 00000000000..a2b48ef8921
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/record_replay_session.cpp
@@ -0,0 +1,56 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/graph/record_replay_session.hpp"
+#include "intel_gpu/runtime/stream.hpp"
+#include "intel_gpu/runtime/event.hpp"
+#include "intel_gpu/runtime/command_list.hpp"
+#include "intel_gpu/runtime/command_recorder.hpp"
+#include "intel_gpu/runtime/debug_configuration.hpp"
+
+#include "primitive_inst.h"
+
+namespace cldnn {
+
+record_replay_session::record_replay_session(stream& s)
+ : _stream(s), _recorder(*s.get_recorder()),
+ _cmd_list(_recorder.create_command_list()) {}
+
+void record_replay_session::begin_recording(const std::vector<std::shared_ptr<event>>& deps) {
+ if (!deps.empty()) {
+ // Ensure dependencies complete before recording
+ _stream.enqueue_barrier(deps);
+ }
+ if (_cmd_list->get_status() != command_list_status::open) {
+ _cmd_list->reset();
+ }
+ _recorder.start_recording(_cmd_list);
+ GPU_DEBUG_TRACE_DETAIL << "[REC] Started recording command list" << std::endl;
+}
+
+void record_replay_session::end_recording() {
+ auto finished = _recorder.stop_recording();
+ _valid = (finished == _cmd_list);
+ GPU_DEBUG_TRACE_DETAIL << "[REC] Command list recording " << (_valid ? "succeeded" : "failed") << std::endl;
+}
+
+bool record_replay_session::replay(const std::vector<std::shared_ptr<event>>& deps, const std::list<std::shared_ptr<primitive_inst>>& primitives) {
+ if (!_valid) {
+ return false;
+ }
+ if (!deps.empty()) {
+ // Ensure dependencies complete before replaying
+ _stream.enqueue_barrier(deps);
+ }
+ _cmd_list->wait();
+ for (const auto& inst : primitives) {
+ inst->reset_out_event();
+ }
+ _cmd_list->enqueue();
+ GPU_DEBUG_TRACE_DETAIL << "[REC] Enqueued recorded command list" << std::endl;
+
+ return true;
+}
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.cpp b/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.cpp
index eb634b8b6fb..59371a65766 100644
--- a/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.cpp
@@ -319,11 +319,23 @@ event::ptr ocl_stream::enqueue_kernel(kernel& kernel,
return std::make_shared<ocl_event>(ret_ev, ++_queue_counter);
}
-void ocl_stream::enqueue_barrier() {
- try {
- _command_queue.enqueueBarrierWithWaitList(nullptr, nullptr);
- } catch (const cl::Error& err) {
- OPENVINO_THROW(OCL_ERR_MSG_FMT(err));
+void ocl_stream::enqueue_barrier(const std::vector<event::ptr>& deps) {
+ if (deps.empty()) {
+ try {
+ _command_queue.enqueueBarrierWithWaitList(nullptr, nullptr);
+ } catch (const cl::Error& err) {
+ OPENVINO_THROW(OCL_ERR_MSG_FMT(err));
+ }
+ } else {
+ auto dep_events = utils::get_cl_events(deps);
+ if (dep_events.empty()) {
+ return;
+ }
+ try {
+ _command_queue.enqueueBarrierWithWaitList(&dep_events, nullptr);
+ } catch (const cl::Error& err) {
+ OPENVINO_THROW(OCL_ERR_MSG_FMT(err));
+ }
}
}
diff --git a/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.hpp b/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.hpp
index d3ff8f9423f..94ee7c565eb 100644
--- a/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ocl/ocl_stream.hpp
@@ -49,7 +49,7 @@ public:
event::ptr enqueue_marker(std::vector<event::ptr> const& deps, bool is_output) override;
event::ptr group_events(std::vector<event::ptr> const& deps) override;
void wait_for_events(const std::vector<event::ptr>& events) override;
- void enqueue_barrier() override;
+ void enqueue_barrier(const std::vector<event::ptr>& deps) override;
event::ptr create_user_event(bool set) override;
event::ptr create_base_event() override;
#ifdef ENABLE_MLIR_FOR_GPU
diff --git a/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.cpp b/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.cpp
index cd8589f2b9f..c2ff51b15af 100644
--- a/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.cpp
+++ b/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.cpp
@@ -130,7 +130,8 @@ event::ptr sycl_stream::enqueue_kernel(kernel& kernel,
return std::make_shared<sycl_event>(ret_ev, _command_queue, ++_queue_counter);
}
-void sycl_stream::enqueue_barrier() {
+void sycl_stream::enqueue_barrier(const std::vector<event::ptr>& deps) {
+ OPENVINO_ASSERT(deps.empty(), "sycl_stream::enqueue_barrier implements only global barrier");
try {
_command_queue.ext_oneapi_submit_barrier();
} catch (::sycl::exception const& err) {
diff --git a/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.hpp b/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.hpp
index 269bc83c3db..8aaed6c52f9 100644
--- a/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.hpp
+++ b/src/plugins/intel_gpu/src/runtime/sycl/sycl_stream.hpp
@@ -46,7 +46,7 @@ public:
event::ptr enqueue_marker(std::vector<event::ptr> const& deps, bool is_output) override;
event::ptr group_events(std::vector<event::ptr> const& deps) override;
void wait_for_events(const std::vector<event::ptr>& events) override;
- void enqueue_barrier() override;
+ void enqueue_barrier(const std::vector<event::ptr>& deps) override;
event::ptr create_user_event(bool set) override;
event::ptr create_base_event() override;
event::ptr create_base_event(::sycl::event& event);
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_base_event.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_base_event.hpp
index 44449514c10..e9bfe7737bc 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_base_event.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_base_event.hpp
@@ -5,8 +5,8 @@
#pragma once
#include "intel_gpu/runtime/event.hpp"
-#include "ze_base_event_factory.hpp"
#include "ze_common.hpp"
+#include "ze_command_recorder.hpp"
#include <chrono>
#include <optional>
@@ -22,12 +22,45 @@ public:
, m_queue_stamp(queue_stamp) { }
uint64_t get_queue_stamp() const { return m_queue_stamp; }
void set_queue_stamp(uint64_t val) { m_queue_stamp = val; }
+ void set_command_recorder(ze_command_recorder::ptr recorder) { m_command_recorder = recorder; }
virtual ze_event_handle_t get_handle() const = 0;
virtual std::optional<ze_kernel_timestamp_result_t> query_timestamp() = 0;
+ /// @brief Retrieve valid Level Zero handles from a list of events.
+ /// @param events A vector of event pointers to check.
+ /// @param expect_handles If true, the function will throw an exception if any event does not have a valid handle.
+ /// @note This function assumes all events derive from ze_base_event and performs unsafe cast to avoid RTTI.
+ /// @return A vector of valid Level Zero event handles.
+ static std::vector<ze_event_handle_t> get_event_handles(const std::vector<event::ptr>& events, bool expect_handles = false) {
+ std::vector<ze_event_handle_t> handles;
+ for (auto& ev : events) {
+ if (!ev) continue; // Discard null event pointers
+ auto handle = static_cast<ze_base_event*>(ev.get())->get_handle();
+ if (handle != nullptr) {
+ handles.push_back(handle);
+ } else if (expect_handles) {
+ OPENVINO_THROW("Expected a valid event object to have a valid Level Zero handle");
+ }
+ }
+ return handles;
+ }
+
protected:
uint64_t m_queue_stamp = 0;
+ ze_command_recorder::ptr m_command_recorder = nullptr;
+
+ void stop_recording() {
+ if (m_command_recorder && m_command_recorder->stop_recording() != nullptr) {
+ GPU_DEBUG_TRACE << "[REC] Recording interrupted by event::wait" << std::endl;
+ }
+ }
+
+ void wait_impl() override final {
+ stop_recording();
+ ze_wait_impl();
+ }
+ virtual void ze_wait_impl() = 0;
static std::chrono::nanoseconds timestamp_to_duration(const device_info &info, const ze_kernel_timestamp_data_t& timestamp) {
constexpr double NS_IN_SEC = 1000000000.0;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_base_event_factory.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_base_event_factory.hpp
index cbcd3886042..0829b9b182c 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_base_event_factory.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_base_event_factory.hpp
@@ -7,19 +7,23 @@
#include "ze_engine.hpp"
#include "intel_gpu/runtime/event.hpp"
+#include <memory>
+
namespace cldnn {
namespace ze {
+struct ze_base_event;
+
// Interface for creating Level Zero events
struct ze_base_event_factory {
public:
- ze_base_event_factory(const ze_engine &engine, bool enable_profiling)
- : m_engine(engine), m_profiling_enabled(enable_profiling) {}
+ ze_base_event_factory(const ze_engine &ze_engine, bool enable_profiling)
+ : m_engine(ze_engine), m_profiling_enabled(enable_profiling) {}
const ze_engine& get_engine() const { return m_engine; }
bool is_profiling_enabled() const { return m_profiling_enabled; }
virtual ~ze_base_event_factory() {}
- virtual event::ptr create_event(uint64_t queue_stamp) = 0;
+ virtual std::shared_ptr<ze_base_event> create_event(uint64_t queue_stamp) = 0;
protected:
const ze_engine& m_engine;
const bool m_profiling_enabled;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.cpp
new file mode 100644
index 00000000000..4020dfdd74f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.cpp
@@ -0,0 +1,91 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "ze_command_list.hpp"
+#include "ze_stream.hpp"
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+# include <oneapi/dnnl/dnnl_ze.hpp>
+#endif
+
+namespace cldnn::ze {
+ze_command_list::ze_command_list(ze_stream& ze_stream, QueueTypes queue_type)
+ : _stream(ze_stream)
+ ,_queue_type(queue_type) {
+ const auto& engine = ze_stream.get_engine();
+ const auto& info = engine.get_device_info();
+ auto ctx_handle = engine.get_context().handle();
+ auto device_handle = engine.get_device().handle();
+
+ ze_command_list_flags_t flags = queue_type == QueueTypes::out_of_order ? 0 : ZE_COMMAND_LIST_FLAG_IN_ORDER;
+ ze_command_list_desc_t command_list_desc = {ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC,
+ nullptr,
+ info.compute_queue_group_ordinal,
+ flags};
+ ze_command_list_handle_t cmd_list_handle = nullptr;
+ OV_ZE_EXPECT(ze::zeCommandListCreate(ctx_handle, device_handle, &command_list_desc, &cmd_list_handle));
+
+ _cmd_list = ze_command_list_resource(cmd_list_handle);
+}
+
+ze_command_list::~ze_command_list() {
+ if (_status == command_list_status::enqueued) {
+ wait();
+ }
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ // Destroy OneDNN stream before dropping command list
+ _onednn_stream.reset();
+#endif
+ _cmd_list.drop();
+}
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+dnnl::stream& ze_command_list::get_onednn_stream() {
+ const auto& engine = _stream.get_engine();
+ OPENVINO_ASSERT(_queue_type == QueueTypes::in_order,
+ "[GPU] Can't create onednn stream handle as onednn doesn't support out-of-order queue");
+ OPENVINO_ASSERT(engine.get_device_info().vendor_id == INTEL_VENDOR_ID,
+ "[GPU] Can't create onednn stream handle as for non-Intel devices");
+ if (!_onednn_stream) {
+ // Pass command list to OneDNN so that OneDNN can append their kernels.
+ _onednn_stream =
+ std::make_shared<dnnl::stream>(dnnl::ze_interop::make_stream(engine.get_onednn_engine(),
+ _cmd_list.handle(),
+ _stream.is_profiling_enabled()));
+ }
+
+ return *_onednn_stream;
+}
+#endif
+
+void ze_command_list::reset_impl() {
+ OV_ZE_EXPECT(ze::zeCommandListReset(_cmd_list.handle()));
+}
+
+void ze_command_list::close_impl() {
+ OV_ZE_EXPECT(ze::zeCommandListClose(_cmd_list.handle()));
+}
+
+void ze_command_list::enqueue_impl() {
+ // Regular command lists (_cmd_list) only records GPU commands - they do not submit work to hardware directly.
+ // ze_stream owns an immediate command list (imm_cmd_list), which acts as the active submission handle connected directly to the GPU execution queue.
+ // This function uses zeCommandListImmediateAppendCommandListsWithParameters to append the fully-recorded batch of commands (_cmd_list)
+ // into the stream's immediate command list, submitting all recorded work to the GPU for execution in a single call.
+ auto& ze_stream = _stream;
+ ze_command_list_handle_t imm_cmd_list = ze_stream.get_immediate_command_list().handle();
+ ze_command_list_handle_t enqueued_cmd_list = _cmd_list.handle();
+ auto event = std::static_pointer_cast<ze_base_event>(ze_stream.create_base_event());
+ auto event_handle = event->get_handle();
+ OV_ZE_EXPECT(zeCommandListImmediateAppendCommandListsWithParameters(imm_cmd_list, 1, &enqueued_cmd_list, nullptr, event_handle, 0, nullptr));
+ _event = event;
+}
+
+void ze_command_list::wait_impl() {
+ if (_event) {
+ _event->wait();
+ _event = nullptr;
+ }
+}
+
+} // namespace cldnn::ze
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.hpp
new file mode 100644
index 00000000000..5914c9cbfcd
--- /dev/null
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_command_list.hpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "intel_gpu/runtime/command_list.hpp"
+#include "ze_common.hpp"
+#include "ze_resource.hpp"
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+# include <oneapi/dnnl/dnnl.hpp>
+#endif
+
+namespace cldnn::ze {
+struct ze_base_event;
+class ze_stream;
+class ze_command_list : public command_list {
+public:
+ using ptr = std::shared_ptr<ze_command_list>;
+ ze_command_list(ze_stream& ze_stream, QueueTypes queue_type);
+ // Cloning command list is experimental Level Zero API
+ ze_command_list(const ze_command_list& other) = delete;
+ ~ze_command_list();
+
+ ze_command_list_resource resource() const { return _cmd_list; }
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ dnnl::stream& get_onednn_stream();
+#endif
+protected:
+ void reset_impl() override;
+ void close_impl() override;
+ void enqueue_impl() override;
+ void wait_impl() override;
+
+private:
+ ze_stream& _stream;
+ ze_command_list_resource _cmd_list;
+ std::shared_ptr<ze_base_event> _event = nullptr;
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ std::shared_ptr<dnnl::stream> _onednn_stream = nullptr;
+#endif
+ QueueTypes _queue_type;
+};
+
+} // namespace cldnn::ze
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.cpp
new file mode 100644
index 00000000000..bdf727e81b2
--- /dev/null
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.cpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "ze_command_recorder.hpp"
+#include "ze_stream.hpp"
+#include "ze_command_list.hpp"
+
+namespace cldnn::ze {
+
+ze_command_recorder::ze_command_recorder(ze_stream& stream)
+ : _stream(stream) {}
+
+command_list::ptr ze_command_recorder::create_command_list() const {
+ return std::make_shared<ze_command_list>(_stream, _stream.get_queue_type());
+}
+
+} // namespace cldnn::ze
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.hpp
new file mode 100644
index 00000000000..e3f5e2dd038
--- /dev/null
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_command_recorder.hpp
@@ -0,0 +1,20 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "intel_gpu/runtime/command_recorder.hpp"
+
+namespace cldnn::ze {
+class ze_stream;
+class ze_command_recorder : public command_recorder {
+public:
+ explicit ze_command_recorder(ze_stream& stream);
+
+ command_list::ptr create_command_list() const override;
+protected:
+ ze_stream& _stream;
+};
+
+} // namespace cldnn::ze
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.cpp
index 31735aa0133..8752bb3b149 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.cpp
@@ -4,6 +4,7 @@
#include "ze_counter_based_event.hpp"
#include "ze/ze_common.hpp"
+#include "ze_base_event_factory.hpp"
#include <cassert>
#include <chrono>
@@ -12,7 +13,7 @@
using namespace cldnn;
using namespace ze;
-void ze_counter_based_event::wait_impl() {
+void ze_counter_based_event::ze_wait_impl() {
OV_ZE_EXPECT(ze::zeEventHostSynchronize(m_event.handle(), endless_wait));
}
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.hpp
index aa17f3f9e9f..c723ab5dc83 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event.hpp
@@ -9,7 +9,7 @@
namespace cldnn {
namespace ze {
-
+struct ze_base_event_factory;
// ze counter based event.
// Signaled state is inferred from the number of tasks completed on device.
@@ -25,7 +25,7 @@ public:
OPENVINO_ASSERT(!m_event.is_empty(), "[GPU] Attempt to create counter based event with empty holder");
}
- void wait_impl() override;
+ void ze_wait_impl() override;
void set_impl() override;
bool is_set_impl() override;
ze_event_handle_t get_handle() const override;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.cpp
index f64fe9dbebb..bf1b71b1f0c 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.cpp
@@ -23,20 +23,22 @@ namespace {
}
}
-ze_counter_based_event_factory::ze_counter_based_event_factory(const ze_engine &engine, bool enable_profiling)
- : ze_base_event_factory(engine, enable_profiling) {
- std::call_once(counter_based_ev_init_flag, find_function_address, engine.get_driver().handle());
+ze_counter_based_event_factory::ze_counter_based_event_factory(const ze_engine &ze_engine, bool enable_profiling)
+ : ze_base_event_factory(ze_engine, enable_profiling) {
+ auto driver_handle = ze_engine.get_driver().handle();
+ std::call_once(counter_based_ev_init_flag, find_function_address, driver_handle);
}
-event::ptr ze_counter_based_event_factory::create_event(uint64_t queue_stamp) {
+std::shared_ptr<ze_base_event> ze_counter_based_event_factory::create_event(uint64_t queue_stamp) {
std::lock_guard<std::mutex> lock(_mutex);
+ const auto &engine = get_engine();
ze_event_handle_t event;
auto desc = defaultIntelCounterBasedEventDesc;
if (is_profiling_enabled()) {
desc.flags |= ZEX_COUNTER_BASED_EVENT_FLAG_KERNEL_TIMESTAMP;
}
- OV_ZE_EXPECT(func_zexCounterBasedEventCreate2(m_engine.get_context().handle(), m_engine.get_device().handle(), &desc, &event));
+ OV_ZE_EXPECT(func_zexCounterBasedEventCreate2(engine.get_context().handle(), engine.get_device().handle(), &desc, &event));
auto ev_holder = ze_event_resource(event);
auto cb_event = std::make_shared<ze_counter_based_event>(queue_stamp, *this, ev_holder);
return cb_event;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.hpp
index 4b080e422a3..2b6f240e258 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_counter_based_event_factory.hpp
@@ -15,8 +15,8 @@ namespace ze {
// Should only be used with in-order queue
struct ze_counter_based_event_factory : public ze_base_event_factory {
public:
- ze_counter_based_event_factory(const ze_engine &engine, bool enable_profiling);
- event::ptr create_event(uint64_t queue_stamp) override;
+ ze_counter_based_event_factory(const ze_engine &ze_engine, bool enable_profiling);
+ std::shared_ptr<ze_base_event> create_event(uint64_t queue_stamp) override;
protected:
std::mutex _mutex;
};
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_empty_event.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_empty_event.hpp
index 57c829de769..66fb70f49c5 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_empty_event.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_empty_event.hpp
@@ -17,7 +17,7 @@ public:
ze_empty_event(uint64_t queue_stamp)
: ze_base_event(queue_stamp) { }
- void wait_impl() override { }
+ void ze_wait_impl() override { }
void set_impl() override { }
bool is_set_impl() override { return true; }
ze_event_handle_t get_handle() const override { return nullptr; }
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_event.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_event.cpp
index b4b1e3d1aa6..b0afafb6fe5 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_event.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_event.cpp
@@ -4,6 +4,7 @@
#include "ze_event.hpp"
#include "ze/ze_common.hpp"
+#include "ze_base_event_factory.hpp"
#include <cassert>
#include <chrono>
@@ -17,7 +18,7 @@ void ze_event::reset() {
OV_ZE_EXPECT(ze::zeEventHostReset(m_event.handle()));
}
-void ze_event::wait_impl() {
+void ze_event::ze_wait_impl() {
OV_ZE_EXPECT(ze::zeEventHostSynchronize(m_event.handle(), endless_wait));
}
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_event.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_event.hpp
index 3383e1f0e0e..0c31c9d559f 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_event.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_event.hpp
@@ -9,6 +9,7 @@
namespace cldnn {
namespace ze {
+struct ze_base_event_factory;
// ZE event. Can be either in signaled state or not signaled state.
struct ze_event : public ze_base_event {
@@ -28,7 +29,7 @@ public:
bool get_profiling_info_impl(std::list<instrumentation::profiling_interval>& info) override;
protected:
- void wait_impl() override;
+ void ze_wait_impl() override;
void set_impl() override;
bool is_set_impl() override;
// TODO: Implement add_event_handler_impl
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.cpp
index 10cd41d3083..3ffbd70c907 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.cpp
@@ -11,12 +11,12 @@
using namespace cldnn;
using namespace ze;
-ze_event_factory::ze_event_factory(const ze_engine &engine, bool enable_profiling, uint32_t capacity)
-: ze_base_event_factory(engine, enable_profiling)
+ze_event_factory::ze_event_factory(const ze_engine &ze_engine, bool enable_profiling, uint32_t capacity)
+: ze_base_event_factory(ze_engine, enable_profiling)
, m_capacity(capacity)
, m_num_used(0) { }
-event::ptr ze_event_factory::create_event(uint64_t queue_stamp) {
+std::shared_ptr<ze_base_event> ze_event_factory::create_event(uint64_t queue_stamp) {
std::lock_guard<std::mutex> lock(_mutex);
if (m_num_used >= m_capacity || m_current_pool.is_empty()) {
@@ -29,8 +29,9 @@ event::ptr ze_event_factory::create_event(uint64_t queue_stamp) {
flags,
m_capacity
};
- auto ctx_handle = m_engine.get_context().handle();
- auto device_handle = m_engine.get_device().handle();
+ const auto &engine = get_engine();
+ auto ctx_handle = engine.get_context().handle();
+ auto device_handle = engine.get_device().handle();
ze_event_pool_handle_t event_pool;
OV_ZE_EXPECT(ze::zeEventPoolCreate(ctx_handle, &event_pool_desc, 1, &device_handle, &event_pool));
m_current_pool = ze_event_pool_resource{event_pool};
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.hpp
index 51dd197a862..4525b048500 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_event_factory.hpp
@@ -15,8 +15,8 @@ namespace ze {
// Interface for creating ze events using event pools
struct ze_event_factory : public ze_base_event_factory {
public:
- ze_event_factory(const ze_engine &engine, bool enable_profiling, uint32_t capacity = 255);
- event::ptr create_event(uint64_t queue_stamp) override;
+ ze_event_factory(const ze_engine &ze_engine, bool enable_profiling, uint32_t capacity = 255);
+ std::shared_ptr<ze_base_event> create_event(uint64_t queue_stamp) override;
protected:
std::mutex _mutex;
ze_event_pool_resource m_current_pool;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_events.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_events.cpp
index 98b3ef8ff7a..b412efe1ff7 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_events.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_events.cpp
@@ -13,7 +13,7 @@
using namespace cldnn;
using namespace ze;
-void ze_events::wait_impl() {
+void ze_events::ze_wait_impl() {
if (_last_ze_event) {
OV_ZE_EXPECT(ze::zeEventHostSynchronize(_last_ze_event, endless_wait));
}
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_events.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_events.hpp
index 2dd04bd8ad0..f7165b23a03 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_events.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_events.hpp
@@ -30,7 +30,7 @@ public:
bool get_profiling_info_impl(std::list<instrumentation::profiling_interval>& info) override;
protected:
- void wait_impl() override;
+ void ze_wait_impl() override;
void set_impl() override;
bool is_set_impl() override;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_memory.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_memory.cpp
index 01d02fb653e..cea7cf8573d 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_memory.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_memory.cpp
@@ -319,8 +319,7 @@ allocation_type gpu_usm::detect_allocation_type(const ze_engine* engine, ze_usm_
}
gpu_usm::gpu_usm(ze_engine* engine, const layout& new_layout, ze_usm_resource buffer, allocation_type type, std::shared_ptr<MemoryTracker> mem_tracker)
- : lockable_gpu_mem()
- , memory(engine, new_layout, type, mem_tracker)
+ : lockable_gpu_mem(engine, new_layout, type, mem_tracker)
, _buffer(std::move(buffer)) {
auto ctx_handle = engine->get_context().handle();
auto ptr = _buffer.handle().ptr;
@@ -333,8 +332,7 @@ gpu_usm::gpu_usm(ze_engine* engine, const layout& new_layout, ze_usm_resource bu
: gpu_usm(engine, new_layout, std::move(buffer), detect_allocation_type(engine, buffer), mem_tracker) {}
gpu_usm::gpu_usm(ze_engine* engine, const layout& layout, allocation_type type)
- : lockable_gpu_mem()
- , memory(engine, layout, type, nullptr) {
+ : lockable_gpu_mem(engine, layout, type, nullptr) {
auto actual_bytes_count = _bytes_count;
if (actual_bytes_count == 0)
actual_bytes_count = 1;
@@ -358,7 +356,7 @@ gpu_usm::gpu_usm(ze_engine* engine, const layout& layout, allocation_type type)
m_mem_tracker = std::make_shared<MemoryTracker>(engine, _buffer.handle().ptr, actual_bytes_count, type);
}
-void* gpu_usm::lock(const stream& stream, mem_lock_type type) {
+void* gpu_usm::lock_impl(const stream& stream, mem_lock_type type) {
std::lock_guard<std::mutex> locker(_mutex);
if (0 == _lock_count) {
auto& _ze_stream = downcast<const ze_stream>(stream);
@@ -369,14 +367,14 @@ void* gpu_usm::lock(const stream& stream, mem_lock_type type) {
_host_buffer = allocate_usm_host(zero_engine->get_context(), _bytes_count);
// Always copy device data to host buffer (treat write as read_write internally).
// This ensures the host buffer always has valid data, making nested locks safe.
- OV_ZE_EXPECT(zeCommandListAppendMemoryCopy(_ze_stream.get_queue(),
+ OV_ZE_EXPECT(zeCommandListAppendMemoryCopy(_ze_stream.get_command_list().handle(),
_host_buffer.handle().ptr,
_buffer.handle().ptr,
_bytes_count,
nullptr,
0,
nullptr));
- OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(_ze_stream.get_queue(), endless_wait));
+ OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(_ze_stream.get_command_list().handle(), endless_wait));
_mapped_ptr = _host_buffer.handle().ptr;
} else {
_mapped_ptr = _buffer.handle().ptr;
@@ -397,14 +395,14 @@ void gpu_usm::unlock(const stream& stream) {
if (0 == _lock_count) {
if (_copy_back_to_device) {
auto& _ze_stream = downcast<const ze_stream>(stream);
- OV_ZE_EXPECT(zeCommandListAppendMemoryCopy(_ze_stream.get_queue(),
+ OV_ZE_EXPECT(zeCommandListAppendMemoryCopy(_ze_stream.get_command_list().handle(),
_buffer.handle().ptr,
_host_buffer.handle().ptr,
_bytes_count,
nullptr,
0,
nullptr));
- OV_ZE_EXPECT(zeCommandListHostSynchronize(_ze_stream.get_queue(), endless_wait));
+ OV_ZE_EXPECT(zeCommandListHostSynchronize(_ze_stream.get_command_list().handle(), endless_wait));
}
_copy_back_to_device = false;
_host_buffer.drop();
@@ -425,7 +423,7 @@ event::ptr gpu_usm::fill(stream& stream, unsigned char pattern, const std::vecto
auto ev_ze = downcast<ze::ze_base_event>(ev.get())->get_handle();
auto ze_dep_events = get_ze_events(dep_events);
const auto num_ze_dep_events = static_cast<uint32_t>(ze_dep_events.size());
- OV_ZE_EXPECT(ze::zeCommandListAppendMemoryFill(_ze_stream.get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendMemoryFill(_ze_stream.get_command_list().handle(),
_buffer.handle().ptr,
&pattern,
sizeof(unsigned char),
@@ -454,7 +452,7 @@ event::ptr gpu_usm::copy_from(stream& stream, const void* data_ptr, size_t src_o
auto src_ptr = reinterpret_cast<const char*>(data_ptr) + src_offset;
auto dst_ptr = reinterpret_cast<char*>(_buffer.handle().ptr) + dst_offset;
- OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_command_list().handle(),
dst_ptr,
src_ptr,
size,
@@ -484,7 +482,7 @@ event::ptr gpu_usm::copy_from(stream& stream, const memory& src_mem, size_t src_
auto src_ptr = reinterpret_cast<const char*>(usm_mem->buffer_ptr()) + src_offset;
auto dst_ptr = reinterpret_cast<char*>(_buffer.handle().ptr) + dst_offset;
- OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_command_list().handle(),
dst_ptr,
src_ptr,
size,
@@ -509,7 +507,7 @@ event::ptr gpu_usm::copy_to(stream& stream, void* data_ptr, size_t src_offset, s
auto src_ptr = reinterpret_cast<const char*>(buffer_ptr()) + src_offset;
auto dst_ptr = reinterpret_cast<char*>(data_ptr) + dst_offset;
- OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendMemoryCopy(_ze_stream->get_command_list().handle(),
dst_ptr,
src_ptr,
size,
@@ -581,8 +579,7 @@ shared_mem_params gpu_usm::get_internal_params(runtime_types rt_type) const {
}
gpu_image2d::gpu_image2d(ze_engine* engine, const layout& layout)
- : lockable_gpu_mem()
- , memory(engine, layout, allocation_type::ze_image, nullptr)
+ : lockable_gpu_mem(engine, layout, allocation_type::ze_image, nullptr)
, _width(0)
, _height(0) {
ze_image_desc_t image_desc = {};
@@ -681,14 +678,13 @@ gpu_image2d::gpu_image2d(ze_engine* engine, const layout& layout)
}
gpu_image2d::gpu_image2d(ze_engine* engine, const layout& new_layout, ze_image_resource image, std::shared_ptr<MemoryTracker> mem_tracker)
- : lockable_gpu_mem()
- , memory(engine, new_layout, allocation_type::ze_image, mem_tracker)
+ : lockable_gpu_mem(engine, new_layout, allocation_type::ze_image, mem_tracker)
, _image_holder(std::move(image)) {
// No way to get width and height from Level Zero so we have to assume layout is correct
std::tie(_width, _height) = get_width_height(new_layout);
}
-void* gpu_image2d::lock(const stream& stream, mem_lock_type type) {
+void* gpu_image2d::lock_impl(const stream& stream, mem_lock_type type) {
auto& zero_stream = downcast<const ze_stream>(stream);
std::lock_guard<std::mutex> locker(_mutex);
if (0 == _lock_count) {
@@ -700,7 +696,7 @@ void* gpu_image2d::lock(const stream& stream, mem_lock_type type) {
auto *zero_engine = downcast<ze_engine>(_engine);
_host_buffer = allocate_usm_host(zero_engine->get_context(), _bytes_count);
if (type != mem_lock_type::write) {
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyToMemory(zero_stream.get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyToMemory(zero_stream.get_command_list().handle(),
_host_buffer.handle().ptr,
_image_holder.handle(),
nullptr,
@@ -708,7 +704,7 @@ void* gpu_image2d::lock(const stream& stream, mem_lock_type type) {
0,
nullptr));
// Block thread and wait for copy and previous operations to finish
- OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(zero_stream.get_queue(), endless_wait));
+ OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(zero_stream.get_command_list().handle(), endless_wait));
}
_mapped_ptr = _host_buffer.handle().ptr;
}
@@ -724,7 +720,7 @@ void gpu_image2d::unlock(const stream& stream) {
if (0 == _lock_count) {
if (_needs_write_back) {
auto& zero_stream = downcast<const ze_stream>(stream);
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream.get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream.get_command_list().handle(),
_image_holder.handle(),
_host_buffer.handle().ptr,
nullptr,
@@ -732,7 +728,7 @@ void gpu_image2d::unlock(const stream& stream) {
0,
nullptr));
// Insert barrier to ensure that following commands have correct image data
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(zero_stream.get_queue(), nullptr, 0, nullptr));
+ OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(zero_stream.get_command_list().handle(), nullptr, 0, nullptr));
}
_host_buffer.drop();
_mapped_ptr = nullptr;
@@ -756,7 +752,7 @@ event::ptr gpu_image2d::fill(stream& stream, unsigned char pattern, const std::v
auto mem_ordinal = zero_stream.get_engine().get_device_info().device_memory_ordinal;
ze_usm_resource fill_buffer = allocate_usm_device(context, device, _bytes_count, mem_ordinal);
- OV_ZE_EXPECT(ze::zeCommandListAppendMemoryFill(zero_stream.get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendMemoryFill(zero_stream.get_command_list().handle(),
fill_buffer.handle().ptr,
&pattern,
sizeof(unsigned char),
@@ -765,7 +761,7 @@ event::ptr gpu_image2d::fill(stream& stream, unsigned char pattern, const std::v
0,
nullptr));
auto ev_result_handle = downcast<ze::ze_base_event>(result_event.get())->get_handle();
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream.get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream.get_command_list().handle(),
_image_holder.handle(),
fill_buffer.handle().ptr,
nullptr,
@@ -829,7 +825,7 @@ event::ptr gpu_image2d::copy_from(stream& stream, const void* data_ptr, size_t s
auto src_ptr = reinterpret_cast<const char*>(data_ptr) + src_offset;
auto ev_result_handle = downcast<ze::ze_base_event>(result_event.get())->get_handle();
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyFromMemory(zero_stream->get_command_list().handle(),
_image_holder.handle(),
src_ptr,
nullptr,
@@ -854,7 +850,7 @@ event::ptr gpu_image2d::copy_from(stream& stream, const memory& src_mem, size_t
auto zero_stream = downcast<ze_stream>(&stream);
auto src_image = downcast<const gpu_image2d>(&src_mem);
auto ev_result_handle = downcast<ze::ze_base_event>(result_event.get())->get_handle();
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopy(zero_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopy(zero_stream->get_command_list().handle(),
_image_holder.handle(),
src_image->_image_holder.handle(),
ev_result_handle,
@@ -876,7 +872,7 @@ event::ptr gpu_image2d::copy_to(stream& stream, void* data_ptr, size_t src_offse
auto zero_stream = downcast<ze_stream>(&stream);
auto dst_ptr = reinterpret_cast<char*>(data_ptr) + dst_offset;
auto ev_result_handle = downcast<ze::ze_base_event>(result_event.get())->get_handle();
- OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyToMemory(zero_stream->get_queue(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendImageCopyToMemory(zero_stream->get_command_list().handle(),
dst_ptr,
_image_holder.handle(),
nullptr,
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_memory.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_memory.hpp
index 15826f35c7f..867f1ab0873 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_memory.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_memory.hpp
@@ -21,24 +21,33 @@ class SharedSurfLock;
namespace cldnn {
namespace ze {
-struct lockable_gpu_mem {
- lockable_gpu_mem() :
+struct lockable_gpu_mem : public memory {
+ lockable_gpu_mem(engine* engine, const layout& layout, allocation_type type, std::shared_ptr<MemoryTracker> mem_tracker) :
+ memory(engine, layout, type, mem_tracker),
_lock_count(0),
_mapped_ptr(nullptr),
_copy_back_to_device(false) {}
+ void* lock(const stream& stream, mem_lock_type type) override final {
+ if (stream.get_recorder()->stop_recording()) {
+ GPU_DEBUG_TRACE << "[REC] Recording interrupted by memory::lock" << std::endl;
+ }
+ return lock_impl(stream, type);
+ }
+protected:
+ virtual void* lock_impl(const stream& stream, mem_lock_type type) = 0;
+
std::mutex _mutex;
unsigned _lock_count;
void* _mapped_ptr;
bool _copy_back_to_device;
};
-struct gpu_usm : public lockable_gpu_mem, public memory {
+struct gpu_usm : public lockable_gpu_mem{
gpu_usm(ze_engine* engine, const layout& new_layout, ze_usm_resource usm_buffer, allocation_type type, std::shared_ptr<MemoryTracker> mem_tracker);
gpu_usm(ze_engine* engine, const layout& new_layout, ze_usm_resource usm_buffer, std::shared_ptr<MemoryTracker> mem_tracker);
gpu_usm(ze_engine* engine, const layout& layout, allocation_type type);
- void* lock(const stream& stream, mem_lock_type type) override;
void unlock(const stream& stream) override;
event::ptr fill(stream& stream, unsigned char pattern, const std::vector<event::ptr>& dep_events = {}, bool blocking = true) override;
@@ -59,15 +68,16 @@ struct gpu_usm : public lockable_gpu_mem, public memory {
static allocation_type detect_allocation_type(const ze_engine* engine, ze_usm_resource buffer);
protected:
+ void* lock_impl(const stream& stream, mem_lock_type type) override;
+
mutable ze_usm_resource _buffer;
ze_usm_resource _host_buffer;
};
-struct gpu_image2d : public lockable_gpu_mem, public memory {
+struct gpu_image2d : public lockable_gpu_mem {
gpu_image2d(ze_engine* engine, const layout& new_layout, ze_image_resource image, std::shared_ptr<MemoryTracker> mem_tracker);
gpu_image2d(ze_engine* engine, const layout& layout);
- void* lock(const stream& stream, mem_lock_type type = mem_lock_type::read_write) override;
void unlock(const stream& stream) override;
event::ptr fill(stream& stream, unsigned char pattern, const std::vector<event::ptr>& dep_events = {}, bool blocking = true) override;
shared_mem_params get_internal_params(runtime_types rt_type) const override;
@@ -82,6 +92,8 @@ struct gpu_image2d : public lockable_gpu_mem, public memory {
event::ptr copy_to(stream& stream, void* data_ptr, size_t src_offset = 0, size_t dst_offset = 0, size_t size = 0, bool blocking = true) const override;
protected:
+ void* lock_impl(const stream& stream, mem_lock_type type) override;
+
mutable ze_image_resource _image_holder;
ze_usm_resource _host_buffer;
size_t _width;
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_stream.cpp b/src/plugins/intel_gpu/src/runtime/ze/ze_stream.cpp
index 8830b595e10..14e46fea4da 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_stream.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_stream.cpp
@@ -18,6 +18,8 @@
#include "ze_kernel.hpp"
#include "ze_memory.hpp"
#include "ze_common.hpp"
+#include "ze_command_list.hpp"
+#include "ze_command_recorder.hpp"
#include "compute_runtime/ze_intel_gpu.h"
#include "compute_runtime/ze_stypes.h"
@@ -237,7 +239,7 @@ ze_stream::ze_stream(const ze_engine &engine, const ExecutionConfig& config)
auto device_handle = engine.get_device().handle();
ze_command_list_handle_t cmd_list = nullptr;
OV_ZE_EXPECT(ze::zeCommandListCreateImmediate(ctx_handle, device_handle, &command_queue_desc, &cmd_list));
- m_cmd_list = ze_command_list_resource(cmd_list);
+ m_imm_cmd_list = ze_command_list_resource(cmd_list);
bool use_counter_based_events = m_queue_type == QueueTypes::in_order && info.supports_counter_based_events;
@@ -247,9 +249,13 @@ ze_stream::ze_stream(const ze_engine &engine, const ExecutionConfig& config)
use_counter_based_events = false;
}
- m_user_ev_factory = std::make_shared<ze_event_factory>(engine, config.get_enable_profiling());
+ // Passing reference to not fully formed object is safe here because ze_command_recorder does not call virtual methods for stream
+ m_recorder = std::make_shared<ze_command_recorder>(*this);
+
+ auto profiling_enabled = config.get_enable_profiling();
+ m_user_ev_factory = std::make_shared<ze_event_factory>(engine, profiling_enabled);
if (use_counter_based_events) {
- m_ev_factory = std::make_shared<ze_counter_based_event_factory>(engine, config.get_enable_profiling());
+ m_ev_factory = std::make_shared<ze_counter_based_event_factory>(engine, profiling_enabled);
} else {
// If counter based events are not supported or not used, use the same factory for both user and base events
m_ev_factory = m_user_ev_factory;
@@ -264,13 +270,17 @@ ze_stream::ze_stream(const ze_engine &engine, const ExecutionConfig& config)
ze_stream::ze_stream(const ze_engine& engine, const ExecutionConfig& config, ze_command_list_resource cmd_list)
: stream(detect_queue_type(cmd_list), stream::get_expected_sync_method(config))
, _engine(engine)
- , m_cmd_list(std::move(cmd_list)) {
+ , m_imm_cmd_list(std::move(cmd_list)) {
const auto &info = engine.get_device_info();
bool use_counter_based_events = m_queue_type == QueueTypes::in_order && info.supports_counter_based_events;
+ auto profiling_enabled = config.get_enable_profiling();
+
+ // Passing reference to not fully formed object is safe here because ze_command_recorder does not call virtual methods for stream
+ m_recorder = std::make_shared<ze_command_recorder>(*this);
- m_user_ev_factory = std::make_shared<ze_event_factory>(engine, config.get_enable_profiling());
+ m_user_ev_factory = std::make_shared<ze_event_factory>(engine, profiling_enabled);
if (use_counter_based_events) {
- m_ev_factory = std::make_shared<ze_counter_based_event_factory>(engine, config.get_enable_profiling());
+ m_ev_factory = std::make_shared<ze_counter_based_event_factory>(engine, profiling_enabled);
} else {
m_ev_factory = m_user_ev_factory;
}
@@ -285,7 +295,7 @@ ze_stream::~ze_stream() {
// Destroy OneDNN stream before dropping command list
_onednn_stream.reset();
#endif
- m_cmd_list.drop();
+ m_imm_cmd_list.drop();
}
void ze_stream::set_arguments(kernel& kernel, const kernel_arguments_desc& args_desc, const kernel_arguments_data& args) {
@@ -309,15 +319,12 @@ event::ptr ze_stream::enqueue_kernel(kernel& kernel,
std::vector<ze_event_handle_t> dep_events;
std::vector<ze_event_handle_t>* dep_events_ptr = nullptr;
if (m_sync_method == SyncMethods::events) {
- for (auto& dep : deps) {
- if (auto ze_base_ev = std::dynamic_pointer_cast<ze_base_event>(dep)) {
- if (ze_base_ev->get_handle() != nullptr)
- dep_events.push_back(ze_base_ev->get_handle());
- }
+ dep_events = ze_base_event::get_event_handles(deps, true);
+ if (!dep_events.empty()) {
+ dep_events_ptr = &dep_events;
}
- dep_events_ptr = &dep_events;
} else if (m_sync_method == SyncMethods::barriers) {
- sync_events(deps, is_output);
+ sync_events(deps);
}
bool set_output_event = m_sync_method == SyncMethods::events || is_output;
@@ -326,7 +333,7 @@ event::ptr ze_stream::enqueue_kernel(kernel& kernel,
auto local = to_group_count(args_desc.workGroups.local);
ze_group_count_t args = { global.groupCountX / local.groupCountX, global.groupCountY / local.groupCountY, global.groupCountZ / local.groupCountZ };
OV_ZE_EXPECT(ze::zeKernelSetGroupSize(kern, local.groupCountX, local.groupCountY, local.groupCountZ));
- OV_ZE_EXPECT(ze::zeCommandListAppendLaunchKernel(m_cmd_list.handle(),
+ OV_ZE_EXPECT(ze::zeCommandListAppendLaunchKernel(get_command_list().handle(),
kern,
&args,
set_output_event ? std::dynamic_pointer_cast<ze_base_event>(ev)->get_handle() : nullptr,
@@ -336,41 +343,44 @@ event::ptr ze_stream::enqueue_kernel(kernel& kernel,
return ev;
}
-void ze_stream::enqueue_barrier() {
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(m_cmd_list.handle(), nullptr, 0, nullptr));
+void ze_stream::enqueue_barrier(const std::vector<event::ptr>& deps) {
+ if (deps.empty()) {
+ OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(get_command_list().handle(), nullptr, 0, nullptr));
+ } else {
+ auto handles = ze_base_event::get_event_handles(deps, true);
+ if (!handles.empty()) {
+ OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(get_command_list().handle(),
+ nullptr,
+ static_cast<uint32_t>(handles.size()),
+ handles.data()));
+ }
+ }
}
-event::ptr ze_stream::enqueue_marker(std::vector<ze_event::ptr> const& deps, bool is_output) {
+event::ptr ze_stream::enqueue_marker(std::vector<event::ptr> const& deps, bool is_output) {
+ // Implemented with barriers as there is no marker concept in Level Zero
+ auto ev = std::static_pointer_cast<ze_base_event>(create_base_event());
+ auto ev_handle = ev->get_handle();
+ auto cmd_list_handle = get_command_list().handle();
+
if (deps.empty()) {
- auto ev = create_base_event();
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(m_cmd_list.handle(), std::dynamic_pointer_cast<ze_base_event>(ev)->get_handle(), 0, nullptr));
+ // Wait for all previous commands
+ OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(cmd_list_handle, ev_handle, 0, nullptr));
return ev;
- }
-
- if (m_sync_method == SyncMethods::events) {
- std::vector<ze_event_handle_t> dep_events;
- for (auto& dep : deps) {
- if (auto ze_base_ev = std::dynamic_pointer_cast<ze_base_event>(dep)) {
- if (ze_base_ev->get_handle() != nullptr)
- dep_events.push_back(ze_base_ev->get_handle());
- }
+ } else if (m_sync_method == SyncMethods::events) {
+ auto dep_event_handles = ze_base_event::get_event_handles(deps, true);
+ if (!dep_event_handles.empty()) {
+ OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(cmd_list_handle, ev_handle, static_cast<uint32_t>(dep_event_handles.size()), dep_event_handles.data()));
+ } else {
+ OV_ZE_EXPECT(ze::zeCommandListAppendSignalEvent(cmd_list_handle, ev_handle));
}
- if (dep_events.empty())
- return create_user_event(true);
-
- auto ev = create_base_event();
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(m_cmd_list.handle(),
- std::dynamic_pointer_cast<ze_base_event>(ev)->get_handle(),
- static_cast<uint32_t>(dep_events.size()),
- &dep_events.front()));
- return ev;
} else if (m_sync_method == SyncMethods::barriers) {
- sync_events(deps, is_output);
- assert(m_last_barrier_ev != nullptr);
- return m_last_barrier_ev;
+ sync_events(deps);
+ OV_ZE_EXPECT(ze::zeCommandListAppendSignalEvent(cmd_list_handle, ev_handle));
} else {
- return create_user_event(true);
+ OV_ZE_EXPECT(ze::zeCommandListAppendSignalEvent(cmd_list_handle, ev_handle));
}
+ return ev;
}
ze_event::ptr ze_stream::group_events(std::vector<ze_event::ptr> const& deps) {
@@ -383,6 +393,7 @@ void ze_stream::wait() {
event::ptr ze_stream::create_user_event(bool set) {
auto ev = m_user_ev_factory->create_event(++m_queue_counter);
+ ev->set_command_recorder(get_recorder());
if (set)
ev->set();
@@ -390,7 +401,9 @@ event::ptr ze_stream::create_user_event(bool set) {
}
event::ptr ze_stream::create_base_event() {
- return m_ev_factory->create_event(++m_queue_counter);
+ auto ev = m_ev_factory->create_event(++m_queue_counter);
+ ev->set_command_recorder(get_recorder());
+ return ev;
}
std::unique_ptr<surfaces_lock> ze_stream::create_surfaces_lock(const std::vector<memory::ptr> &mem) const {
@@ -402,7 +415,10 @@ void ze_stream::flush() const {
}
void ze_stream::finish() const {
- OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(m_cmd_list.handle(), endless_wait));
+ if (get_recorder()->stop_recording()) {
+ GPU_DEBUG_TRACE << "[REC] Recording interrupted by stream::finish" << std::endl;
+ }
+ OV_ZE_EXPECT(ze::zeCommandListHostSynchronize(m_imm_cmd_list.handle(), endless_wait));
}
void ze_stream::wait_for_events(const std::vector<event::ptr>& events) {
@@ -423,31 +439,20 @@ void ze_stream::wait_for_events(const std::vector<event::ptr>& events) {
}
}
-void ze_stream::sync_events(std::vector<event::ptr> const& deps, bool is_output) {
+void ze_stream::sync_events(std::vector<event::ptr> const& deps) {
+ // Enqueue global barrier based on deps stamps
bool needs_barrier = false;
for (auto& dep : deps) {
- auto* ze_base_ev = dynamic_cast<ze_base_event*>(dep.get());
- assert(ze_base_ev != nullptr);
- if (ze_base_ev->get_queue_stamp() > m_last_barrier) {
+ auto stamp = static_cast<ze_base_event*>(dep.get())->get_queue_stamp();
+ if (stamp > m_last_barrier) {
needs_barrier = true;
+ break;
}
}
-
if (needs_barrier) {
- if (is_output) {
- m_last_barrier_ev = std::dynamic_pointer_cast<ze_event>(create_base_event());
- m_last_barrier_ev->set_queue_stamp(m_queue_counter.load());
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(m_cmd_list.handle(), m_last_barrier_ev->get_handle(), 0, nullptr));
- } else {
- OV_ZE_EXPECT(ze::zeCommandListAppendBarrier(m_cmd_list.handle(), nullptr, 0, nullptr));
- }
+ enqueue_barrier();
m_last_barrier = ++m_queue_counter;
}
-
- if (!m_last_barrier_ev) {
- m_last_barrier_ev = std::dynamic_pointer_cast<ze_event>(create_user_event(true));
- m_last_barrier_ev->set_queue_stamp(m_queue_counter.load());
- }
}
ze_context_resource ze_stream::get_context() const {
@@ -458,13 +463,27 @@ ze_context_resource ze_stream::get_context() const {
dnnl::stream& ze_stream::get_onednn_stream() {
OPENVINO_ASSERT(m_queue_type == QueueTypes::in_order, "[GPU] Can't create onednn stream handle as onednn doesn't support out-of-order queue");
OPENVINO_ASSERT(_engine.get_device_info().vendor_id == INTEL_VENDOR_ID, "[GPU] Can't create onednn stream handle as for non-Intel devices");
+ if (auto active_cmd_list = m_recorder->get_active_command_list()) {
+ return std::static_pointer_cast<ze_command_list>(active_cmd_list)->get_onednn_stream();
+ }
if (!_onednn_stream) {
- _onednn_stream = std::make_shared<dnnl::stream>(dnnl::ze_interop::make_stream(_engine.get_onednn_engine(), m_cmd_list.handle(), m_ev_factory->is_profiling_enabled()));
+ _onednn_stream = std::make_shared<dnnl::stream>(dnnl::ze_interop::make_stream(_engine.get_onednn_engine(), m_imm_cmd_list.handle(), is_profiling_enabled()));
}
return *_onednn_stream;
}
#endif
+command_recorder::ptr ze_stream::get_recorder() const {
+ return m_recorder;
+}
+
+ze_command_list_resource ze_stream::get_command_list() const {
+ if (auto active_cmd_list = m_recorder->get_active_command_list()) {
+ return std::static_pointer_cast<ze_command_list>(active_cmd_list)->resource();
+ }
+ return m_imm_cmd_list;
+}
+
} // namespace ze
} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/runtime/ze/ze_stream.hpp b/src/plugins/intel_gpu/src/runtime/ze/ze_stream.hpp
index 7791c97eb58..6619f6f3ab4 100644
--- a/src/plugins/intel_gpu/src/runtime/ze/ze_stream.hpp
+++ b/src/plugins/intel_gpu/src/runtime/ze/ze_stream.hpp
@@ -10,35 +10,24 @@
#include "ze_resource.hpp"
#include "ze_engine.hpp"
#include "ze_event.hpp"
+#include "ze_command_list.hpp"
#include "ze_base_event_factory.hpp"
+
namespace cldnn {
namespace ze {
+class ze_command_recorder;
class ze_stream : public stream {
public:
- ze_command_list_handle_t get_queue() const { return m_cmd_list.handle(); }
- const ze_engine& get_engine() const { return _engine; }
-
ze_stream(const ze_engine& engine, const ExecutionConfig& config);
ze_stream(const ze_engine& engine, const ExecutionConfig& config, ze_command_list_resource cmd_list);
- ze_stream(ze_stream&& other)
- : stream(other.m_queue_type, other.m_sync_method)
- , _engine(other._engine)
- , m_cmd_list(std::move(other.m_cmd_list))
- , m_queue_counter(other.m_queue_counter.load())
- , m_last_barrier(other.m_last_barrier.load())
- , m_last_barrier_ev(other.m_last_barrier_ev)
- , m_ev_factory(std::move(other.m_ev_factory))
- , m_user_ev_factory(std::move(other.m_user_ev_factory)) {
- }
-
+ ze_stream(const ze_stream& other) = delete;
~ze_stream();
void flush() const override;
void finish() const override;
void wait() override;
-
void set_arguments(kernel& kernel, const kernel_arguments_desc& args_desc, const kernel_arguments_data& args) override;
event::ptr enqueue_kernel(kernel& kernel,
const kernel_arguments_desc& args_desc,
@@ -48,31 +37,36 @@ public:
event::ptr enqueue_marker(std::vector<event::ptr> const& deps, bool is_output) override;
event::ptr group_events(std::vector<event::ptr> const& deps) override;
void wait_for_events(const std::vector<event::ptr>& events) override;
- void enqueue_barrier() override;
+ void enqueue_barrier(const std::vector<event::ptr>& deps = {}) override;
event::ptr create_user_event(bool set) override;
event::ptr create_base_event() override;
std::unique_ptr<surfaces_lock> create_surfaces_lock(const std::vector<memory::ptr> &mem) const override;
ze_context_resource get_context() const;
- ze_command_list_resource get_command_list() const { return m_cmd_list; }
-
#ifdef ENABLE_ONEDNN_FOR_GPU
dnnl::stream& get_onednn_stream() override;
#endif
+ command_recorder::ptr get_recorder() const override;
+
+ /// @brief Get the current command list.
+ /// @return Recorded command list if recording is in progress, otherwise the immediate command list.
+ ze_command_list_resource get_command_list() const;
+ bool is_profiling_enabled() const { return m_ev_factory->is_profiling_enabled(); }
+ const ze_engine& get_engine() const { return _engine; }
+ ze_command_list_resource get_immediate_command_list() const { return m_imm_cmd_list; }
private:
- void sync_events(std::vector<event::ptr> const& deps, bool is_output = false);
+ void sync_events(std::vector<event::ptr> const& deps);
const ze_engine& _engine;
- ze_command_list_resource m_cmd_list;
+ ze_command_list_resource m_imm_cmd_list;
mutable std::atomic<uint64_t> m_queue_counter{0};
std::atomic<uint64_t> m_last_barrier{0};
- std::shared_ptr<ze_event> m_last_barrier_ev = nullptr;
std::shared_ptr<ze_base_event_factory> m_ev_factory;
std::shared_ptr<ze_base_event_factory> m_user_ev_factory;
-
#ifdef ENABLE_ONEDNN_FOR_GPU
- std::shared_ptr<dnnl::stream> _onednn_stream = nullptr;
+ std::shared_ptr<dnnl::stream> _onednn_stream;
#endif
+ std::shared_ptr<command_recorder> m_recorder;
};
} // namespace ze
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/command_list_and_recorder_test.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/command_list_and_recorder_test.cpp
new file mode 100644
index 00000000000..860076bccd1
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/command_list_and_recorder_test.cpp
@@ -0,0 +1,167 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/runtime/command_list.hpp"
+#include "intel_gpu/runtime/command_recorder.hpp"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+using namespace cldnn;
+
+namespace {
+
+// Minimal command_list implementation that counts backend calls so the base
+// class state machine can be validated without a real device.
+class mock_command_list : public command_list {
+public:
+ int reset_calls = 0;
+ int close_calls = 0;
+ int enqueue_calls = 0;
+ int wait_calls = 0;
+
+protected:
+ void reset_impl() override { ++reset_calls; }
+ void close_impl() override { ++close_calls; }
+ void enqueue_impl() override { ++enqueue_calls; }
+ void wait_impl() override { ++wait_calls; }
+};
+
+class mock_command_recorder : public command_recorder {
+public:
+ command_list::ptr create_command_list() const override {
+ return std::make_shared<mock_command_list>();
+ }
+};
+
+} // namespace
+
+TEST(command_list_test, new_list_is_open) {
+ mock_command_list cmd_list;
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::open);
+}
+
+TEST(command_list_test, close_transitions_open_to_closed) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::closed);
+ ASSERT_EQ(cmd_list.close_calls, 1);
+}
+
+TEST(command_list_test, close_when_not_open_throws) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ ASSERT_ANY_THROW(cmd_list.close());
+}
+
+TEST(command_list_test, enqueue_when_open_throws) {
+ mock_command_list cmd_list;
+ ASSERT_ANY_THROW(cmd_list.enqueue());
+ ASSERT_EQ(cmd_list.enqueue_calls, 0);
+}
+
+TEST(command_list_test, close_then_enqueue_transitions_to_enqueued) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ cmd_list.enqueue();
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::enqueued);
+ ASSERT_EQ(cmd_list.enqueue_calls, 1);
+}
+
+TEST(command_list_test, enqueue_while_enqueued_waits_before_resubmitting) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ cmd_list.enqueue();
+ cmd_list.enqueue();
+ // Second enqueue must wait for the in-flight execution before re-submitting.
+ ASSERT_EQ(cmd_list.wait_calls, 1);
+ ASSERT_EQ(cmd_list.enqueue_calls, 2);
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::enqueued);
+}
+
+TEST(command_list_test, wait_when_open_throws) {
+ mock_command_list cmd_list;
+ ASSERT_ANY_THROW(cmd_list.wait());
+ ASSERT_EQ(cmd_list.wait_calls, 0);
+}
+
+TEST(command_list_test, wait_when_closed_is_noop) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ cmd_list.wait();
+ ASSERT_EQ(cmd_list.wait_calls, 0);
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::closed);
+}
+
+TEST(command_list_test, wait_when_enqueued_transitions_to_closed) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ cmd_list.enqueue();
+ cmd_list.wait();
+ ASSERT_EQ(cmd_list.wait_calls, 1);
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::closed);
+}
+
+TEST(command_list_test, reset_from_open_keeps_open) {
+ mock_command_list cmd_list;
+ cmd_list.reset();
+ ASSERT_EQ(cmd_list.reset_calls, 1);
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::open);
+}
+
+TEST(command_list_test, reset_from_enqueued_waits_then_reopens) {
+ mock_command_list cmd_list;
+ cmd_list.close();
+ cmd_list.enqueue();
+ cmd_list.reset();
+ ASSERT_EQ(cmd_list.wait_calls, 1);
+ ASSERT_EQ(cmd_list.reset_calls, 1);
+ ASSERT_EQ(cmd_list.get_status(), command_list_status::open);
+}
+
+TEST(command_recorder_test, no_active_command_list_by_default) {
+ mock_command_recorder recorder;
+ ASSERT_EQ(recorder.get_active_command_list(), nullptr);
+}
+
+TEST(command_recorder_test, start_recording_sets_active_command_list) {
+ mock_command_recorder recorder;
+ auto cmd_list = recorder.create_command_list();
+ recorder.start_recording(cmd_list);
+ ASSERT_EQ(recorder.get_active_command_list(), cmd_list);
+}
+
+TEST(command_recorder_test, start_recording_non_open_list_throws) {
+ mock_command_recorder recorder;
+ auto cmd_list = recorder.create_command_list();
+ cmd_list->close();
+ ASSERT_ANY_THROW(recorder.start_recording(cmd_list));
+ ASSERT_EQ(recorder.get_active_command_list(), nullptr);
+}
+
+TEST(command_recorder_test, start_recording_twice_throws) {
+ mock_command_recorder recorder;
+ recorder.start_recording(recorder.create_command_list());
+ ASSERT_ANY_THROW(recorder.start_recording(recorder.create_command_list()));
+}
+
+TEST(command_recorder_test, stop_recording_closes_and_enqueues) {
+ mock_command_recorder recorder;
+ auto cmd_list = std::static_pointer_cast<mock_command_list>(recorder.create_command_list());
+ recorder.start_recording(cmd_list);
+
+ auto finished = recorder.stop_recording();
+
+ ASSERT_EQ(finished, cmd_list);
+ ASSERT_EQ(cmd_list->close_calls, 1);
+ ASSERT_EQ(cmd_list->enqueue_calls, 1);
+ ASSERT_EQ(cmd_list->get_status(), command_list_status::enqueued);
+ ASSERT_EQ(recorder.get_active_command_list(), nullptr);
+}
+
+TEST(command_recorder_test, stop_recording_without_active_returns_null) {
+ mock_command_recorder recorder;
+ ASSERT_EQ(recorder.stop_recording(), nullptr);
+}
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/ze/ze_command_recorder.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/ze/ze_command_recorder.cpp
new file mode 100644
index 00000000000..447f0872467
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/ze/ze_command_recorder.cpp
@@ -0,0 +1,106 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#ifdef OV_GPU_WITH_ZE_RT
+
+#include "ze_test_context.hpp"
+
+#include "intel_gpu/runtime/command_list.hpp"
+#include "intel_gpu/runtime/command_recorder.hpp"
+#include "intel_gpu/runtime/memory.hpp"
+#include "intel_gpu/runtime/utils.hpp"
+#include "intel_gpu/graph/record_replay_session.hpp"
+
+#include "runtime/ze/ze_stream.hpp"
+#include "runtime/ze/ze_command_list.hpp"
+#include "runtime/ze/ze_base_event.hpp"
+#include "runtime/ze/ze_empty_event.hpp"
+
+#include <vector>
+
+using namespace cldnn;
+using namespace ze_tests;
+
+namespace {
+
+std::shared_ptr<memory> allocate_device_memory(const ze_test_context& ctx, size_t bytes) {
+ const layout mem_layout = {{static_cast<int64_t>(bytes)}, data_types::u8, format::bfyx};
+ if (!ctx.ze_test_engine->supports_allocation(allocation_type::usm_device)) {
+ return nullptr;
+ }
+ return ctx.ze_test_engine->allocate_memory(mem_layout, allocation_type::usm_device);
+}
+
+} // namespace
+
+TEST(ze_command_recorder, stream_provides_recorder) {
+ auto ctx = create_ze_test_context();
+ ASSERT_NE(ctx.ze_test_stream->get_recorder(), nullptr);
+}
+
+TEST(ze_command_recorder, created_command_list_is_open) {
+ auto ctx = create_ze_test_context();
+ auto cmd_list = ctx.ze_test_stream->get_recorder()->create_command_list();
+ ASSERT_NE(cmd_list, nullptr);
+ ASSERT_EQ(cmd_list->get_status(), command_list_status::open);
+}
+
+TEST(ze_command_recorder, recording_swaps_stream_command_list) {
+ auto ctx = create_ze_test_context();
+ auto& ze_test_stream = downcast<ze::ze_stream>(*ctx.ze_test_stream);
+ auto recorder = ze_test_stream.get_recorder();
+
+ auto immediate_handle = ze_test_stream.get_immediate_command_list().handle();
+ // Without an active recording, the stream targets its immediate command list.
+ ASSERT_EQ(ze_test_stream.get_command_list().handle(), immediate_handle);
+
+ auto cmd_list = recorder->create_command_list();
+ recorder->start_recording(cmd_list);
+
+ auto recorded_handle = std::static_pointer_cast<ze::ze_command_list>(cmd_list)->resource().handle();
+ // While recording, the stream must target the recorded command list.
+ ASSERT_EQ(ze_test_stream.get_command_list().handle(), recorded_handle);
+ ASSERT_NE(recorded_handle, immediate_handle);
+
+ recorder->stop_recording();
+ // After recording stops, the stream targets the immediate command list again.
+ ASSERT_EQ(ze_test_stream.get_command_list().handle(), immediate_handle);
+}
+
+TEST(ze_command_recorder, recorded_command_list_replays_commands) {
+ auto ctx = create_ze_test_context();
+ auto& ze_test_stream = downcast<ze::ze_stream>(*ctx.ze_test_stream);
+
+ constexpr size_t bytes = 256;
+ auto mem = allocate_device_memory(ctx, bytes);
+ if (mem == nullptr) {
+ GTEST_SKIP() << "USM device allocation is not supported";
+ }
+ auto read_back = [&]() {
+ std::vector<uint8_t> host(bytes, 0);
+ mem->copy_to(ze_test_stream, host.data(), true);
+ return host;
+ };
+
+ mem->fill(ze_test_stream, 0x00, {}, true);
+ auto recorder = ze_test_stream.get_recorder();
+ auto cmd_list = recorder->create_command_list();
+
+ // Record a fill with a distinct pattern (non-blocking so recording is not interrupted).
+ recorder->start_recording(cmd_list);
+ mem->fill(ze_test_stream, 0xCD, {}, false);
+ ASSERT_EQ(recorder->stop_recording(), cmd_list);
+ ze_test_stream.finish();
+ ASSERT_EQ(read_back(), std::vector<uint8_t>(bytes, 0xCD));
+
+ mem->fill(ze_test_stream, 0x00, {}, true);
+ ASSERT_EQ(read_back(), std::vector<uint8_t>(bytes, 0x00));
+
+ // Replay recorded fill operation
+ cmd_list->enqueue();
+ cmd_list->wait();
+ ASSERT_EQ(read_back(), std::vector<uint8_t>(bytes, 0xCD));
+}
+
+#endif // OV_GPU_WITH_ZE_RT
diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmake
index a80098c3219..e78a64f018c 100644
--- a/src/plugins/intel_gpu/tests/unit/sources.cmake
+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake
@@ -73,6 +73,7 @@ set(GPU_UNIT_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/module_tests/memory_dependency_set_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/nodes_ordering_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/primitive_comparison_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/module_tests/command_list_and_recorder_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/shape_predictor_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/sycl/sycl_test_context.hpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/test_uqr_distribution.cpp
@@ -250,6 +251,7 @@ set(GPU_UNIT_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/test_cases/quantize_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/random_uniform_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/range_gpu_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/record_replay_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/reduce_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/region_yolo_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/removing_output_node_test.cpp
@@ -531,6 +533,7 @@ endif()
# Tests with a dependency on the Level Zero runtime.
set(GPU_UNIT_TESTS_ZE_RT_SRCS
+ ${CMAKE_CURRENT_LIST_DIR}/module_tests/ze/ze_command_recorder.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/ze/ze_device_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/ze/ze_engine_test.cpp
${CMAKE_CURRENT_LIST_DIR}/module_tests/ze/ze_events_test.cpp
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/record_replay_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/record_replay_gpu_test.cpp
new file mode 100644
index 00000000000..604e9c9b3d8
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/record_replay_gpu_test.cpp
@@ -0,0 +1,55 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "test_utils.h"
+
+#include "intel_gpu/graph/network.hpp"
+#include "intel_gpu/primitives/input_layout.hpp"
+#include "intel_gpu/primitives/activation.hpp"
+
+#include <memory>
+#include <vector>
+
+using namespace cldnn;
+using namespace ::tests;
+
+TEST(record_replay_gpu_test, returns_correct_results) {
+ auto& engine = get_test_engine();
+ if (engine.type() != engine_types::ze) {
+ GTEST_SKIP() << "Record and replay requires a Level Zero engine";
+ }
+
+ layout in_layout{{1, 1, 2, 2}, data_types::f32, format::bfyx};
+ auto input_mem = engine.allocate_memory(in_layout);
+ set_values(input_mem, std::vector<float>{-1, -0.1, 0.1, 1});
+
+ topology topology;
+ topology.add(input_layout("input", in_layout));
+ topology.add(activation("clamp", input_info("input"), activation_func::clamp, {-5.f, 5.f}));
+ topology.add(activation("relu", input_info("clamp"), activation_func::relu));
+
+ auto exec_and_read_out = [](network& net) {
+ auto output = net.execute().at("relu").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> lock(output, net.get_stream());
+ return std::vector<float>(lock.data(), lock.data() + output->count());
+ };
+
+ network ref_net(engine, topology, get_test_default_config(engine));
+ ref_net.set_input_data("input", input_mem);
+ const auto reference = exec_and_read_out(ref_net);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::record_replay(true));
+ network net(engine, topology, config);
+ net.set_input_data("input", input_mem);
+
+ // First iteration records, subsequent iterations replay
+ constexpr size_t iterations = 4;
+ for (size_t iter = 0; iter < iterations; ++iter) {
+ const auto out = exec_and_read_out(net);
+ ASSERT_EQ(out.size(), reference.size());
+ for (size_t i = 0; i < reference.size(); ++i)
+ ASSERT_FLOAT_EQ(out[i], reference[i]);
+ }
+}
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
index f5f7bfad88e..5662bb38825 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
@@ -2164,7 +2164,7 @@ TEST_P(sdpa_ref_scratch_test, native_q_broadcast) {
net->set_arguments();
for (const auto& id : net->get_executed_primitive_ids()) {
const auto instance = net->get_primitive(id);
- instance->reset_events();
+ instance->clear_events();
instance->prepare_primitive();
if (id == "sdpa") {
ASSERT_EQ(instance->get_impl()->m_manager->get_type_info(), ov::intel_gpu::ocl::SDPARef::get_type_info_static());