When Platforms are initialized liboffload sets an atexit handler that
ensures that is deinitialized before deinitialazing platforms.
Because this happens lazily, a library using offload that wants to
run some of its shutdown needs to properly setup its atexit handler
after the liboffload one (because they're called in reverse order).
This requires to know precisely the internal implementation of
liboffload.
Instead of requiring that, this PR adds an API that allows the users
of liboffload to register their own deinit code and be assured that it
will
be called before liboffload shutdowns independently of when platforms
are initialized.
Assisted by Claude.
---
<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
Rewrite the documentation of olCreateQueue, olDestroyQueue,
olGetQueueInfo and olGetQueueInfoSize. Add a number of tests to ensure
that the documented claims hold.
Change the error returned when reusing a destroyed queue fails. This is
a very unlikely situation that probably indicates an unrecoverable error
(at least with the current liboffload API).
Assisted-by: Claude
The host plugin runs every operation synchronously, but
hasPendingWorkImpl returned true unconditionally. As a result
OL_QUEUE_INFO_EMPTY was always false on the host device, and
olDestroyQueue parked every host queue on the context's outstanding list
until the context was destroyed.
Return false instead, so a host queue reports as empty and is released
when it is destroyed. All backends now report the real queue status, so
drop the "may be unconditionally false" caveat from the
OL_QUEUE_INFO_EMPTY documentation.
Assisted-by: Claude
Add a new `olGetProgramInfo` API to retrieve information about a
`ol_program` and add properties to get the Device Image after loading.
Move the handling of `ImageIR` directly to libomptarget (only used for
Record Replay).
Use the new API to remove the helper calls and references to the
`DeviceImageTy` from the Plugin interface.
Assisted by Claude.
Reimplement OpenMP interop support using liboffload interfaces:
* Added a new property liboffload devices to get the native platform of
a device that was missing (could be moved to a sepparate PR).
* Reimplemented the queue creation and logic assuming liboffload inorder
queues.
* Some of the backend decision logic was moved into libomptarget (if
#235844 is merged it should be moved there)
* Renamed some "tgt" interop related stuff to use "omp" prefix.
I also found a bug in which properties were allowed for
`interop(target`) which I fixed here but could do it sepparately.
Assisted by Claude.
Add a new kind of Symbol to liboffload
(`OL_SYMBOL_KIND_IMAGE_VARIABLE`). The information of these symbols are
retrieved from the loaded image instead of through the device. This
allows to implement the support of `readGlobalFromImage` in
libomptarget.
As it doesn't seem to be used anywhere else, it can be removed from the
PluginInterface.
Assisted by Claude.
Other subprojects invoke their TableGen through a project-specific
wrapper (clang_tablegen, mlir_tablegen, lldb_tablegen). Add
llvm_tablegen for llvm-tblgen and replace every tablegen(LLVM ...) call
with it.
The llvm-tblgen-specific logic in tablegen() moves into llvm_tablegen:
the DAGISel/GlobalISel coverage and -omit-comments flags, and the extra
outputs of -gen-register-info, which tablegen() now accepts generically
through a new EXTRA_OUTPUTS argument.
My motivation is general cleanliness but also as a use-case to add the
`EXTRA_OUTPUTS` cmake option to the `tablegen` command
Add a new property to `olGetDeviceInfo` to query if host memory should
be preferred over device copies (`PREFERS_ZERO_COPY`). Use it to
implement libomptarget `AutoZeroCopy` logic.
Remove `GenericPluginTy::use_auto_zero_copy` interface as a result.
Assisted by Claude.
Two new properties (`KERNEL_STATIC_BLOCK_MEM_SIZE` and
`KERNEL_MAX_THREADS`) were added to query the kernel properties that
libomptarget was querying directly.
Decouple RecordReplay from `GenericKernelTy` by introducing a new
`KernelInfoTy` structure that only carries the subset of information
that RR needs.
For now, libomptarget still needs access to `DeviceImageTy` to get some
that information.
Assisted by Claude.
The Level Zero plugin reports `OL_DEVICE_INFO_NAME` and
`OL_DEVICE_INFO_PRODUCT_NAME` backwards from how other plugins report
these values, e.g.:
|Backend|NAME|PRODUCT_NAME|
|-|-|-|
|Level Zero|Intel(R) Arc(TM) B580 Graphics|Intel GPU Xe HP|
|AMDGPU|gfx1201|AMD Radeon RX 9070 XT|
|CUDA|NVIDIA GeForce RTX 3060|NVIDIA GeForce RTX 3060|
Change the Level Zero plugin to report the product name through
PRODUCT_NAME and the architecture string through NAME (mirroring
AMDGPU), clarify the `NAME` description in Device.td, and change libsycl
to use `PRODUCT_NAME` for `sycl::info::device::name` so it still reports
the product name.
Add two new device properties accessible through liboffload:
LAUNCH_MAX_NUM_WORK_GROUPS (max blocks) and LAUNCH_MAX_GRID_SIZE (max
total work-items). Using them compute the getBlockLimit in libomptarget
in a backend agnostic way.
Remove getBlockLimit from the Plugin Interface as it's no longer needed.
Assisted by Claude.
Add two new device properties accessible through liboffload:
LAUNCH_MAX_NUM_WORK_GROUPS (max blocks) and LAUNCH_MAX_GRID_SIZE (max
total work-items). Using them compute the getBlockLimit in libomptarget
in a backend agnostic way.
Remove getBlockLimit from the Plugin Interface as it's no longer needed.
Assisted by Claude.
Adds a property to be able to retrieve the native handle of a queue,
device and context to their respective olGetInfo routines.
This is needed to implement interopability features on top of liboffload
like OpenMP's interop directive.
Assisted by Claude.
If either the src or dst device is a null device handle then a host
device will be used as the src/dst (or both).
This simplifies the usage from libraries that treat the host as a
special device (e.g., libomptarget).
Assisted by Claude.
---------
Co-authored-by: Kevin Sala Penades <kevinsala.ks@gmail.com>
First patch from a series that will improve liboffload documentation. As
liboffload is getting used by more projects, we should have
comprehensive documentation. I'm starting with the olInit/olShutDown
functions. Documented behavior is paired with basic unittests.
Generator changes needed to express this:
* offload-tblgen: a `details` entry starting with "- " is rendered as a
bullet, anything else as a paragraph.
* The default return list named OL_RESULT_SUCCESS and
OL_ERRC_DEVICE_LOST, neither of which exists. It now lists OL_SUCCESS
and OL_ERRC_UNINITIALIZED with a description, and a function that lists
a default code itself replaces the generic condition instead of
duplicating the entry.
* OL_ERRC_INVALID_NULL_HANDLE / _POINTER are only added to a function's
returns when it has a handle or pointer parameter to check.
Assisted-By: Claude
Removes all calls to the PluginInterface to get device specific
properties:
- Some were reading only env vars and were moved directly to
libomptarget.
- A few new properties were adedd to be accessible through
olGetDeviceInfo.
- A few others were derived in libomptarget.
Assisted by Claude.
Implement a new method in liboffload to access isAccessiblePtr method in
GenericDeviceTy and use it in libomptarget to substitute the direct call
to GenericPluginTy.
Assisted by Claude.
Extend olGetPlatformInfo to retrieve if a Platform is active (has been
initialized and has at least one device) and use it to implement
__tgt_register_rpc_callback in libomptarget through liboffload.
Also, add to the running list olRegisterRPCCallback unit tests that we
seem to have forgotten to add in
https://github.com/llvm/llvm-project/pull/178774.
Assisted by Claude.
Add a new API that iterates through all devices. For devices compatible
with the image (and their platform too) it calls the Callback.
Assisted by Claude.
Add a new service to iterate created Platforms. This differs from
obtaining the platforms from the existing olIterateDevices in that the
platforms are not initialized.
Assisted by Claude.
Summary:
The Offloading library wraps around the underlying plugins. The problem
is that we currently initialize all plugins we find, even if they are
not needed for the program. This is very expensive for trivial uses, as
fully heterogenous usage is quite rare. In practice this means that you
will always pay a 200 ms penalty for having CUDA installed.
This patch changes the behavior to provide accessors into the plugins
and devices that allows them to be initialized lazily. We use a
once_flag, this should properly take a fast-path check while still
blocking on concurrent use.
Making full use of this will require a way to filter platforms more
specifically. I'm thinking of what this would look like as an API.
I'm thinking that we either have an extra iterate function that takes a
callback on the platform, or we just provide a helper to find all the
devices that can run a given image. Maybe both?
Fixes: #159636
Realnd of: https://github.com/llvm/llvm-project/pull/163272
This is the last part of the context refactor. This patch:
- Adds context param to all memory allocation functions.
- Routes ptr info through the plugins instead of a global map.
- Removes allocation tracking from liboffload.
- olGetMemInfo(OL_MEM_INFO_DEVICE) now returns INVALID_ARGUMENT for host
allocations, which have no per-device affinity.
Re-land of #222677 + #224622, which were reverted together in #224703.
Assisted-by: Claude Opus 4.7
This is the last part of the context refactor. This patch:
- Adds context param to all memory allocation functions.
- Routes ptr info through the plugins instead of a global map.
- Removes allocation tracking from liboffload.
- olGetMemInfo(OL_MEM_INFO_DEVICE) now returns INVALID_ARGUMENT for host
allocations, which have no per-device affinity.
Assisted-by: Claude Opus 4.7
Prior to the introduction of liboffload contexts, Level Zero devices
under different driver instances used to each receive their own
`L0ContextTy`s.
https://github.com/llvm/llvm-project/pull/209144 introduced contexts,
which are designed to map to a single `ze_context` on L0.
`olCreateContext` accepts a user-defined device list and is restricted
to accept devices within a single platform. This restriction is
insufficient for L0 - passing devices from different driver instances is
allowed under this contract, but does not make sense on L0 as
`zeContextCreate` needs a concrete driver instance as a parameter.
Introduce a `DRIVER_ID` device property. On CUDA and AMD, it is always
equal to 0. On L0, it is a distinct integer for each driver instance. A
set of devices can be used to create a context if and only if they all
belong to the same platform and have the same DRIVER_ID.
Change libsycl to create separate logical SYCL platforms (which share
their ol_platform_handle_t) for each possible liboffload (platform,
driverId) pair.
Assisted-by: Codex (5.6 Sol)
This patch is the 3rd patch in the context patch series. This change is
relatively simple compared to the others: we just introduce context to
the create program API and pass it down through the plugin interface to
the plugins.
Fix Level Zero memory fills that cannot use
`zeCommandListAppendMemoryFill`, such as non-power-of-two patterns.
The replication fallback previously submitted a temporary host vector
whose lifetime could end before the asynchronous copy completed, which
caused unit test failures. This PR changes the replication fallback to
simply use `dataSubmit()` + `synchronize()` for the seed upload.
The software fill is also moved to L0SyncQueueTy so it's only possible
with a synchronous queue.
Assisted-by: Codex
Second patch in the context series.
Outstanding-queue bookkeeping (queues destroyed while still busy) moves
from ol_device_impl_t to ol_context_impl_t, keyed by device. This keeps
backend queue resources from being reused across native contexts and
lets olDestroyContext drain everything it owns.
On the Level Zero side, LevelZeroPluginContextTy owns a ze_context and
an L0QueueCacheTy pooling idle queues per device bound to that
ze_context. L0ContextTy holds a DefaultUserCtx used by the libomptarget
path when no user context is set on the async info. Queue creation,
command-list creation and initAsyncInfoImpl all thread the plugin
context through so queues are bound to the right ze_context.
Assisted-by: Claude
---------
Co-authored-by: blazej-smorawski <blazej.smorawski@intel.com>
olMemcpy currently disallows host-to-host copies with a queue, even
though that is a desirable use case (e.g. to copy a buffer as a
dependency for another operation)
This PR adds support for asynchronous host-to-host copies by adding
`GenericDeviceTy::dataMemcpy` and the corresponding required
`dataMemcpyImpl` plugin operation. Unlike `dataSubmit`, `dataRetrieve`,
and `dataExchange`, this operation does not assign a device direction to
either pointer:
- CUDA: Uses `cuMemcpyAsync`, which by itself determines the pointer
types and preserves stream ordering. Dynamic CUDA symbol declarations
and `_v2` lookup support are included.
- Level Zero: Uses the existing queue `memoryCopy` operation (backed by
`zeCommandListAppendMemoryCopy`), which appends a memory-copy command to
the command list.
- AMDGPU: No "enqueue a host-to-host copy" operation exists directly in
that API, so we enqueue a `std::memcpy` callback through
`pushHostCallback`.
- Host: Call `memcpy` directly.
The `olMemcpy` API documentation now states that queued host-to-host
copies are ordered with other work in the queue. The public function
signature is unchanged.
A new unit test executes an `h2d -> d2h -> h2h -> h2d -> d2h` operation
chain, which should fail if the queue order isn't respected.
Assisted-by: Codex
Offload API functions may fail with error codes that shouldn't be
ignored. Most notably, if `olInit` fails and its error return value is
ignored, it is easy to use the library in an invalid uninitialized
state, which can and has caused confusion. In those cases, it may be
useful to have the ability to mark some API function with
`[[nodiscard]]`
This PR adds an optional `nodiscard` property to offload-tblgen's
`Function`, `Enum`, and `Struct`. If set, an `OL_NODISCARD` macro is
emitted, which expands to `[[nodiscard]]` on >=C++17 and >=C23, and to
nothing otherwise.
`nodiscard` is set for `ol_errc_t`, meaning every call to a function
that returns it will emit a compiler warning if the return value is
ignored and the TU is compiled on a supported language mode.
`libsycl` and `llvm-gpu-loader` still build cleanly and are unaffected
by the change.
Worth considering: should there be an opt-out (`#define
OL_DISABLE_NODISCARD` or similar)?
Assisted-by: Claude
Summary:
This provides users with a way to check all symbols present in a given
program. This is useful for many cases where a power user wants to do
something dynamic with the objects present.
At the previous community meeting, we agreed to introduce contexts into
the liboffload API. I also mentioned that, as part of this work, we
could split the allocation function into three separate functions, but
we did not discuss this idea in detail.
This patch only splits the allocation functions, allowing us to discuss
and agree on the proposed interface before introducing contexts into the
`olMemAlloc` API.
Once contexts are added, the device parameter will be removed from host
allocations, and the final interface would look like this:
```c
ol_result_t olMemAllocDevice(ol_context_handle_t, ol_device_handle_t, size_t, void **);
ol_result_t olMemAllocHost(ol_context_handle_t, size_t, void **);
ol_result_t olMemAllocManaged(ol_context_handle_t, ol_device_handle_t, size_t, void **);
```
Currently, for host allocations, the device parameter is required mainly
to determine which plugin should perform the allocation. Once contexts
are introduced, this information will be provided by the context, making
the device parameter redundant.
Requiring both a context and a device for host allocations could also be
misleading, since it is unclear what the device parameter actually
represents in this API.
Assisted by: Claude.
Add the initial Context handle API to liboffload:
- olCreateContext / olDestroyContext
- olGetContextInfo / olGetContextInfoSize
- OL_ERRC_INVALID_CONTEXT error code
- OL_CONTEXT_INFO_{NUM_DEVICES,DEVICES,PLATFORM} queries
This is the first patch in a series. I decided to split the original
change into multiple smaller PRs to make the review process faster and
more manageable.
This patch introduces context management functions, but the context
handle is not used anywhere yet. The following patches will extend the
API to use contexts in:
``` c
ol_result_t olMemAlloc(ol_context_handle_t, ol_device_handle_t, ol_alloc_type_t, size_t, void**);
ol_result_t olMemFree(ol_context_handle_t, void*);
ol_result_t olGetMemInfo(ol_context_handle_t, const void*, ol_mem_info_t, size_t, void*);
ol_result_t olGetMemInfoSize(ol_context_handle_t, const void*, ol_mem_info_t, size_t*);
ol_result_t olCreateQueue(ol_context_handle_t, ol_device_handle_t, ol_queue_handle_t*);
ol_result_t olCreateProgram(ol_context_handle_t, ol_device_handle_t, const void*, size_t, ol_program_handle_t*);
```
You can also take a look at #201398, which contains the first version of
the complete change. I'm cleaning it up as I go, so the patches in this
series are not a direct 1:1 split of that PR.
Even though L0, CUDA and HSA do not directly support filling memory
regions with non-power-of-two-sized patterns, plugins explicitly allow
for such fills by falling back to a slow path whenever a direct API call
is not possible.
The Level Zero plugin is the odd one out, forwarding directly to
`zeCommandListAppendMemoryFill`. This fails for non-power-of-two
patterns, causing unit tests for `olMemFill` to fail when run on L0.
This PR adds fallbacks in L0 plugin's `memoryFill` implementation to
support arbitrary pattern sizes:
- if all pattern bytes are the same, substitute `1` for `patternSize`
and proceed with the native fill
- if memory is host-accessible (host or shared alloc), then simply
`std::copy_n` the pattern
- if memory is device-only, upload a seed to the device, and
`memoryCopy` O(log n) times, doubling the pattern each time, until the
entire region is filled. The seed is the input pattern, but extended on
the host to 1-2KiB to potentially eliminate several small `memoryCopy`
calls that would otherwise be almost pure overhead.
Conceptually, this approach has better worst-case overhead than the one
found in the CUDA plugin (decompose the pattern to then run multiple
strided memsets) and the AMDGPU one (call `pushMemoryCopyH2DAsync` with
the pattern, setting `NumTimes`). Aligning the fallback fill approaches
is outside the scope of this PR, however - the main intent is to fix the
unit test failures.
liboffload plugins would not always exhaustively map the underlying
API's error values to ol_errc_t, resulting in unintended behavior - e.g.
olCreateProgram, given an invalid binary, would return OL_ERRC_UNKNOWN
instead of OL_ERRC_INVALID_BINARY.
This patch largely eliminates the most glaring cases of this by
assigning an ol_errc_t value to every error code of the underlying API
in every plugin. The proper granularity for this mapping is per-API
call, but that is a large rework that belongs in a separate patch.
Assisted-by: Claude
Adds olMemPrefetch and the OL_MEM_MIGRATION_FLAG_* enum, wired through a
new dataPrefetchImpl on the plugin interface with Level Zero and CUDA
implementations. Backends without prefetch support inherit the default
no-op.
Prefetch is a hint that migrates a USM allocation between the host and a
device so subsequent accesses on the target side are faster.
Assisted-by: Claude
This patch is the first step towards introducing alignment support in
memory allocations using liboffload, in order to enable SYCL
implementation of aligned allocations.
At the level of device allocators, it does not modify the Level Zero
code except for forwarding the alignment parameter, since Level Zero
already allows for specifying the alignment in its device allocator
implementation. For AMD and CUDA, it checks whether the alignment passed
by the caller is supported by the given backend; the reasoning behind
this verification is described in the following paragraphs. At the API
level, it adds a new function olMemAllocAligned, which is expected to
work similarly to olMemAlloc, with the difference that the buffers
returned by olMemAllocAligned should be aligned to the alignment passed
by the user. At the level of the plugin interface internal abstractions,
it adds a new argument Alignment to existing functions and delegates
memory allocation between olMemAllocAligned and olMemAlloc
implementations by using a common helper function.
The goal of the anticipated series of patches is to implement handling
of the alignment in the memory manager at the plugin interface level. At
the first stage, presented in this patch, the information about the
passed alignment is used mainly for checking whether the buffer returned
by the device allocators meets the requirements. In the case of the
requested memory size exceeding the thresholds of allocations handled by
the memory manager, the request is forwarded directly to the device.
Otherwise, the memory manager is responsible for allocating memory in
full pages and pooling it according to the requested chunks. In the
first scenario, the requested size, which is greater than the
aforementioned threshold, is usually a multiple of the page size.
Therefore, any alignment smaller than the page size would be correct.
Neither CUDA nor HSA provides users with the ability to specify the
alignment of the allocated memory. Their APIs include the alignment as
one of the possible arguments only in functions that reserve virtual
address space. CUDA enables users only to check the allocation
granularity, which is usually synonymous with the page size. In the case
of HSA, if the memory is allocated using a pool, the user is able to
check not only the granularity, but also the alignment of the buffers
allocated using the given pool. However, these values - granularity and
alignment - are defined only if
HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED is set to true, which
should always be set since the current implementation of the memory pool
for the AMD plugin in liboffload uses only hsa_amd_memory_pool_ts for
allocations. Only Level Zero accepts the alignment parameter during the
memory allocation process, but manages returned pointers internally.
Since pooling is also implemented in the memory manager at the plugin
level, such a design in the Level Zero device allocator duplicates
pooling in the whole application.
In the final version, the memory manager at the plugin interface level
will handle memory pooling and the buffer alignment from different
devices instead of delegating memory management to device allocator
implementations, as this would simplify the Level Zero plugin design and
provide AMD and CUDA plugins with support for the alignment in memory
allocations, which is not natively included in their APIs.
This PR changes olLaunchKernel to accept an array of pointers to
arguments:
```
void *ArgPtrs[] = {&A, &B, &C};
size_t ArgSizes[] = {sizeof(A), sizeof(B), sizeof(C)};
olLaunchKernel(Queue, Device, Kernel, &LaunchArgs, std::size(ArgPtrs), ArgPtrs, ArgSizes);
```
The newly proposed interface is implementable by existing and
anticipated
backends, is familiar to CUDA programmers, eliminates the extraneous
construction of a contiguous arguments buffer, replacing it with
constructing
an array of pointers, sidesteps the alignment requirements, does not
require reading program image metadata where it's impractical, and
enables
a compliant SYCL implementation to be built on top of it.
The ArgSizes array is required to support OpenCL, which does not have
native support for launching a kernel with an argument pointer array, or
a reliable way of retrieving argument sizes for a kernel.
## Mapping the proposed API to backends
CUDA and Level-Zero both support accepting an array of pointers to
kernel arguments, through `cuLaunchKernel`
(https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15)
and `zeCommandListAppendLaunchKernelWithArguments`
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments)
respectively.
For OpenCL, which requires the kernel arguments to be set separately
from the kernel launch, a potential implementation can extract the
number of arguments from the OpenCL API, and then iterate over the
argument pointer and size arrays:
```
cl_uint num_args = 0;
cl_int err = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS,
sizeof(num_args), &num_args, NULL);
for (cl_uint i = 0; i < num_args; ++i) {
clSetKernelArg(kernel, i, ArgSizes[i], ArgPtrs[i]);
}
```
The AMDGPU plugin needs to construct a contiguous buffer using the array
of argument pointers. To do this conversion, we need to have offsets
at which to place the arguments. Here, luckily, as mentioned before,
the AMD plugin already reads kernel metadata from the program image.
The implementation simply retrieves size and offset for each argument
from the kernel image, and then uses it to populate a buffer.
Summary:
Profiling requires getting time stamp information, which required
actually materializing barriers on the event. This caused performance
regressions in some OpenMP applications. Instead, we want to make this
opt in. This just adds a new argument to `olCreateEvent` which takes
some flags. Right now this is just none and profiling. Pretty mechanical
beyond that. Should revert this to the old behavior for OpenMP.
Co-authored-by: Kevin Sala Penades <kevinsala.ks@gmail.com>
Introduce a properties argument to olLaunchKernel to enable future
extensions.
This change adds initial extension for cooperative kernel launch.
The change restores the functionality from:
https://github.com/llvm/llvm-project/pull/184343
which was later reverted in:
https://github.com/llvm/llvm-project/pull/197463#184343 modified the API, and between the last rebase and the final
merge, additional tests were added
upstream(https://github.com/llvm/llvm-project/pull/193927) that still
relied on the previous API version.
Diff between this PR and #184343
```
diff --git a/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp b/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
index 0251bffefe60..cd527f18db38 100644
--- a/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
+++ b/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
@@ -241,8 +241,8 @@ TEST_P(olLaunchKernelSingleCounterSyncEventTest, SuccessSyncEvent) {
ArgsSingleCounter Args{LoopRange, NumberToAdd, (uint32_t *)InitValuePassed,
(uint32_t *)ResNum};
- ASSERT_SUCCESS(
- olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs));
+ ASSERT_SUCCESS(olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args),
+ &LaunchArgs, nullptr));
uint32_t FinalResVal = 0;
ASSERT_SUCCESS(olMemcpy(Queue, &FinalResVal, Host, ResNum, Device, Size));
@@ -294,8 +294,8 @@ TEST_P(olLaunchKernelSingleCounterSyncEventTest, SuccessTwoQueues) {
ArgsSingleCounter Args{LoopRange, NumberToAdd, (uint32_t *)InitValuePassed,
(uint32_t *)ResNum1};
- ASSERT_SUCCESS(
- olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs));
+ ASSERT_SUCCESS(olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args),
+ &LaunchArgs, nullptr));
ol_event_handle_t Event = nullptr;
ASSERT_SUCCESS(olCreateEvent(Queue, &Event));
@@ -308,7 +308,7 @@ TEST_P(olLaunchKernelSingleCounterSyncEventTest, SuccessTwoQueues) {
// been completed by the time the kernel is executed using the second queue,
// the FinalResVal would be incorrect.
ASSERT_SUCCESS(olLaunchKernel(Queue2, Device, Kernel, &Args2, sizeof(Args2),
- &LaunchArgs));
+ &LaunchArgs, nullptr));
ASSERT_SUCCESS(olSyncQueue(Queue2));
uint32_t FinalResVal = 0;
```
Add device info queries to detect support for half-, single-, and
double-precision floating-point formats.
For the AMDGPU, CUDA, and Host plugins, add the new queries alongside
the existing capability reporting without changing current behavior.
For the Level Zero plugin, implement floating-point support detection
and capability querying.
This patch adds `olGetEventElapsedTime` to the new LLVM Offload API, as
requested in
[#185728](https://github.com/llvm/llvm-project/issues/185728), and adds
the corresponding support in `plugins-nextgen`.
A main motivation for this change is to make it possible to measure the
elapsed time of work submitted to a queue, especially kernel launches.
This is relevant to the intended use of the new Offload API for
microbenchmarking GPU libc math functions.
### Summary
The new API returns the elapsed time, in milliseconds, between two
events on the same device.
To support the common pattern `create start event → enqueue kernel →
create end event → sync end event → get elapsed time`, `olCreateEvent`
now always creates and records a backend event through the device
interface. For backends that materialize real event state, this gives
the event concrete backend state that can be used for elapsed-time
measurement. For backends that do not materialize backend event state,
`EventInfo` may still remain null and existing event operations continue
to treat such events as trivially complete.
Previously, an event created on an empty queue could be represented only
as a logical event. That representation was sufficient for sync and
completion queries, but it was not suitable for elapsed-time measurement
because there was no backend event state to timestamp. The new behavior
preserves the meaning of completion of prior work while also allowing
backends with timing support to attach real event state.
### Changes in `plugins-nextgen`
#### Common interface
Add elapsed-time support to the common device and plugin interfaces:
* `GenericPluginTy::get_event_elapsed_time`
* `GenericDeviceTy::getEventElapsedTime`
* `GenericDeviceTy::getEventElapsedTimeImpl`
#### AMDGPU
* Add the required ROCr declarations and wrappers.
* Enable queue profiling at queue creation time.
* Record events by enqueuing a real barrier marker packet on the stream.
* Retain the timing signal needed to query the recorded marker later.
* Implement `getEventElapsedTimeImpl` using
`hsa_amd_profiling_get_dispatch_time`, converting the result to
milliseconds with `HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY`.
This follows the ROCm/HIP approach of enabling queue profiling at HSA
queue creation time, while keeping the AMDGPU queue path simpler than
the lazy-enable alternative discussed during review.
#### CUDA
* Add the required CUDA driver declarations and wrappers.
* Implement `getEventElapsedTimeImpl` with `cuEventElapsedTime`.
#### Host
* Add `getEventElapsedTimeImpl` that stores `0.0f` in the output
pointer, when present, and returns success.
Reason: the host plugin does not materialize backend event state and
already treats event operations as trivially successful. Returning
`0.0f` preserves that model without introducing a new failure mode.
#### Level Zero
* Add `getEventElapsedTimeImpl`, but leave it unimplemented.
Reason: the Level Zero plugin currently does not provide standalone
backend event support for this event model. For example, `waitEventImpl`
/ `syncEventImpl` are still unimplemented there.
---------
Signed-off-by: Leandro Augusto Lacerda Campos <leandrolcampos@yahoo.com.br>
Signed-off-by: Leandro A. Lacerda Campos <leandrolcampos@yahoo.com.br>