Skip to content

[SYCL][L0] Implement reuse of l0 events in plugin #5947

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 134 additions & 24 deletions sycl/plugins/level_zero/pi_level_zero.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,41 @@ pi_result _pi_context::decrementUnreleasedEventsInPool(pi_event Event) {
return PI_SUCCESS;
}

ze_event_handle_t _pi_context::getZeEventFromCache() {
std::lock_guard<std::mutex> Lock(ZeEventsCacheMutex);
if (ZeEventsCache.empty())
return nullptr;

auto It = ZeEventsCache.begin();
ze_event_handle_t ZeEvent = *It;
ZeEventsCache.erase(It);

++ZeEventUseCount[ZeEvent];
return ZeEvent;
}

void _pi_context::addZeEventToCache(ze_event_handle_t ZeEvent,
bool CamefromEventRelease) {
std::lock_guard<std::mutex> Lock(ZeEventsCacheMutex);

if (CamefromEventRelease) {
auto It = ZeEventUseCount.find(ZeEvent);
if (It == ZeEventUseCount.end()) {
ZeEventUseCount[ZeEvent] = 0;
} else {
if (--(ZeEventUseCount[ZeEvent]) != 0) {
return;
}
}
} else {
auto It = ZeEventUseCount.find(ZeEvent);
if (It == ZeEventUseCount.end()) {
ZeEventUseCount[ZeEvent] = 1;
}
}
ZeEventsCache.emplace(ZeEvent);
}

// Some opencl extensions we know are supported by all Level Zero devices.
constexpr char ZE_SUPPORTED_EXTENSIONS[] =
"cl_khr_il_program cl_khr_subgroups cl_intel_subgroups "
Expand Down Expand Up @@ -789,6 +824,13 @@ pi_result _pi_context::finalize() {
// This function is called when pi_context is deallocated, piContextRelease.
// There could be some memory that may have not been deallocated.
// For example, event pool caches would be still alive.
{
std::lock_guard<std::mutex> Lock(ZeEventsCacheMutex);
for (auto &ZeEvent : ZeEventsCache) {
ZE_CALL(zeEventDestroy, (ZeEvent));
}
}

{
std::lock_guard<std::mutex> Lock(ZeEventPoolCacheMutex);
for (auto &ZePoolCache : ZeEventPoolCache) {
Expand Down Expand Up @@ -1262,6 +1304,23 @@ void _pi_queue::adjustBatchSizeForPartialBatch(bool IsCopy) {
}
}

pi_result _pi_queue::resetLastEventIfNeeded(pi_command_list_ptr_t CommandList) {
if (!this->LastCommandEvent)
return PI_SUCCESS;

auto &ZeEvent = this->LastCommandEvent->ZeEvent;
if (ZeEvent == CommandList->second.EventList.back()->ZeEvent)
die("Current command event and last command event must be different");

if (isInOrderQueue() && !this->LastCommandEvent->isHostVisible() &&
!this->LastCommandEvent->isProfilingEnabled()) {
ZE_CALL(zeCommandListAppendWaitOnEvents, (CommandList->first, 1, &ZeEvent));
ZE_CALL(zeCommandListAppendEventReset, (CommandList->first, ZeEvent));
this->LastCommandEvent->Context->addZeEventToCache(ZeEvent);
}
return PI_SUCCESS;
}

pi_result _pi_queue::executeCommandList(pi_command_list_ptr_t CommandList,
bool IsBlocking,
bool OKToBatchCommand) {
Expand Down Expand Up @@ -4900,6 +4959,8 @@ piEnqueueKernelLaunch(pi_queue Queue, pi_kernel Kernel, pi_uint32 WorkDim,
if (IndirectAccessTrackingEnabled)
Queue->KernelsToBeSubmitted.push_back(Kernel);

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;
Comment on lines +4962 to +4963
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is reset of the unused events can't happen in the executeCommandList?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We probably can, but then we should add a new parameter to executeCommandList to separate the cases when resetLastEventIfNeeded is executed and when it is not.
For example, one of the problematic cases: we should not reset the L0 event when closing the command-list if we take this event later as a dependency (this situation occurs when the event is from another queue, this happens inside createAndRetainPiZeEventList for LastCommandEvent which should be used as a dependency.)

I'm trying to say that the general rule is to reset the L0 event immediately after queue operations such as zeCommandListAppendLaunchKernel, zeCommandListAppendMemoryCopy etc. (or after zeCommandListAppendWaitOnEvents if the queue operation used it, see next paragraph about it).

On the other hand, in the future we may do some optimization: currently for cases when we already had zeCommandListAppendWaitOnEvents, we could skip it in resetLastEventIfNeeded and for this we can add one parameter to resetLastEventIfNeeded function, but if we transfer it to executeCommandList, then for such optimization you have to add two parameters to executeCommandList function. That is, we can do as you suggest, but the only question is whether it is necessary?

// Execute command list asynchronously, as the event will be used
// to track down its completion.
if (auto Res = Queue->executeCommandList(CommandList, false, true))
Expand Down Expand Up @@ -4985,6 +5046,9 @@ _pi_event::getOrCreateHostVisibleEvent(ze_event_handle_t &ZeHostVisibleEvent) {
ZE_CALL(zeCommandListAppendSignalEvent,
(CommandList->first, HostVisibleEvent->ZeEvent));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res = Queue->executeCommandList(CommandList, false, OkToBatch))
return Res;
}
Expand All @@ -5005,38 +5069,49 @@ static pi_result EventCreate(pi_context Context, pi_queue Queue,
bool ProfilingEnabled =
!Queue || (Queue->Properties & PI_QUEUE_PROFILING_ENABLE) != 0;

size_t Index = 0;
ze_event_pool_handle_t ZeEventPool = {};
if (auto Res = Context->getFreeSlotInExistingOrNewPool(
ZeEventPool, Index, HostVisible, ProfilingEnabled))
return Res;

ze_event_handle_t ZeEvent;
ZeStruct<ze_event_desc_t> ZeEventDesc;
ZeEventDesc.index = Index;
ZeEventDesc.wait = 0;
ze_event_handle_t ZeEvent = nullptr;
ze_event_pool_handle_t ZeEventPool = nullptr;

if (HostVisible) {
ZeEventDesc.signal = ZE_EVENT_SCOPE_FLAG_HOST;
} else {
//
// Set the scope to "device" for every event. This is sufficient for global
// device access and peer device access. If needed to be seen on the host
// we are doing special handling, see EventsScope options.
//
// TODO: see if "sub-device" (ZE_EVENT_SCOPE_FLAG_SUBDEVICE) can better be
// used in some circumstances.
//
ZeEventDesc.signal = 0;
bool OwnZeEvent = HostVisible || ProfilingEnabled || !Queue->isInOrderQueue();
if (!OwnZeEvent) {
ZeEvent = Context->getZeEventFromCache();
}

ZE_CALL(zeEventCreate, (ZeEventPool, &ZeEventDesc, &ZeEvent));
if (!ZeEvent) {
size_t Index = 0;
if (auto Res = Context->getFreeSlotInExistingOrNewPool(
ZeEventPool, Index, HostVisible, ProfilingEnabled))
return Res;

ZeStruct<ze_event_desc_t> ZeEventDesc;
ZeEventDesc.index = Index;
ZeEventDesc.wait = 0;

if (HostVisible) {
ZeEventDesc.signal = ZE_EVENT_SCOPE_FLAG_HOST;
} else {
//
// Set the scope to "device" for every event. This is sufficient for
// global device access and peer device access. If needed to be seen on
// the host we are doing special handling, see EventsScope options.
//
// TODO: see if "sub-device" (ZE_EVENT_SCOPE_FLAG_SUBDEVICE) can better be
// used in some circumstances.
//
ZeEventDesc.signal = 0;
}

ZE_CALL(zeEventCreate, (ZeEventPool, &ZeEventDesc, &ZeEvent));

if (!OwnZeEvent)
ZeEventPool = nullptr;
}

try {
PI_ASSERT(RetEvent, PI_INVALID_VALUE);

*RetEvent = new _pi_event(ZeEvent, ZeEventPool, Context,
PI_COMMAND_TYPE_USER, true);
PI_COMMAND_TYPE_USER, OwnZeEvent);
} catch (const std::bad_alloc &) {
return PI_OUT_OF_HOST_MEMORY;
} catch (...) {
Expand Down Expand Up @@ -5388,6 +5463,11 @@ static pi_result EventRelease(pi_event Event, pi_queue LockedQueue) {
}
if (Event->OwnZeEvent) {
ZE_CALL(zeEventDestroy, (Event->ZeEvent));
} else {
if (Event->Queue->isInOrderQueue() && !Event->isHostVisible() &&
!Event->isProfilingEnabled()) {
Event->Context->addZeEventToCache(Event->ZeEvent, true);
}
}
// It is possible that host-visible event was never created.
// In case it was check if that's different from this same event
Expand Down Expand Up @@ -5653,6 +5733,9 @@ pi_result piEnqueueEventsWait(pi_queue Queue, pi_uint32 NumEventsInWaitList,

ZE_CALL(zeCommandListAppendSignalEvent, (ZeCommandList, ZeEvent));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

// Execute command list asynchronously as the event will be used
// to track down its completion.
return Queue->executeCommandList(CommandList);
Expand Down Expand Up @@ -5721,6 +5804,9 @@ pi_result piEnqueueEventsWaitWithBarrier(pi_queue Queue,
(CommandList->first, ZeEvent, (*Event)->WaitList.Length,
(*Event)->WaitList.ZeEventList));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

// Execute command list asynchronously as the event will be used
// to track down its completion.
return Queue->executeCommandList(CommandList, false, OkToBatch);
Expand Down Expand Up @@ -5823,6 +5909,9 @@ static pi_result enqueueMemCopyHelper(pi_command_type CommandType,
pi_cast<std::uintptr_t>(ZeEvent));
printZeEventList(WaitList);

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res =
Queue->executeCommandList(CommandList, BlockingWrite, OkToBatch))
return Res;
Expand Down Expand Up @@ -5921,6 +6010,9 @@ static pi_result enqueueMemCopyRectHelper(
zePrint("calling zeCommandListAppendBarrier() with Event %#lx\n",
pi_cast<std::uintptr_t>(ZeEvent));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res = Queue->executeCommandList(CommandList, Blocking, OkToBatch))
return Res;

Expand Down Expand Up @@ -6101,6 +6193,9 @@ enqueueMemFillHelper(pi_command_type CommandType, pi_queue Queue, void *Ptr,
pi_cast<pi_uint64>(ZeEvent));
printZeEventList(WaitList);

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

// Execute command list asynchronously, as the event will be used
// to track down its completion.
if (auto Res = Queue->executeCommandList(CommandList, false, OkToBatch))
Expand Down Expand Up @@ -6256,6 +6351,9 @@ pi_result piEnqueueMemBufferMap(pi_queue Queue, pi_mem Buffer,
pi_cast<char *>(Buffer->getZeHandle()) + Offset, Size, ZeEvent, 0,
nullptr));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res = Queue->executeCommandList(CommandList, BlockingMap))
return Res;

Expand Down Expand Up @@ -6382,6 +6480,9 @@ pi_result piEnqueueMemUnmap(pi_queue Queue, pi_mem MemObj, void *MappedPtr,
pi_cast<char *>(MemObj->getZeHandle()) + MapInfo.Offset, MappedPtr,
MapInfo.Size, ZeEvent, 0, nullptr));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

// Execute command list asynchronously, as the event will be used
// to track down its completion.
if (auto Res = Queue->executeCommandList(CommandList))
Expand Down Expand Up @@ -6579,6 +6680,9 @@ static pi_result enqueueMemImageCommandHelper(
return PI_INVALID_OPERATION;
}

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res = Queue->executeCommandList(CommandList, IsBlocking, OkToBatch))
return Res;

Expand Down Expand Up @@ -7467,6 +7571,9 @@ pi_result piextUSMEnqueuePrefetch(pi_queue Queue, const void *Ptr, size_t Size,
// so manually add command to signal our event.
ZE_CALL(zeCommandListAppendSignalEvent, (ZeCommandList, ZeEvent));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

if (auto Res = Queue->executeCommandList(CommandList, false))
return Res;

Expand Down Expand Up @@ -7529,6 +7636,9 @@ pi_result piextUSMEnqueueMemAdvise(pi_queue Queue, const void *Ptr,
// so manually add command to signal our event.
ZE_CALL(zeCommandListAppendSignalEvent, (ZeCommandList, ZeEvent));

if (auto Res = Queue->resetLastEventIfNeeded(CommandList))
return Res;

Queue->executeCommandList(CommandList, false);
return PI_SUCCESS;
}
Expand Down
20 changes: 20 additions & 0 deletions sycl/plugins/level_zero/pi_level_zero.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,13 @@ struct _pi_context : _pi_object {
// and return the pool to the cache if there are no unreleased events.
pi_result decrementUnreleasedEventsInPool(pi_event Event);

// Return event if cache has an event available, nullptr otherwise.
ze_event_handle_t getZeEventFromCache();

// Put the event in the cache for reuse.
void addZeEventToCache(ze_event_handle_t ZeEvent,
bool CamefromEventRelease = false);

// Store USM allocator context(internal allocator structures)
// for USM shared and device allocations. There is 1 allocator context
// per each pair of (context, device) per each memory type.
Expand Down Expand Up @@ -718,6 +725,15 @@ struct _pi_context : _pi_object {
// Mutex to control operations on event pool caches and the helper maps
// holding the current pool usage counts.
std::mutex ZeEventPoolCacheMutex;

// This counts how many PI events used a particular L0 event. If the counter
// becomes zero when we release the PI event, this means it was the last user
// of the L0 event and we can safely put it back in the cache.
std::unordered_map<ze_event_handle_t, size_t> ZeEventUseCount;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why you need any new counts for this. It should be at the time we currently call zeEventDestroy that the event is known to be no longer needed and returned to the cache.

Also how do you ensure that the pool containing the event is not destroyed to early but is destroyed when all events in it are destroyed? (since you are adding a new structure to cache unused events it needs to sync with the exisitng pool structure). And I think they can use the same mutex.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why you need any new counts for this. It should be at the time we currently call zeEventDestroy that the event is known to be no longer needed and returned to the cache.

Since we reuse L0 event multiple times in different PI events, there is a case when we release the PI event but we should not really add the L0 event to cache and we can safely add L0 event into cache only after last PI event is released.
So we need to know that current PI event is last which used the L0 event, for that I added new counter here.

Also how do you ensure that the pool containing the event is not destroyed to early but is destroyed when all events in it are destroyed? (since you are adding a new structure to cache unused events it needs to sync with the exisitng pool structure). And I think they can use the same mutex.

L0 events from the cache will be removed inside _pi_context::finalize right before the pool is destroyed.
Is that enough to guarantee what you say? should we still have the same mutex per pool and per cache as you suggested before?

// Cache of allocated events that are in non-signaled state and can be reused.
std::unordered_set<ze_event_handle_t> ZeEventsCache;
// Mutex to control operations on L0 event cache and event usage counts.
std::mutex ZeEventsCacheMutex;
};

struct _pi_queue : _pi_object {
Expand Down Expand Up @@ -869,6 +885,10 @@ struct _pi_queue : _pi_object {
auto CommandBatch = (IsCopy) ? CopyCommandBatch : ComputeCommandBatch;
return CommandBatch.OpenCommandList != CommandListMap.end();
}

// Reset LastCommandEvent->ZeEvent if necessary and put it in cache for reuse.
pi_result resetLastEventIfNeeded(pi_command_list_ptr_t CommandList);

// Attach a command list to this queue, close, and execute it.
// Note that this command list cannot be appended to after this.
// The "IsBlocking" tells if the wait for completion is required.
Expand Down