MLIR 24.0.0git
LevelZeroRuntimeWrappers.cpp
Go to the documentation of this file.
1//===- LevelZeroRuntimeWrappers.cpp - MLIR Level Zero (L0) wrapper library-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implements wrappers around the Level Zero (L0) runtime library with C linkage
10//
11//===----------------------------------------------------------------------===//
12
13#include "level_zero/ze_api.h"
14#include <cassert>
15#include <cstring>
16#include <deque>
17#include <exception>
18#include <functional>
19#include <iostream>
20#include <limits>
21#include <memory>
22#include <stdexcept>
23#include <string>
24#include <unordered_map>
25#include <vector>
26
27#ifdef _WIN32
28#define MLIR_LEVELZERO_WRAPPERS_EXPORT __declspec(dllexport)
29#else
30#define MLIR_LEVELZERO_WRAPPERS_EXPORT __attribute__((visibility("default")))
31#endif // _WIN32
32
33namespace {
34template <typename F>
35auto catchAll(F &&func) {
36 try {
37 return func();
38 } catch (const std::exception &e) {
39 std::cerr << "An exception was thrown: " << e.what() << std::endl;
40 std::abort();
41 } catch (...) {
42 std::cerr << "An unknown exception was thrown." << std::endl;
43 std::abort();
44 }
45}
46
47#define L0_SAFE_CALL(call) \
48 { \
49 ze_result_t status = (call); \
50 if (status != ZE_RESULT_SUCCESS) { \
51 const char *errorString; \
52 ze_result_t descriptionStatus = \
53 zeDriverGetLastErrorDescriptionWrapper(&errorString); \
54 if (descriptionStatus == ZE_RESULT_SUCCESS && errorString) \
55 std::cerr << "L0 error " << status << ": " << errorString \
56 << std::endl; \
57 else \
58 std::cerr << "Level Zero call failed: " << #call << ", status=0x" \
59 << std::hex << static_cast<uint32_t>(status) << std::dec \
60 << std::endl; \
61 std::abort(); \
62 } \
63 }
64} // namespace
65
66static ze_result_t
67zeDriverGetLastErrorDescriptionWrapper(const char **errorString);
68
69//===----------------------------------------------------------------------===//
70// L0 RT context & device setters
71//===----------------------------------------------------------------------===//
72
73// Returns the L0 driver handle for the given index. Default index is 0
74// (i.e., returns the first driver handle of the available drivers).
75
76static ze_driver_handle_t getDriver(uint32_t idx = 0) {
77 ze_init_driver_type_desc_t driver_type = {};
78 driver_type.stype = ZE_STRUCTURE_TYPE_INIT_DRIVER_TYPE_DESC;
79 driver_type.flags = ZE_INIT_DRIVER_TYPE_FLAG_GPU;
80 driver_type.pNext = nullptr;
81 uint32_t driverCount{0};
82 thread_local static std::vector<ze_driver_handle_t> drivers;
83 thread_local static bool isDriverInitialised{false};
84 if (isDriverInitialised && idx < drivers.size())
85 return drivers[idx];
86 L0_SAFE_CALL(zeInitDrivers(&driverCount, nullptr, &driver_type));
87 if (!driverCount)
88 throw std::runtime_error("No L0 drivers found.");
89 drivers.resize(driverCount);
90 L0_SAFE_CALL(zeInitDrivers(&driverCount, drivers.data(), &driver_type));
91 if (idx >= driverCount)
92 throw std::runtime_error(std::string("Requested driver idx out-of-bound, "
93 "number of availabe drivers: ") +
94 std::to_string(driverCount));
95 isDriverInitialised = true;
96 return drivers[idx];
97}
98
99static ze_device_handle_t getDevice(const uint32_t driverIdx = 0,
100 const int32_t devIdx = 0) {
101 thread_local static ze_device_handle_t l0Device;
102 thread_local int32_t currDevIdx{-1};
103 thread_local uint32_t currDriverIdx{0};
104 if (currDriverIdx == driverIdx && currDevIdx == devIdx)
105 return l0Device;
106 auto driver = getDriver(driverIdx);
107 uint32_t deviceCount{0};
108 L0_SAFE_CALL(zeDeviceGet(driver, &deviceCount, nullptr));
109 if (!deviceCount)
110 throw std::runtime_error("getDevice failed: did not find L0 device.");
111 if (static_cast<int>(deviceCount) < devIdx + 1)
112 throw std::runtime_error("getDevice failed: devIdx out-of-bounds.");
113 std::vector<ze_device_handle_t> devices(deviceCount);
114 L0_SAFE_CALL(zeDeviceGet(driver, &deviceCount, devices.data()));
115 l0Device = devices[devIdx];
116 currDriverIdx = driverIdx;
117 currDevIdx = devIdx;
118 return l0Device;
119}
120
121// Returns the default L0 context of the defult driver.
122static ze_context_handle_t getContext(ze_driver_handle_t driver) {
123 thread_local static ze_context_handle_t context;
124 thread_local static bool isContextInitialised{false};
125 if (isContextInitialised)
126 return context;
127 ze_context_desc_t ctxtDesc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
128 L0_SAFE_CALL(zeContextCreate(driver, &ctxtDesc, &context));
129 isContextInitialised = true;
130 return context;
131}
132
133//===----------------------------------------------------------------------===//
134// L0 RT helper structs
135//===----------------------------------------------------------------------===//
136
138 void operator()(ze_context_handle_t ctx) const {
139 if (ctx)
140 L0_SAFE_CALL(zeContextDestroy(ctx));
141 }
142};
143
145 void operator()(ze_command_list_handle_t cmdList) const {
146 if (cmdList)
147 L0_SAFE_CALL(zeCommandListDestroy(cmdList));
148 }
149};
151 std::unique_ptr<std::remove_pointer<ze_context_handle_t>::type,
154 std::unique_ptr<std::remove_pointer<ze_command_list_handle_t>::type,
157 ze_driver_handle_t driver{nullptr};
158 ze_device_handle_t device{nullptr};
160 // Usually, one immediate command list with ordinal 0 suffices for
161 // both copy and compute ops, but leaves HW underutilized.
163 // Copy engines can be used for both memcpy and memset, but
164 // they have limitations for memset pattern size (e.g., 1 byte).
167
169 L0RTContextWrapper(const uint32_t driverIdx = 0, const int32_t devIdx = 0)
170 : driver(getDriver(driverIdx)), device(getDevice(devIdx)) {
171 // Create context
172 ze_context_handle_t ctx = getContext(driver);
173 context.reset(ctx);
174
175 // Determine ordinals
176 uint32_t computeEngineOrdinal = -1u, copyEngineOrdinal = -1u;
177 ze_device_properties_t deviceProperties{};
178 L0_SAFE_CALL(zeDeviceGetProperties(device, &deviceProperties));
179 uint32_t queueGroupCount = 0;
180 L0_SAFE_CALL(zeDeviceGetCommandQueueGroupProperties(
181 device, &queueGroupCount, nullptr));
182 std::vector<ze_command_queue_group_properties_t> queueGroupProperties(
183 queueGroupCount);
184 L0_SAFE_CALL(zeDeviceGetCommandQueueGroupProperties(
185 device, &queueGroupCount, queueGroupProperties.data()));
186
187 for (uint32_t queueGroupIdx = 0; queueGroupIdx < queueGroupCount;
188 ++queueGroupIdx) {
189 const auto &group = queueGroupProperties[queueGroupIdx];
190 if (group.flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE)
191 computeEngineOrdinal = queueGroupIdx;
192 else if (group.flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY) {
193 copyEngineOrdinal = queueGroupIdx;
194 copyEngineMaxMemoryFillPatternSize = group.maxMemoryFillPatternSize;
195 }
196 if (copyEngineOrdinal != -1u && computeEngineOrdinal != -1u)
197 break;
198 }
199
200 // Fallback to the default queue if no dedicated copy queue is available.
201 if (copyEngineOrdinal == -1u)
202 copyEngineOrdinal = computeEngineOrdinal;
203
204 assert(copyEngineOrdinal != -1u && computeEngineOrdinal != -1u &&
205 "Expected two engines to be available.");
206
207 // Create copy command list
208 ze_command_queue_desc_t cmdQueueDesc{
209 ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC,
210 nullptr,
211 copyEngineOrdinal, // ordinal
212 0, // index (assume one physical engine in the group)
213 0, // flags
214 ZE_COMMAND_QUEUE_MODE_ASYNCHRONOUS,
215 ZE_COMMAND_QUEUE_PRIORITY_NORMAL};
216
217 ze_command_list_handle_t rawCmdListCopy = nullptr;
218 L0_SAFE_CALL(zeCommandListCreateImmediate(context.get(), device,
219 &cmdQueueDesc, &rawCmdListCopy));
220 immCmdListCopy.reset(rawCmdListCopy);
221
222 // Create compute command list
223 cmdQueueDesc.ordinal = computeEngineOrdinal;
224 ze_command_list_handle_t rawCmdListCompute = nullptr;
225 L0_SAFE_CALL(zeCommandListCreateImmediate(
226 context.get(), device, &cmdQueueDesc, &rawCmdListCompute));
227 immCmdListCompute.reset(rawCmdListCompute);
228 }
231 // Allow move
233 L0RTContextWrapper &operator=(L0RTContextWrapper &&) noexcept = default;
234 ~L0RTContextWrapper() = default;
235};
236
238 void operator()(ze_event_handle_t event) const {
239 if (event)
240 L0_SAFE_CALL(zeEventDestroy(event));
241 }
242};
243
245 void operator()(ze_event_pool_handle_t pool) const {
246 if (pool)
247 L0_SAFE_CALL(zeEventPoolDestroy(pool));
248 }
249};
250
252 std::unique_ptr<std::remove_pointer<ze_event_handle_t>::type,
255 std::unique_ptr<std::remove_pointer<ze_event_pool_handle_t>::type,
257
258// L0 only supports pre-determined sizes of event pools,
259// implement a runtime data structure to avoid running out of events.
260
262 constexpr static size_t numEventsPerPool{128};
263
264 std::vector<UniqueZeEventPool> eventPools;
265 std::vector<UniqueZeEvent> availableEvents;
266 std::unordered_map<ze_event_handle_t, UniqueZeEvent> takenEvents;
267
268 // Limit the number of events to avoid running out of memory.
269 // The limit is set to 32K events, which should be sufficient for most use
270 // cases.
271 size_t maxEventsCount{32768}; // 32K events
275
279
282
283 // Allow move
284 DynamicEventPool(DynamicEventPool &&) noexcept = default;
285 DynamicEventPool &operator=(DynamicEventPool &&) noexcept = default;
286
288 assert(takenEvents.empty() && "Some events were not released");
289 }
290
291 void createNewPool(size_t numEvents) {
292 ze_event_pool_desc_t eventPoolDesc = {};
293 eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
294 eventPoolDesc.count = numEvents;
295
296 ze_event_pool_handle_t rawPool = nullptr;
297 L0_SAFE_CALL(zeEventPoolCreate(rtCtx->context.get(), &eventPoolDesc, 1,
298 &rtCtx->device, &rawPool));
299
300 eventPools.emplace_back(UniqueZeEventPool(rawPool));
301 currentEventsLimit += numEvents;
302 }
303
304 ze_event_handle_t takeEvent() {
305 ze_event_handle_t rawEvent = nullptr;
306
307 if (!availableEvents.empty()) {
308 // Reuse one
309 auto uniqueEvent = std::move(availableEvents.back());
310 availableEvents.pop_back();
311 rawEvent = uniqueEvent.get();
312 takenEvents[rawEvent] = std::move(uniqueEvent);
313 } else {
315 throw std::runtime_error("DynamicEventPool: reached max events limit");
316 }
319
320 ze_event_desc_t eventDesc = {
321 ZE_STRUCTURE_TYPE_EVENT_DESC, nullptr,
322 static_cast<uint32_t>(currentEventsCnt % numEventsPerPool),
323 ZE_EVENT_SCOPE_FLAG_DEVICE, ZE_EVENT_SCOPE_FLAG_HOST};
324
325 ze_event_handle_t newEvent = nullptr;
327 zeEventCreate(eventPools.back().get(), &eventDesc, &newEvent));
328
329 takenEvents[newEvent] = UniqueZeEvent(newEvent);
330 rawEvent = newEvent;
332 }
333
334 return rawEvent;
335 }
336
337 void releaseEvent(ze_event_handle_t event) {
338 auto it = takenEvents.find(event);
339 assert(it != takenEvents.end() &&
340 "Attempting to release unknown or already released event");
341
342 L0_SAFE_CALL(zeEventHostReset(event));
343 availableEvents.emplace_back(std::move(it->second));
344 takenEvents.erase(it);
345 }
346};
347
349 thread_local static L0RTContextWrapper rtContext(0);
350 return rtContext;
351}
352
354 thread_local static DynamicEventPool dynEventPool{&getRtContext()};
355 return dynEventPool;
356}
357
358static ze_result_t
359zeDriverGetLastErrorDescriptionWrapper(const char **errorString) {
360 return zeDriverGetLastErrorDescription(getRtContext().driver, errorString);
361}
362
364 // avoid event pointer invalidations
365 std::deque<ze_event_handle_t> implicitEventStack;
367
370
371 ze_event_handle_t *getLastImplicitEventPtr() {
372 // Assume current implicit events will not be used after `sync`.
373 return implicitEventStack.size() ? &implicitEventStack.back() : nullptr;
374 }
375
376 void sync(ze_event_handle_t explicitEvent = nullptr) {
377 ze_event_handle_t syncEvent{nullptr};
378 if (!explicitEvent) {
379 ze_event_handle_t *lastImplicitEventPtr = getLastImplicitEventPtr();
380 syncEvent = lastImplicitEventPtr ? *lastImplicitEventPtr : nullptr;
381 } else {
382 syncEvent = explicitEvent;
383 }
384 if (syncEvent)
385 L0_SAFE_CALL(zeEventHostSynchronize(
386 syncEvent, std::numeric_limits<uint64_t>::max()));
387 // All of the "implicit" events were signaled and are of no use, release
388 // them. "explicit" event must be "released" via mgpuEventDestroy
389 for (auto event : implicitEventStack)
390 dynEventPool.releaseEvent(event);
391 implicitEventStack.clear();
392 }
393
394 template <typename Func>
395 void enqueueOp(Func &&op) {
396 ze_event_handle_t newImplicitEvent = dynEventPool.takeEvent();
397 ze_event_handle_t *lastImplicitEventPtr = getLastImplicitEventPtr();
398 const uint32_t numWaitEvents = lastImplicitEventPtr ? 1 : 0;
399 std::forward<Func>(op)(newImplicitEvent, numWaitEvents,
400 lastImplicitEventPtr);
401 implicitEventStack.push_back(newImplicitEvent);
402 }
403};
404
405static ze_module_handle_t
406loadModule(const void *data, size_t dataSize,
407 ze_module_format_t format = ZE_MODULE_FORMAT_NATIVE) {
408 assert(data);
409 ze_module_handle_t zeModule;
410 ze_module_desc_t desc = {
411 ZE_STRUCTURE_TYPE_MODULE_DESC, nullptr, format, dataSize,
412 (const uint8_t *)data, nullptr, nullptr};
413
414 ze_module_build_log_handle_t buildLogHandle;
415 ze_result_t result =
416 zeModuleCreate(getRtContext().context.get(), getRtContext().device, &desc,
417 &zeModule, &buildLogHandle);
418 if (result != ZE_RESULT_SUCCESS) {
419 std::cerr << "Error creating module, error code: " << result << std::endl;
420 size_t logSize = 0;
421 L0_SAFE_CALL(zeModuleBuildLogGetString(buildLogHandle, &logSize, nullptr));
422 std::string buildLog(" ", logSize);
424 zeModuleBuildLogGetString(buildLogHandle, &logSize, buildLog.data()));
425 std::cerr << "Build log:\n" << buildLog << std::endl;
426 std::abort();
427 }
428 return zeModule;
429}
430
431//===----------------------------------------------------------------------===//
432// L0 Wrappers definition
433//===----------------------------------------------------------------------===//
434
438
439extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
441 if (stream)
442 stream->sync();
443}
444
445extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
447 delete stream;
448}
449
450extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
451mgpuStreamWaitEvent(StreamWrapper *stream, ze_event_handle_t event) {
452 assert(stream && "Invalid stream");
453 assert(event && "Invalid event");
454 stream->sync(event);
455}
456
457extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT ze_event_handle_t mgpuEventCreate() {
459}
460
461extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
462mgpuEventDestroy(ze_event_handle_t event) {
463 return getDynamicEventPool().releaseEvent(event);
464}
465
466extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
467mgpuEventSynchronize(ze_event_handle_t event) {
469 zeEventHostSynchronize(event, std::numeric_limits<uint64_t>::max()));
470 L0_SAFE_CALL(zeEventHostReset(event));
471}
472
473extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
474mgpuEventRecord(ze_event_handle_t event, StreamWrapper *stream) {
475 L0_SAFE_CALL(zeCommandListAppendSignalEvent(
476 getRtContext().immCmdListCopy.get(), event));
477 L0_SAFE_CALL(zeCommandListAppendSignalEvent(
478 getRtContext().immCmdListCompute.get(), event));
479}
480
481extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void *
482mgpuMemAlloc(uint64_t size, StreamWrapper *stream, bool isShared) {
483 return catchAll([&]() {
484 void *memPtr = nullptr;
485 constexpr size_t alignment{64};
486 ze_device_mem_alloc_desc_t deviceDesc = {};
487 deviceDesc.stype = ZE_STRUCTURE_TYPE_DEVICE_MEM_ALLOC_DESC;
488 if (isShared) {
489 ze_host_mem_alloc_desc_t hostDesc = {};
490 hostDesc.stype = ZE_STRUCTURE_TYPE_HOST_MEM_ALLOC_DESC;
491 L0_SAFE_CALL(zeMemAllocShared(getRtContext().context.get(), &deviceDesc,
492 &hostDesc, size, alignment,
493 getRtContext().device, &memPtr));
494 } else {
495 L0_SAFE_CALL(zeMemAllocDevice(getRtContext().context.get(), &deviceDesc,
496 size, alignment, getRtContext().device,
497 &memPtr));
498 }
499 if (!memPtr)
500 throw std::runtime_error("mem allocation failed!");
501 return memPtr;
502 });
503}
504
505extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
506mgpuMemFree(void *ptr, StreamWrapper *stream) {
507 stream->sync();
508 if (ptr)
509 L0_SAFE_CALL(zeMemFree(getRtContext().context.get(), ptr));
510}
511
512extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
513mgpuMemcpy(void *dst, void *src, size_t sizeBytes, StreamWrapper *stream) {
514 stream->enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
515 ze_event_handle_t *waitEvents) {
516 L0_SAFE_CALL(zeCommandListAppendMemoryCopy(
517 getRtContext().immCmdListCopy.get(), dst, src, sizeBytes, newEvent,
518 numWaitEvents, waitEvents));
519 });
520}
521
522template <typename PATTERN_TYPE>
523static void mgpuMemset(void *dst, PATTERN_TYPE value, size_t count,
524 StreamWrapper *stream) {
525 L0RTContextWrapper &rtContext = getRtContext();
526 auto listType =
527 rtContext.copyEngineMaxMemoryFillPatternSize >= sizeof(PATTERN_TYPE)
528 ? rtContext.immCmdListCopy.get()
529 : rtContext.immCmdListCompute.get();
530 stream->enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
531 ze_event_handle_t *waitEvents) {
532 L0_SAFE_CALL(zeCommandListAppendMemoryFill(
533 listType, dst, &value, sizeof(PATTERN_TYPE),
534 count * sizeof(PATTERN_TYPE), newEvent, numWaitEvents, waitEvents));
535 });
536}
537extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
538mgpuMemset32(void *dst, unsigned int value, size_t count,
539 StreamWrapper *stream) {
540 mgpuMemset<unsigned int>(dst, value, count, stream);
541}
542
543extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
544mgpuMemset16(void *dst, unsigned short value, size_t count,
545 StreamWrapper *stream) {
546 mgpuMemset<unsigned short>(dst, value, count, stream);
547}
548
549extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT ze_module_handle_t
550mgpuModuleLoad(const void *data, size_t gpuBlobSize) {
551 return catchAll([&]() { return loadModule(data, gpuBlobSize); });
552}
553
554extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT ze_module_handle_t
555mgpuModuleLoadJIT(void *data, int optLevel, size_t assemblySize) {
556 // Account for extra null terminator added in embedBinaryImpl.
557 // A null terminator is added during embedding binary for assembly format to
558 // support JIT paths that expect null-terminated strings. However, for SPIR-V
559 // binary format, the null terminator is not expected. So we need to subtract
560 // the null terminator when loading SPIR-V binary.
561 assert((assemblySize == 0 ||
562 reinterpret_cast<char *>(data)[assemblySize - 1] == 0) &&
563 "Expected null terminator at the end of the assembly string.");
564 size_t actualAssemblySize = assemblySize - 1;
565 assert(actualAssemblySize % 4 == 0 &&
566 "SPIR-V binary size must be a multiple of 4");
567 return catchAll([&]() {
568 return loadModule(data, actualAssemblySize, ZE_MODULE_FORMAT_IL_SPIRV);
569 });
570}
571
572extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT ze_kernel_handle_t
573mgpuModuleGetFunction(ze_module_handle_t module, const char *name) {
574 assert(module && name);
575 ze_kernel_handle_t zeKernel;
576 ze_kernel_desc_t desc = {};
577 desc.pKernelName = name;
578 L0_SAFE_CALL(zeKernelCreate(module, &desc, &zeKernel));
579 return zeKernel;
580}
581
582extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
583mgpuLaunchKernel(ze_kernel_handle_t kernel, size_t gridX, size_t gridY,
584 size_t gridZ, size_t blockX, size_t blockY, size_t blockZ,
585 int32_t sharedMemBytes, StreamWrapper *stream, void **params,
586 void ** /*extra*/, size_t paramsCount) {
587
588 if (sharedMemBytes > 0) {
589 paramsCount = paramsCount - 1; // Last param is shared memory size
591 zeKernelSetArgumentValue(kernel, paramsCount, sharedMemBytes, nullptr));
592 }
593 for (size_t i = 0; i < paramsCount; ++i)
594 L0_SAFE_CALL(zeKernelSetArgumentValue(kernel, static_cast<uint32_t>(i),
595 sizeof(void *), params[i]));
596 L0_SAFE_CALL(zeKernelSetGroupSize(kernel, blockX, blockY, blockZ));
597 ze_group_count_t dispatch;
598 dispatch.groupCountX = static_cast<uint32_t>(gridX);
599 dispatch.groupCountY = static_cast<uint32_t>(gridY);
600 dispatch.groupCountZ = static_cast<uint32_t>(gridZ);
601 stream->enqueueOp([&](ze_event_handle_t newEvent, uint32_t numWaitEvents,
602 ze_event_handle_t *waitEvents) {
603 L0_SAFE_CALL(zeCommandListAppendLaunchKernel(
604 getRtContext().immCmdListCompute.get(), kernel, &dispatch, newEvent,
605 numWaitEvents, waitEvents));
606 });
607}
608
609extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
610mgpuModuleUnload(ze_module_handle_t module) {
611 L0_SAFE_CALL(zeModuleDestroy(module));
612}
613
614extern "C" MLIR_LEVELZERO_WRAPPERS_EXPORT void
615mgpuSetDefaultDevice(int32_t devIdx) {
616 catchAll([&]() {
617 // For now, a user must ensure that streams and events complete
618 // and are destroyed before switching a device.
621 });
622}
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuStreamSynchronize(StreamWrapper *stream)
std::unique_ptr< std::remove_pointer< ze_event_handle_t >::type, ZeEventDeleter > UniqueZeEvent
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuEventDestroy(ze_event_handle_t event)
static L0RTContextWrapper & getRtContext()
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuEventSynchronize(ze_event_handle_t event)
static ze_module_handle_t loadModule(const void *data, size_t dataSize, ze_module_format_t format=ZE_MODULE_FORMAT_NATIVE)
MLIR_LEVELZERO_WRAPPERS_EXPORT void * mgpuMemAlloc(uint64_t size, StreamWrapper *stream, bool isShared)
static ze_result_t zeDriverGetLastErrorDescriptionWrapper(const char **errorString)
#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)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuStreamDestroy(StreamWrapper *stream)
MLIR_LEVELZERO_WRAPPERS_EXPORT StreamWrapper * mgpuStreamCreate()
static DynamicEventPool & getDynamicEventPool()
std::unique_ptr< std::remove_pointer< ze_context_handle_t >::type, ZeContextDeleter > UniqueZeContext
MLIR_LEVELZERO_WRAPPERS_EXPORT ze_module_handle_t mgpuModuleLoad(const void *data, size_t gpuBlobSize)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuMemFree(void *ptr, StreamWrapper *stream)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuModuleUnload(ze_module_handle_t module)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuMemset32(void *dst, unsigned int value, size_t count, StreamWrapper *stream)
MLIR_LEVELZERO_WRAPPERS_EXPORT ze_kernel_handle_t mgpuModuleGetFunction(ze_module_handle_t module, const char *name)
MLIR_LEVELZERO_WRAPPERS_EXPORT ze_module_handle_t mgpuModuleLoadJIT(void *data, int optLevel, size_t assemblySize)
MLIR_LEVELZERO_WRAPPERS_EXPORT 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, int32_t sharedMemBytes, StreamWrapper *stream, void **params, void **, size_t paramsCount)
static ze_driver_handle_t getDriver(uint32_t idx=0)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuMemcpy(void *dst, void *src, size_t sizeBytes, StreamWrapper *stream)
std::unique_ptr< std::remove_pointer< ze_command_list_handle_t >::type, ZeCommandListDeleter > UniqueZeCommandList
#define MLIR_LEVELZERO_WRAPPERS_EXPORT
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuEventRecord(ze_event_handle_t event, StreamWrapper *stream)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuMemset16(void *dst, unsigned short value, size_t count, StreamWrapper *stream)
MLIR_LEVELZERO_WRAPPERS_EXPORT ze_event_handle_t mgpuEventCreate()
std::unique_ptr< std::remove_pointer< ze_event_pool_handle_t >::type, ZeEventPoolDeleter > UniqueZeEventPool
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuStreamWaitEvent(StreamWrapper *stream, ze_event_handle_t event)
MLIR_LEVELZERO_WRAPPERS_EXPORT void mgpuSetDefaultDevice(int32_t devIdx)
b getContext())
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
UniqueZeCommandList immCmdListCopy
L0RTContextWrapper()=default
L0RTContextWrapper & operator=(const L0RTContextWrapper &)=delete
L0RTContextWrapper(L0RTContextWrapper &&) noexcept=default
L0RTContextWrapper(const uint32_t driverIdx=0, const int32_t devIdx=0)
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 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