Skip to content

Avoid potential deadlocks in host allocator #159352

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

Open
wants to merge 4 commits into
base: gh/guangyey/174/base
Choose a base branch
from
Open
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
14 changes: 10 additions & 4 deletions aten/src/ATen/core/CachingHostAllocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ struct CachingHostAllocatorImpl {
auto* block = reinterpret_cast<B*>(ctx);

std::optional<std::vector<E>> events;
ska::flat_hash_set<S> streams;
{
std::lock_guard<std::mutex> g(block->mutex_);
block->allocated_ = false;
Expand All @@ -259,14 +260,19 @@ struct CachingHostAllocatorImpl {
} else {
events = std::vector<E>();
events->reserve(block->streams_.size());
for (auto stream : block->streams_) {
record_stream(events, stream);
}
block->event_count_ += events->size();
block->event_count_ += block->streams_.size();
// Move out streams to avoid holding the mutex during event recording
streams = std::move(block->streams_);
block->streams_.clear();
Copy link
Collaborator

Choose a reason for hiding this comment

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

Moved streams are used at the next line.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This actually fine per the spec, std::move moves puts it an unspecified, but valid state. Clear() should be safe to call.

}
}

// Event recording must be done outside the mutex to avoid potential
// deadlocks (e.g., when Python GIL is involved)
for (auto stream : streams) {
record_stream(events, stream);
}

if (!events) {
auto index = size_index(block->size_);
std::lock_guard<std::mutex> g(free_list_[index].mutex_);
Expand Down
Loading