Skip to content
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
8 changes: 7 additions & 1 deletion mlx/backend/metal/fence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include "mlx/scheduler.h"
#include "mlx/utils.h"

#include <arm_acle.h>

namespace mlx::core {

struct FenceImpl {
Expand Down Expand Up @@ -111,7 +113,11 @@ void Fence::update(Stream stream, const array& x, bool cross_device) {
return;
}

f.cpu_value()[0] = count;
// seq_cst compiles to DMB ISH (inner-shareable) on ARM64,
// which is not visible to the GPU. Use DSB SY (full system)
// to force the store to the point of coherence.
f.cpu_value()->store(count, std::memory_order_seq_cst);
__dsb(0xF);
});
return;
}
Expand Down
23 changes: 17 additions & 6 deletions mlx/backend/metal/kernels/fence.metal
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,23 @@ constexpr constant metal::thread_scope thread_scope_system =
volatile coherent(system) device uint* timestamp [[buffer(0)]],
constant uint& value [[buffer(1)]]) {
while (1) {
metal::atomic_thread_fence(
metal::mem_flags::mem_device,
metal::memory_order_seq_cst,
metal::thread_scope_system);
if (timestamp[0] >= value) {
break;
// Fast path: volatile reads through GPU cache + system-scope fence
for (uint i = 0; i < 1000000; i++) {
metal::atomic_thread_fence(
metal::mem_flags::mem_device,
metal::memory_order_seq_cst,
metal::thread_scope_system);
if (timestamp[0] >= value) {
return;
}
}
// System-scope atomic load to force GPU cache refresh from SLC
uint cur = __metal_atomic_load_explicit(
timestamp,
int(metal::memory_order_relaxed),
__METAL_MEMORY_SCOPE_SYSTEM__);
if (cur >= value) {
return;
}
}
}