= sycl_ext_oneapi_reusable_events

:source-highlighter: coderay
:coderay-linenums-mode: table

// This section needs to be after the document title.
:doctype: book
:toc2:
:toc: left
:encoding: utf-8
:lang: en
:dpcpp: pass:[DPC++]
:endnote: &#8212;{nbsp}end{nbsp}note

// Set the default source code type in this document to C++,
// for syntax highlighting purposes.  This is needed because
// docbook uses c++ and html5 uses cpp.
:language: {basebackend@docbook:c++:cpp}


== Notice

[%hardbreaks]
Copyright (C) 2025 Intel Corporation.  All rights reserved.

Khronos(R) is a registered trademark and SYCL(TM) and SPIR(TM) are trademarks
of The Khronos Group Inc.  OpenCL(TM) is a trademark of Apple Inc. used by
permission by Khronos.


== Contact

To report problems with this extension, please open a new issue at:

https://github.com/intel/llvm/issues


== Dependencies

This extension is written against the SYCL 2020 revision 11 specification.
All references below to the "core SYCL specification" or to section numbers in
the SYCL specification refer to that revision.

This extension also depends on the following other SYCL extensions:

* link:../experimental/sycl_ext_oneapi_properties.asciidoc[
  sycl_ext_oneapi_properties]


== Status

This is an experimental extension specification, intended to provide early
access to features and gather community feedback.  Interfaces defined in this
specification are implemented in {dpcpp}, but they are not finalized and may
change incompatibly in future versions of {dpcpp} without prior notice.
*Shipping software products should not rely on APIs defined in this
specification.*

This extension has been implemented with temporary limitations, outlined in the
"Implementation limitations" section.

== Backend support status

This extension is not supported with the Level Zero v1 adapter. All of the
functions defined in the extension will throw an `exception` with the
`errc::feature_not_supported` error code.

== Overview

This extension adds the ability to reuse the same `event` object to track
completion of multiple command submissions, rather than creating a new event for
each submission.
An `event` object is still only able to track one command at a time, but this
extension allows an `event` to track a new command once the application no
longer needs to track the previous one.
This pattern may perform better on some implementations because fewer event
objects need to be created and destroyed.
This pattern may also be more familiar to users porting CUDA code to SYCL.

This extension also adds a way to construct an event that enables profiling
timing without enabling profiling on the entire queue.
This is more efficient on some platforms because only a subset of the events are
required to contain timestamp information.
It is also more convenient for use in libraries when the library wants to get
timing information for some commands, but the library does not control the
construction of the queue.


== Specification

=== Feature test macro

This extension provides a feature-test macro as described in the core SYCL
specification.
An implementation supporting this extension must predefine the macro
`SYCL_EXT_ONEAPI_REUSABLE_EVENTS` to one of the values defined in the table
below.
Applications can test for the existence of this macro to determine if the
implementation supports this feature, or applications can test the macro's value
to determine which of the extension's features the implementation supports.

[%header,cols="1,5"]
|===
|Value
|Description

|1
|The APIs of this experimental extension are not versioned, so the
 feature-test macro always has this value.
|===

=== New functions to create an event

This extension adds the following factory functions which can create an event
with a specific context or with associated properties.

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

template<typename PropertyListT = empty_properties_t>
event make_event(const context &ctxt, PropertyListT props = {});

} // namespace sycl::ext::oneapi::experimental
----

_Constraints:_

* `PropertyListT` is one of the properties listed below in section "New properties
  for creating an event"; or
* `is_property_list_v<PropertyListT>` is `true` and contains no properties other
  than those listed below in section "New properties for creating an event".

_Returns:_ An event that is associated with context `ctxt`. The event has
`info::event_command_status::complete` status.

_Throws:_ An `exception` with the `errc::feature_not_supported` error code if
`PropertyListT` contains an `enable_profiling` property that enables profiling
timestamps and devices in `ctxt` do not have
`aspect::ext_oneapi_per_event_profiling`.

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

template<typename PropertyListT = empty_properties_t>
event make_event(PropertyListT props = {});

} // namespace sycl::ext::oneapi::experimental
----

_Constraints:_

* `PropertyListT` is one of the properties listed below in section "New properties
  for creating an event"; or
* `is_property_list_v<PropertyListT>` is `true` and contains no properties other
  than those listed below in section "New properties for creating an event".

_Effects:_ Equivalent to:

[source,c++,indent=2]
----
sycl::device dev;
sycl::context ctxt = dev.get_platform().khr_get_default_context();
return sycl::ext::oneapi::experimental::make_event(ctxt, props);
----

'''

=== New properties for creating an event

This extension adds the following properties, which can be used with
`make_event`:

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

struct enable_profiling {
  enable_profiling(bool enable = true);  (1)
};
using enable_profiling_key = enable_profiling;

} // namespace sycl::ext::oneapi::experimental
----

This property controls whether the event captures profiling timestamps.

_Effects_ (1): Creates a new `enable_profiling` property with a boolean value
indicating whether the event captures profiling timestamp information.

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

enum class event_mode_enum { none, low_power };

struct event_mode {
  event_mode(event_mode_enum mode);  (1)
};
using event_mode_key = event_mode;

} // namespace sycl::ext::oneapi::experimental
----

This property is a hint for the driver to optimize event host synchronization.
Passing `event_mode_enum::low_power` requests that the driver conserve CPU
resources by sleeping the waiting thread instead of polling, which may increase
completion latency. `event_mode_enum::none` requests no specific mode and is
equivalent to not passing the property.

Backends that do not support the requested mode will silently ignore this hint.

_Effects_ (1): Creates a new `event_mode` property with the given mode.

'''

=== New device aspect

This extension adds the following device aspect.

'''

[source,c++]
----
namespace sycl {

enum class aspect {
  ext_oneapi_per_event_profiling
  // ...
};

} // namespace sycl
----

Indicates that the device's platform allows events to be created with profiling
enabled. All devices in the same platform return the same information for this
query.

'''

=== New functions to enqueue event operations [[enqueue-event-operations]]

This extension adds the following free functions which submit operations related
to events onto a queue.

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

template<typename PropertyListT = empty_properties_t>
void enqueue_wait_event(queue q, const event& evt, PropertyListT props = {});

template<typename PropertyListT = empty_properties_t>
void enqueue_wait_events(queue q, const std::vector<event>& evts,
                         PropertyListT props = {});

} // namespace sycl::ext::oneapi::experimental
----

_Constraints:_

* `PropertyListT` is a property that is documented as legal to pass to this
  function; or
* `is_property_list_v<PropertyListT>` is `true` and contains no properties other
  than those that are documented as legal to pass to this function.

_Effects:_ Enqueues a special barrier to `q` with the following semantic.
Any commands submitted to the queue after this barrier cannot begin execution
until all commands associated with `evt` or `evts` have completed.

_Remarks:_ The event `evt` and the events in `evts` do _not_ need to have the
same context as `q`.

'''

[source,c++]
----
namespace sycl::ext::oneapi::experimental {

template<typename PropertyListT = empty_properties_t>
void enqueue_signal_event(queue q, event& evt, PropertyListT props = {});

} // namespace sycl::ext::oneapi::experimental
----

_Constraints:_

* `PropertyListT` is a property that is documented as legal to pass to this
  function; or
* `is_property_list_v<PropertyListT>` is `true` and contains no properties other
  than those that are documented as legal to pass to this function.

_Effects:_ The event `evt` is immediately disassociated with any previous
command, and its status is set to `info::event_command_status::submitted`.

If the queue `q` is in-order (i.e. was constructed with
`property::queue::in_order`), this function enqueues a lightweight "tag"
operation that marks the current head of the queue.
The status of `evt` becomes `info::event_command_status::complete` when all
commands submitted prior to the tag have completed.

If the queue `q` is out-of-order, it enqueues a command barrier, and any
commands submitted after this barrier cannot begin execution until all
previously submitted commands have completed.
After the barrier completes, a "tag" operation sets the status of `evt` to
`info::event_command_status::complete`.

The event's timestamp information is also set if the queue `q` was created with
the `property::queue::enable_profiling` property or if the event `evt` was
created with the `ext::oneapi::experimental::enable_profiling` property.
Because the operation represented by the event is an empty command, the
`info::event_profiling::command_start` timestamp is equivalent to the
`info::event_profiling::command_end` timestamp, which reflects the time at which
the event becomes signaled (enters the "complete" state).
Applications are discouraged from using the
`info::event_profiling::command_submit` timestamp, whose value is some time
between the point when the host thread calls `enqueue_signal_event` and the
`command_start` timestamp.

[_Note:_ An implementation may simply set all three timestamps to the same
value.
_{endnote}_]

It is unspecified whether the event ever has the
`info::event_command_status::running` status.
Implementations are encouraged to transition the event directly from the
"submitted" status to the "complete" status.

_Throws:_

 * An `exception` with the `errc::invalid` error code if `evt` and `q` don't
   have the same context.

=== Interaction with other event APIs

An event _E_ created via `make_event` can be used as a command dependency (e.g.
via `handler::depends_on`) for a command submitted to some queue _Q_.
It is _not_ necessary for the context of _E_ to match the context of _Q_.

If an event _E_ is used as a command dependency for some command _C_ (e.g. via
`handler::depends_on`), the dependency is captured at the point when _C_ is
submitted.
It is legal to reassociate the event _E_ to a new command via
`enqueue_signal_event` even before command _C_ completes.
Doing so does _not_ change the dependency for command _C_.

When an event _E_ is enqueued for signaling via `enqueue_signal_event`, its
wait list is replaced as well.
From then on, `event::get_wait_list` called on _E_ returns only dependencies of
the new command, if any, and never the dependencies of a command _E_ was
associated with before.

It is not recommended to call both `enqueue_signal_event` and
`event::get_wait_list` for events in the same dependency chain. Consider the
case when _E1_ represents the completion of command _C_, and _C_ depends on
some other event _E2_. If _E2_ is reassociated with a new command via
`enqueue_signal_event`, a subsequent call to `E1.get_wait_list()` may still
return _E2_ even though _E2_ is no longer a dependency.

If another host thread is blocked waiting for event _E_ to complete via
`event::wait` or `event::wait_and_throw` when event _E_ is reassociated with a
new command via `enqueue_signal_event`, the behavior of the `event::wait` or
`event::wait_and_throw` call is undefined.

The core SYCL specification defines a default constructor for the `event`
class. The default constructor creates an event that is equivalent to calling
`make_event` with no parameters.

Several of the `queue` class member functions from the core SYCL specification
return an event. These events are associated with the queue's context as though
created by `make_event` with that context.
These events may be passed to any of the functions in this extension that take
an event parameter.

== Examples

=== Recording cross queue dependencies

[source,c++]
----
#include <sycl/sycl.hpp>
namespace syclex = sycl::ext::oneapi::experimental;

static constexpr size_t N = 1024;

int main() {
  sycl::device dev;
  sycl::context ctxt = dev.get_platform().khr_get_default_context();
  sycl::queue q1{ctxt, dev, sycl::property::queue::in_order{}};
  sycl::queue q2{ctxt, dev, sycl::property::queue::in_order{}};
  sycl::event e = syclex::make_event(ctxt);

  // Launch a kernel on `q1` and then signal an event when the kernel completes.
  syclex::parallel_for(q1, sycl::range{N}, [=](sycl::item<> it) { /* ... */ });
  syclex::enqueue_signal_event(q1, e);

  // Add a dependency on `q2` which waits for the kernel on `q1` to complete.
  // Then launch a kernel on `q2`.
  syclex::enqueue_wait_event(q2, e);
  syclex::parallel_for(q2, sycl::range{N}, [=](sycl::item<> it) { /* ... */ });

  // Reassociate the same event with the kernel on `q2`.
  syclex::enqueue_signal_event(q2, e);

  // Wait for both commands to complete.
  e.wait();
}
----

=== Timing a sequence of kernels

[source,c++]
----
#include <iostream>
#include <sycl/sycl.hpp>
namespace syclex = sycl::ext::oneapi::experimental;

static constexpr size_t N = 1024;

int main() {
  sycl::queue q;
  sycl::context ctxt = q.get_context();

  // This example creates a queue that does not enable profiling and then
  // creates events that do enable profiling. This is an optional feature, so
  // check if all the devices in the platform support it.
  if (!ctxt.get_platform().has(sycl::aspect::ext_oneapi_per_event_profiling)) {
    std::cout << "Cannot time kernels without per-event profiling support\n";
    return 0;
  }

  sycl::event start = syclex::make_event(ctxt, syclex::enable_profiling{true});
  sycl::event end = syclex::make_event(ctxt, syclex::enable_profiling{true});

  syclex::enqueue_signal_event(q, start);
  syclex::parallel_for(q, sycl::range{N}, [=](auto i) { /* first kernel */ });
  syclex::parallel_for(q, sycl::range{N}, [=](auto i) { /* second kernel */ });
  syclex::enqueue_signal_event(q, end);

  q.wait();

  uint64_t elapsed =
    end.get_profiling_info<sycl::info::event_profiling::command_start>() -
    start.get_profiling_info<sycl::info::event_profiling::command_end>();
  std::cout << "Execution time: " << elapsed << " (nanoseconds)\n";
}
----


== Implementation notes

=== Mapping on Level Zero

The APIs in this extension have a straightforward mapping to Level Zero when
using counter-based events:

* The `make_event` function maps to `zeEventCounterBasedCreate`.
  If the `enable_profiling` property is specified to `make_event`, the event
  should have the corresponding Level Zero flag set.
* Devices on the Level Zero backend can return `true` for
  `aspect::ext_oneapi_per_event_profiling`.
* The `enqueue_wait_event` function maps to `zeCommandListAppendWaitOnEvents`.
* The `enqueue_signal_event` function maps to `zeCommandListAppendSignalEvent`.
* The SYCL `event` passed to `enqueue_signal_event` will contain a
  `ze_event_handle_t`.
  Each call to `zeCommandListAppendSignalEvent` can pass this same
  `ze_event_handle_t`, thus reusing the backend event across many calls.

=== Mapping on OpenCL

The mapping is not so straightforward for OpenCL because OpenCL APIs return an
event when a command is submitted, rather than taking an event as input.

* The `make_event` function has no direct mapping to OpenCL.
  Instead, this function just creates a SYCL `event` object with no underlying
  OpenCL event.
* Devices on the OpenCL backend are expected to return `false` for
  `aspect::ext_oneapi_per_event_profiling`, unless we create some OpenCL
  extension that makes this possible.
* The `enqueue_wait_event` function maps to either `clEnqueueMarkerWithWaitList`
  (for in-order queues) or to `clEnqueueBarrierWithWaitList` (for out-of-order
  queues).
  In either case, the output `event` parameter should be NULL.
  It would also be legal to call `clEnqueueBarrierWithWaitList` for both
  in-order and out-of-order queues.
* The `enqueue_signal_event` function also maps to either
  `clEnqueueMarkerWithWaitList` or `clEnqueueBarrierWithWaitList`, but in this
  case the input `event_wait_list` parameter is empty and the output `event`
  parameter is non-NULL.
  These OpenCL functions return an output `cl_event`, and the SYCL runtime will
  store this in the SYCL `event`.
* Because OpenCL is unable to reuse a `cl_event`, subsequent calls to
  `enqueue_signal_event` first check to see if there is a `cl_event` from a
  previous call attached to the SYCL `event`.
  If so, the `cl_event` is released before calling `clEnqueueMarkerWithWaitList`
  or `clEnqueueBarrierWithWaitList`.

=== Host tasks

Because host tasks are executed by the SYCL runtime, there can be cases where
a command _C_ is submitted at the SYCL level, but the command remains pending
inside the SYCL runtime until a host task completes.
(E.g. when command _C_ has a dependency on the host task.)
As a result, there may be cases when `enqueue_signal_event` must also leave the
"event signal" operation pending in the SYCL runtime, or when
`enqueue_wait_event` must leave the "event wait" operation pending in the SYCL
runtime.
In these cases, we expect that a backend event may not be associated with the
SYCL event until the pending operations are resolved in the runtime library.
This will likely cause the handling of events to be less efficient when host
tasks are submitted to the same queue as "native" commands like kernels or
copy operations, or when there are dependencies between host tasks and native
commands.

=== Implementation limitations

This extension has been implemented with the following limitations. A program
must avoid them in order to work correctly, but a violation is only diagnosed
in some cases. The implementation throws an `exception` with the `errc::invalid`
error code if, at the point of the call, the command which the "event signal" or
"event wait" operation depends on is still pending inside the SYCL runtime. If
that command has already been submitted to the backend by then, the operation
succeeds instead. Since an application cannot generally observe which of the
two is the case, it must not rely on either outcome.

* The `evt` passed to the `enqueue_wait_event` function and all events in
  `evts` passed to the `enqueue_wait_events` function need to have the same
  context as `q`.
* The `enqueue_signal_event`, `enqueue_wait_event` and `enqueue_wait_events`
  functions cannot be dependent on a host task (`enqueue_wait_event` and
  `enqueue_wait_events` cannot take an event produced by a host task submission
  as an argument and all those functions cannot be enqueued behind a host task
  on an in-order queue), which has been submitted using the
  `handler::host_task` function. Submitting host tasks using the
  `sycl::ext::oneapi::experimental::host_task` function from the
  link:../experimental/sycl_ext_oneapi_enqueue_functions.asciidoc[
  sycl_ext_oneapi_enqueue_functions] extension is supported.
* The `enqueue_signal_event`, `enqueue_wait_event` and `enqueue_wait_events`
  functions cannot be dependent on a command which accesses a memory object
  while a host accessor for that memory object exists (`enqueue_wait_event` and
  `enqueue_wait_events` cannot take an event produced by such a command as an
  argument and all those functions cannot be enqueued behind such a command on
  an in-order queue). This applies to `host_accessor`,
  `buffer::get_host_access`, `host_unsampled_image_accessor` and
  `host_sampled_image_accessor`. Unlike a host task, which completes on its own,
  such a command is held until the host accessor is destroyed, which happens
  when the last copy of the host accessor is destroyed, so the application
  controls how long this limitation lasts.
* An event returned by a command submission cannot be passed to the
  `enqueue_signal_event` function while that command, or any command it depends
  on, is still pending inside the SYCL runtime, for example behind a host task
  submitted using the `handler::host_task` function. The implementation throws
  an `exception` with the `errc::invalid` error code in this case.
* The `enqueue_signal_event`, `enqueue_wait_event` and `enqueue_wait_events`
  functions cannot be dependent on any commands which use cross-context
  event dependencies.
* The `enqueue_signal_event`, `enqueue_wait_event` and `enqueue_wait_events`
  functions cannot be dependent on any commands using `sycl::stream`.
* The `enqueue_signal_event`, `enqueue_wait_event` and `enqueue_wait_events`
  functions cannot be dependent on the following methods from the
  link:../supported/sycl_ext_oneapi_memcpy2d.asciidoc[
  sycl_ext_oneapi_memcpy2d] extension: `queue::ext_oneapi_memcpy2d`,
  `queue::ext_oneapi_copy2d`, `handler::ext_oneapi_memcpy2d`,
  `handler::ext_oneapi_copy2d`, if the copy is a host-to-host data copy,
  and the following methods: `queue::ext_oneapi_fill2d`,
  `queue::ext_oneapi_memset2d`, `handler::ext_oneapi_fill2d`,
  `handler::ext_oneapi_memset2d`, if the backend does not support 2D fill or
  the target memory is on host.
* When an event is passed to the `enqueue_signal_event` function and is also
  used as a dependency of a command (via `handler::depends_on`, one of the
  `queue` member functions which take event dependencies, or any other API
  which establishes an event dependency), the same limitations apply as those
  described above for the `enqueue_wait_event` and `enqueue_wait_events`
  functions. This includes the restriction that the event needs to have the
  same context as the queue to which the dependent command is submitted, which
  temporarily restricts the behavior described in the section "Interaction with
  other event APIs". These limitations apply regardless of whether the
  dependent command is submitted before or after the call to
  `enqueue_signal_event`. If any of these limitations is violated, the behavior
  is undefined. This case is never diagnosed, because the implementation does
  not currently differentiate between events enqueued for signaling using
  `enqueue_signal_event` and regular events produced during command submission.
