13#include "level_zero/ze_api.h"
22#include <unordered_set>
27auto catchAll(F &&func) {
30 }
catch (
const std::exception &e) {
31 std::cerr <<
"An exception was thrown: " << e.what() << std::endl;
34 std::cerr <<
"An unknown exception was thrown." << std::endl;
39#define L0_SAFE_CALL(call) \
41 ze_result_t status = (call); \
42 if (status != ZE_RESULT_SUCCESS) { \
43 const char *errorString; \
44 zeDriverGetLastErrorDescription(NULL, &errorString); \
45 std::cerr << "L0 error " << status << ": " << errorString << std::endl; \
58static ze_driver_handle_t
getDriver(uint32_t idx = 0) {
59 ze_init_driver_type_desc_t driver_type = {};
60 driver_type.stype = ZE_STRUCTURE_TYPE_INIT_DRIVER_TYPE_DESC;
61 driver_type.flags = ZE_INIT_DRIVER_TYPE_FLAG_GPU;
62 driver_type.pNext =
nullptr;
63 uint32_t driverCount{0};
64 thread_local static std::vector<ze_driver_handle_t> drivers;
65 thread_local static bool isDriverInitialised{
false};
66 if (isDriverInitialised && idx < drivers.size())
68 L0_SAFE_CALL(zeInitDrivers(&driverCount,
nullptr, &driver_type));
70 throw std::runtime_error(
"No L0 drivers found.");
71 drivers.resize(driverCount);
72 L0_SAFE_CALL(zeInitDrivers(&driverCount, drivers.data(), &driver_type));
73 if (idx >= driverCount)
74 throw std::runtime_error(std::string(
"Requested driver idx out-of-bound, "
75 "number of availabe drivers: ") +
76 std::to_string(driverCount));
77 isDriverInitialised =
true;
81static ze_device_handle_t
getDevice(
const uint32_t driverIdx = 0,
82 const int32_t devIdx = 0) {
83 thread_local static ze_device_handle_t l0Device;
84 thread_local int32_t currDevIdx{-1};
85 thread_local uint32_t currDriverIdx{0};
86 if (currDriverIdx == driverIdx && currDevIdx == devIdx)
89 uint32_t deviceCount{0};
90 L0_SAFE_CALL(zeDeviceGet(driver, &deviceCount,
nullptr));
92 throw std::runtime_error(
"getDevice failed: did not find L0 device.");
93 if (
static_cast<int>(deviceCount) < devIdx + 1)
94 throw std::runtime_error(
"getDevice failed: devIdx out-of-bounds.");
95 std::vector<ze_device_handle_t> devices(deviceCount);
96 L0_SAFE_CALL(zeDeviceGet(driver, &deviceCount, devices.data()));
97 l0Device = devices[devIdx];
98 currDriverIdx = driverIdx;
104static ze_context_handle_t
getContext(ze_driver_handle_t driver) {
105 thread_local static ze_context_handle_t context;
106 thread_local static bool isContextInitialised{
false};
107 if (isContextInitialised)
109 ze_context_desc_t ctxtDesc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC,
nullptr, 0};
110 L0_SAFE_CALL(zeContextCreate(driver, &ctxtDesc, &context));
111 isContextInitialised =
true;
133 std::unique_ptr<std::remove_pointer<ze_context_handle_t>::type,
136 std::unique_ptr<std::remove_pointer<ze_command_list_handle_t>::type,
158 uint32_t computeEngineOrdinal = -1u, copyEngineOrdinal = -1u;
159 ze_device_properties_t deviceProperties{};
161 uint32_t queueGroupCount = 0;
163 device, &queueGroupCount,
nullptr));
164 std::vector<ze_command_queue_group_properties_t> queueGroupProperties(
167 device, &queueGroupCount, queueGroupProperties.data()));
169 for (uint32_t queueGroupIdx = 0; queueGroupIdx < queueGroupCount;
171 const auto &group = queueGroupProperties[queueGroupIdx];
172 if (group.flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE)
173 computeEngineOrdinal = queueGroupIdx;
174 else if (group.flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY) {
175 copyEngineOrdinal = queueGroupIdx;
178 if (copyEngineOrdinal != -1u && computeEngineOrdinal != -1u)
183 if (copyEngineOrdinal == -1u)
184 copyEngineOrdinal = computeEngineOrdinal;
186 assert(copyEngineOrdinal != -1u && computeEngineOrdinal != -1u &&
187 "Expected two engines to be available.");
190 ze_command_queue_desc_t cmdQueueDesc{
191 ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC,
196 ZE_COMMAND_QUEUE_MODE_ASYNCHRONOUS,
197 ZE_COMMAND_QUEUE_PRIORITY_NORMAL};
199 ze_command_list_handle_t rawCmdListCopy =
nullptr;
201 &cmdQueueDesc, &rawCmdListCopy));
205 cmdQueueDesc.ordinal = computeEngineOrdinal;
206 ze_command_list_handle_t rawCmdListCompute =
nullptr;
234 std::unique_ptr<std::remove_pointer<ze_event_handle_t>::type,
237 std::unique_ptr<std::remove_pointer<ze_event_pool_handle_t>::type,
270 assert(
takenEvents.empty() &&
"Some events were not released");
274 ze_event_pool_desc_t eventPoolDesc = {};
275 eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
276 eventPoolDesc.count = numEvents;
278 ze_event_pool_handle_t rawPool =
nullptr;
280 &
rtCtx->device, &rawPool));
287 ze_event_handle_t rawEvent =
nullptr;
293 rawEvent = uniqueEvent.get();
297 throw std::runtime_error(
"DynamicEventPool: reached max events limit");
302 ze_event_desc_t eventDesc = {
303 ZE_STRUCTURE_TYPE_EVENT_DESC,
nullptr,
305 ZE_EVENT_SCOPE_FLAG_DEVICE, ZE_EVENT_SCOPE_FLAG_HOST};
307 ze_event_handle_t newEvent =
nullptr;
309 zeEventCreate(
eventPools.back().get(), &eventDesc, &newEvent));
322 "Attempting to release unknown or already released event");
353 void sync(ze_event_handle_t explicitEvent =
nullptr) {
354 ze_event_handle_t syncEvent{
nullptr};
355 if (!explicitEvent) {
357 syncEvent = lastImplicitEventPtr ? *lastImplicitEventPtr :
nullptr;
359 syncEvent = explicitEvent;
363 syncEvent, std::numeric_limits<uint64_t>::max()));
371 template <
typename Func>
373 ze_event_handle_t newImplicitEvent =
dynEventPool.takeEvent();
375 const uint32_t numWaitEvents = lastImplicitEventPtr ? 1 : 0;
376 std::forward<Func>(op)(newImplicitEvent, numWaitEvents,
377 lastImplicitEventPtr);
382static ze_module_handle_t
loadModule(
const void *data,
size_t dataSize) {
384 ze_module_handle_t zeModule;
385 ze_module_desc_t desc = {ZE_STRUCTURE_TYPE_MODULE_DESC,
387 ZE_MODULE_FORMAT_IL_SPIRV,
389 (
const uint8_t *)data,
392 ze_module_build_log_handle_t buildLogHandle;
395 &zeModule, &buildLogHandle);
396 if (
result != ZE_RESULT_SUCCESS) {
397 std::cerr <<
"Error creating module, error code: " <<
result << std::endl;
399 L0_SAFE_CALL(zeModuleBuildLogGetString(buildLogHandle, &logSize,
nullptr));
400 std::string buildLog(
" ", logSize);
402 zeModuleBuildLogGetString(buildLogHandle, &logSize, buildLog.data()));
403 std::cerr <<
"Build log:\n" << buildLog << std::endl;
425 ze_event_handle_t event) {
426 assert(stream &&
"Invalid stream");
427 assert(event &&
"Invalid event");
441 zeEventHostSynchronize(event, std::numeric_limits<uint64_t>::max()));
455 return catchAll([&]() {
456 void *memPtr =
nullptr;
457 constexpr size_t alignment{64};
458 ze_device_mem_alloc_desc_t deviceDesc = {};
459 deviceDesc.stype = ZE_STRUCTURE_TYPE_DEVICE_MEM_ALLOC_DESC;
461 ze_host_mem_alloc_desc_t hostDesc = {};
462 hostDesc.stype = ZE_STRUCTURE_TYPE_HOST_MEM_ALLOC_DESC;
464 &hostDesc, size, alignment,
472 throw std::runtime_error(
"mem allocation failed!");
483extern "C" void mgpuMemcpy(
void *dst,
void *src,
size_t sizeBytes,
485 stream->
enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
486 ze_event_handle_t *waitEvents) {
489 numWaitEvents, waitEvents));
493template <
typename PATTERN_TYPE>
494static void mgpuMemset(
void *dst, PATTERN_TYPE value,
size_t count,
501 stream->
enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
502 ze_event_handle_t *waitEvents) {
504 listType, dst, &value,
sizeof(PATTERN_TYPE),
505 count *
sizeof(PATTERN_TYPE), newEvent, numWaitEvents, waitEvents));
508extern "C" void mgpuMemset32(
void *dst,
unsigned int value,
size_t count,
513extern "C" void mgpuMemset16(
void *dst,
unsigned short value,
size_t count,
519 size_t gpuBlobSize) {
520 return catchAll([&]() {
return loadModule(data, gpuBlobSize); });
525 assert(module && name);
526 ze_kernel_handle_t zeKernel;
527 ze_kernel_desc_t desc = {};
528 desc.pKernelName = name;
534 size_t gridY,
size_t gridZ,
size_t blockX,
535 size_t blockY,
size_t blockZ,
537 void **params,
void ** ,
538 size_t paramsCount) {
540 if (sharedMemBytes > 0) {
541 paramsCount = paramsCount - 1;
543 zeKernelSetArgumentValue(kernel, paramsCount, sharedMemBytes,
nullptr));
545 for (
size_t i = 0; i < paramsCount; ++i)
546 L0_SAFE_CALL(zeKernelSetArgumentValue(kernel,
static_cast<uint32_t
>(i),
547 sizeof(
void *), params[i]));
548 L0_SAFE_CALL(zeKernelSetGroupSize(kernel, blockX, blockY, blockZ));
549 ze_group_count_t dispatch;
550 dispatch.groupCountX =
static_cast<uint32_t
>(gridX);
551 dispatch.groupCountY =
static_cast<uint32_t
>(gridY);
552 dispatch.groupCountZ =
static_cast<uint32_t
>(gridZ);
553 stream->
enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
554 ze_event_handle_t *waitEvents) {
557 numWaitEvents, waitEvents));
std::unique_ptr< std::remove_pointer< ze_event_handle_t >::type, ZeEventDeleter > UniqueZeEvent
void mgpuSetDefaultDevice(int32_t devIdx)
static ze_module_handle_t loadModule(const void *data, size_t dataSize)
static L0RTContextWrapper & getRtContext()
void mgpuMemset16(void *dst, unsigned short value, size_t count, StreamWrapper *stream)
#define L0_SAFE_CALL(call)
static void mgpuMemset(void *dst, PATTERN_TYPE value, size_t count, StreamWrapper *stream)
static ze_device_handle_t getDevice(const uint32_t driverIdx=0, const int32_t devIdx=0)
static DynamicEventPool & getDynamicEventPool()
std::unique_ptr< std::remove_pointer< ze_context_handle_t >::type, ZeContextDeleter > UniqueZeContext
void * mgpuMemAlloc(uint64_t size, StreamWrapper *stream, bool isShared)
void mgpuStreamDestroy(StreamWrapper *stream)
ze_module_handle_t mgpuModuleLoad(const void *data, size_t gpuBlobSize)
void mgpuEventSynchronize(ze_event_handle_t event)
void mgpuModuleUnload(ze_module_handle_t module)
static ze_driver_handle_t getDriver(uint32_t idx=0)
void mgpuMemset32(void *dst, unsigned int value, size_t count, StreamWrapper *stream)
StreamWrapper * mgpuStreamCreate()
std::unique_ptr< std::remove_pointer< ze_command_list_handle_t >::type, ZeCommandListDeleter > UniqueZeCommandList
void mgpuEventDestroy(ze_event_handle_t event)
void mgpuStreamSynchronize(StreamWrapper *stream)
ze_kernel_handle_t mgpuModuleGetFunction(ze_module_handle_t module, const char *name)
void mgpuMemcpy(void *dst, void *src, size_t sizeBytes, StreamWrapper *stream)
void mgpuStreamWaitEvent(StreamWrapper *stream, ze_event_handle_t event)
void mgpuMemFree(void *ptr, StreamWrapper *stream)
void mgpuEventRecord(ze_event_handle_t event, StreamWrapper *stream)
ze_event_handle_t mgpuEventCreate()
std::unique_ptr< std::remove_pointer< ze_event_pool_handle_t >::type, ZeEventPoolDeleter > UniqueZeEventPool
void mgpuLaunchKernel(ze_kernel_handle_t kernel, size_t gridX, size_t gridY, size_t gridZ, size_t blockX, size_t blockY, size_t blockZ, size_t sharedMemBytes, StreamWrapper *stream, void **params, void **, size_t paramsCount)
void createNewPool(size_t numEvents)
L0RTContextWrapper * rtCtx
DynamicEventPool & operator=(const DynamicEventPool &)=delete
static constexpr size_t numEventsPerPool
void releaseEvent(ze_event_handle_t event)
DynamicEventPool(DynamicEventPool &&) noexcept=default
DynamicEventPool(L0RTContextWrapper *rtCtx)
std::vector< UniqueZeEventPool > eventPools
std::unordered_map< ze_event_handle_t, UniqueZeEvent > takenEvents
ze_event_handle_t takeEvent()
std::vector< UniqueZeEvent > availableEvents
DynamicEventPool(const DynamicEventPool &)=delete
size_t currentEventsLimit
UniqueZeCommandList immCmdListCopy
L0RTContextWrapper()=default
L0RTContextWrapper & operator=(const L0RTContextWrapper &)=delete
uint32_t copyEngineMaxMemoryFillPatternSize
ze_device_handle_t device
L0RTContextWrapper(L0RTContextWrapper &&) noexcept=default
L0RTContextWrapper(const uint32_t driverIdx=0, const int32_t devIdx=0)
ze_driver_handle_t driver
UniqueZeCommandList immCmdListCompute
L0RTContextWrapper(const L0RTContextWrapper &)=delete
ze_event_handle_t * getLastImplicitEventPtr()
void sync(ze_event_handle_t explicitEvent=nullptr)
StreamWrapper(DynamicEventPool &dynEventPool)
std::deque< ze_event_handle_t > implicitEventStack
DynamicEventPool & dynEventPool
void enqueueOp(Func &&op)
void operator()(ze_command_list_handle_t cmdList) const
void operator()(ze_context_handle_t ctx) const
void operator()(ze_event_handle_t event) const
void operator()(ze_event_pool_handle_t pool) const