Skip to content
Merged
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
12 changes: 11 additions & 1 deletion mlx/backend/metal/device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ void CommandEncoder::barrier() {
get_command_encoder()->memoryBarrier(MTL::BarrierScopeBuffers);
}

void CommandEncoder::end_encoding() {
void CommandEncoder::end_encoding(bool wait_in_flight) {
// Each command encoder has a unique fence. We also store a map of
// all previous outputs of command encoders to their corresponding fence.
// - The command encoder records its inputs and outputs.
Expand Down Expand Up @@ -478,6 +478,16 @@ void CommandEncoder::end_encoding() {
}
}
}
// A spin wait must start after all earlier encoders, as it might block
// earlier operations to be finished.
// See https://github.com/ml-explore/mlx/pull/4689
if (wait_in_flight) {
for (auto& [_, fence] : prev_ce_outputs_) {
if (waiting_on.insert(fence).second) {
encoder_->waitForFence(fence.get());
}
}
}
for (auto& out : all_outputs_) {
prev_ce_outputs_[out] = fence_;
}
Expand Down
2 changes: 1 addition & 1 deletion mlx/backend/metal/device.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class MLX_API CommandEncoder {
}

void barrier();
void end_encoding();
void end_encoding(bool wait_in_flight = false);
void wait_event(Event event, uint64_t value);
void signal_event(Event event, uint64_t value);
bool needs_commit() const;
Expand Down
3 changes: 3 additions & 0 deletions mlx/backend/metal/fence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ void Fence::wait(Stream stream, const array& x, uint32_t value) {
auto& d = metal::device(stream.device);
auto& compute_encoder = metal::get_command_encoder(stream);

compute_encoder.end_encoding();

// Register outputs to ensure that no kernels which depends on the
// output starts before this one is done
compute_encoder.register_output_array(x);
Expand All @@ -77,6 +79,7 @@ void Fence::wait(Stream stream, const array& x, uint32_t value) {
compute_encoder.set_buffer(f.buffer(), 0);
compute_encoder.set_bytes(value, 1);
compute_encoder.dispatch_threads(kernel_dims, kernel_dims);
compute_encoder.end_encoding(true);

compute_encoder.get_command_buffer()->addCompletedHandler(
[fence_ = fence_](MTL::CommandBuffer* cbuf) {});
Expand Down
Loading