Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
38 changes: 38 additions & 0 deletions mlx/backend/metal/device.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright © 2023-2024 Apple Inc.

#include <atomic>
#include <cstdlib>
#include <sstream>

Expand All @@ -14,6 +15,7 @@
#include "mlx/backend/metal/event.h"
#include "mlx/backend/metal/metal.h"
#include "mlx/backend/metal/utils.h"
#include "mlx/scheduler.h"
#include "mlx/utils.h"

namespace std {
Expand All @@ -32,6 +34,13 @@ namespace mlx::core::metal {

namespace {

// Work counters behind counters()/reset() (metal.h). Relaxed: they are
// statistics read while no eval is in flight, never used for synchronization.
std::atomic<uint64_t> dispatch_count{0};
std::atomic<uint64_t> commit_count{0};
std::atomic<uint64_t> sync_count{0};
std::atomic<uint64_t> wait_count{0};

constexpr const char* default_mtllib_path = METAL_PATH;

void set_compile_options(
Expand Down Expand Up @@ -418,6 +427,7 @@ void CommandEncoder::dispatch_threadgroups(
MTL::Size group_dims) {
maybeInsertBarrier();
buffer_ops_++;
dispatch_count.fetch_add(1, std::memory_order_relaxed);
get_command_encoder()->dispatchThreadgroups(grid_dims, group_dims);
}

Expand All @@ -426,6 +436,7 @@ void CommandEncoder::dispatch_threads(
MTL::Size group_dims) {
maybeInsertBarrier();
buffer_ops_++;
dispatch_count.fetch_add(1, std::memory_order_relaxed);
get_command_encoder()->dispatchThreads(grid_dims, group_dims);
}

Expand Down Expand Up @@ -564,6 +575,7 @@ void CommandEncoder::commit(std::function<void()> completion) {
}
});
buffer_->commit();
commit_count.fetch_add(1, std::memory_order_relaxed);
buffer_ = NS::RetainPtr(queue_->commandBufferWithUnretainedReferences());
buffer_ops_ = 0;
buffer_sizes_ = 0;
Expand All @@ -574,6 +586,11 @@ void CommandEncoder::synchronize() {
auto cbuf = buffer_; // retained
end_encoding();
commit();
// Encoder teardown (clear_streams(), thread exit) is not an explicit sync.
if (!exiting_) {
sync_count.fetch_add(1, std::memory_order_relaxed);
count_host_wait();
Comment thread
jeethu marked this conversation as resolved.
Resolved
}
cbuf->waitUntilCompleted();

if (!exiting_) {
Expand Down Expand Up @@ -980,4 +997,25 @@ bool is_nax_available() {
#endif
}

void count_host_wait() {
wait_count.fetch_add(1, std::memory_order_relaxed);
}

Counters counters() {
return {
dispatch_count.load(std::memory_order_relaxed),
commit_count.load(std::memory_order_relaxed),
sync_count.load(std::memory_order_relaxed),
wait_count.load(std::memory_order_relaxed) +
scheduler::scheduler().gpu_waits()};
}

void reset() {
dispatch_count.store(0, std::memory_order_relaxed);
commit_count.store(0, std::memory_order_relaxed);
sync_count.store(0, std::memory_order_relaxed);
wait_count.store(0, std::memory_order_relaxed);
scheduler::scheduler().reset_gpu_waits();
}

} // namespace mlx::core::metal
4 changes: 4 additions & 0 deletions mlx/backend/metal/device.h
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,8 @@ NS::SharedPtr<NS::AutoreleasePool> new_scoped_memory_pool();

bool is_nax_available();

// Bumps the `waits` counter of counters() (metal.h). Called immediately
// before every host-side blocking wait on GPU completion.
void count_host_wait();

} // namespace mlx::core::metal
15 changes: 12 additions & 3 deletions mlx/backend/metal/event.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,24 @@ Event::Event(Stream stream) : stream_(stream) {

void Event::wait() {
check_error();
if (stream_.device == Device::gpu) {
metal::count_host_wait();
}
cast<metal::EventImpl>().wait(value());
check_error();
}

void Event::wait(Stream stream) {
if (stream.device == Device::cpu) {
scheduler::wait_event(stream, *this, [value = value()](Event& self) {
self.cast<metal::EventImpl>().wait(value);
});
scheduler::wait_event(
stream,
*this,
[value = value(), gpu = stream_.device == Device::gpu](Event& self) {
if (gpu) {
metal::count_host_wait();
}
self.cast<metal::EventImpl>().wait(value);
});
} else {
auto& encoder = metal::get_command_encoder(stream);
encoder.wait_event(*this, value());
Expand Down
7 changes: 6 additions & 1 deletion mlx/backend/metal/fence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace mlx::core {

struct FenceImpl {
FenceImpl(Stream stream) {
FenceImpl(Stream stream) : device(stream.device) {
auto d = metal::device(stream.device).mtl_device();
if (!d->supportsFamily(MTL::GPUFamilyMetal3)) {
use_fast = false;
Expand All @@ -29,6 +29,8 @@ struct FenceImpl {
allocator::free(allocator::Buffer{static_cast<MTL::Buffer*>(fence)});
}
}
// Device of the stream that updates (signals) the fence.
Device device;
bool use_fast{false};
uint32_t count{0};
void* fence;
Expand All @@ -55,6 +57,9 @@ void Fence::wait(Stream stream, const array& x) {
if (stream.device == Device::cpu) {
scheduler::enqueue(stream, [fence_ = fence_, count = f.count]() mutable {
auto& f = *static_cast<FenceImpl*>(fence_.get());
if (f.device == Device::gpu) {
metal::count_host_wait();
}
while (f.cpu_value()[0] < count) {
}
});
Expand Down
38 changes: 38 additions & 0 deletions mlx/backend/metal/metal.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#pragma once

#include <cstdint>
#include <string>
#include <unordered_map>
#include <variant>
Expand All @@ -27,4 +28,41 @@ MLX_API const
MLX_API void set_metallib_path(const std::string& path);
MLX_API const std::string& get_metallib_path();

/** Process-wide Metal work counters, summed over every stream.
*
* - `dispatches`: compute kernel dispatches (dispatchThreadgroups /
* dispatchThreads).
* - `commits`: command-buffer commits, including the automatic splits made
Comment thread
jeethu marked this conversation as resolved.
Resolved
* when a buffer exceeds MLX_MAX_OPS_PER_BUFFER / MLX_MAX_MB_PER_BUFFER.
* A commit is not a host wait.
* - `syncs`: explicit stream synchronizations (CommandEncoder::synchronize(),
* i.e. mx::synchronize()). Encoder teardown (clear_streams(), thread exit)
* is not counted.
* - `waits`: host blocking waits on GPU completion. Counted once per wait
* *call*, whether or not the GPU had already finished, never as blocking
* time: Metal shared-event waits on a GPU-signaled event
* (EventImpl::wait: an eval()/item() on an array still in flight, or a CPU
* stream waiting on a GPU event), the waitUntilCompleted inside
* synchronize() (so every sync is also a wait), the CPU-stream spin on a
* GPU-updated fast fence, and eval() throttling (scheduler::wait_for_one())
* that blocks while GPU command buffers are in flight. Waits on CPU-signaled
* events and fences are not counted. Note array::wait() skips the event
* wait when the event is already signaled, so an eval() whose GPU work
* finished before the host checked records no wait.
*
* Every field is built from independent relaxed atomics with no
* happens-before relation to the GPU or to other threads encoding work.
* counters() is a set of independent loads and reset() a set of independent
* stores, so both are only meaningful while no eval is in flight on any
* thread: call them after the measured eval has completed and before the next
* one starts. */
struct Counters {
uint64_t dispatches;
uint64_t commits;
uint64_t syncs;
uint64_t waits;
};
MLX_API Counters counters();
MLX_API void reset();

} // namespace mlx::core::metal
5 changes: 5 additions & 0 deletions mlx/backend/metal/no_metal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ const std::string& get_metallib_path() {
"[metal::get_metallib_path] Cannot get metallib path without metal backend");
}

Counters counters() {
return {0, 0, 0, 0};
}
void reset() {}

} // namespace metal

} // namespace mlx::core
20 changes: 20 additions & 0 deletions mlx/scheduler.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ class MLX_API Scheduler {
{
std::lock_guard<std::mutex> lk(mtx);
n_active_tasks_++;
if (stream.device == Device::gpu) {
n_active_gpu_tasks_++;
}
}
completion_cv.notify_all();
}
Expand All @@ -45,6 +48,9 @@ class MLX_API Scheduler {
{
std::lock_guard<std::mutex> lk(mtx);
n_active_tasks_--;
if (stream.device == Device::gpu) {
n_active_gpu_tasks_--;
}
}
completion_cv.notify_all();
}
Expand All @@ -57,18 +63,32 @@ class MLX_API Scheduler {
std::unique_lock<std::mutex> lk(mtx);
int n_tasks_old = n_active_tasks();
if (n_tasks_old > 1) {
if (n_active_gpu_tasks_ > 0) {
gpu_waits_.fetch_add(1, std::memory_order_relaxed);
Comment thread
jeethu marked this conversation as resolved.
Resolved
}
completion_cv.wait(lk, [this, n_tasks_old] {
return this->n_active_tasks() < n_tasks_old;
});
}
}

// Blocking wait_for_one() calls made while GPU tasks were in flight.
uint64_t gpu_waits() const {
return gpu_waits_.load(std::memory_order_relaxed);
}

void reset_gpu_waits() {
gpu_waits_.store(0, std::memory_order_relaxed);
}

private:
friend Stream mlx::core::new_stream(Device d);

StreamThread& get_thread(Stream s);

int n_active_tasks_{0};
int n_active_gpu_tasks_{0};
std::atomic<uint64_t> gpu_waits_{0};
std::unordered_map<int, std::unique_ptr<StreamThread>> threads_;
std::shared_mutex threads_mtx_;
std::condition_variable completion_cv;
Expand Down
2 changes: 1 addition & 1 deletion tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ if(MLX_BUILD_METAL OR MLX_BUILD_CUDA)
endif()

if(MLX_BUILD_METAL)
list(APPEND METAL_TEST_SOURCES residency_tests.cpp)
list(APPEND METAL_TEST_SOURCES residency_tests.cpp metal_counters_tests.cpp)
endif()

include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake)
Expand Down
87 changes: 87 additions & 0 deletions tests/metal_counters_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright © 2026 Apple Inc.

#include <thread>

#include "doctest/doctest.h"

#include "mlx/backend/metal/metal.h"
#include "mlx/mlx.h"

using namespace mlx::core;

TEST_CASE("test metal counters count dispatches, commits, syncs and waits") {
// Use the GPU explicitly: DEVICE=cpu makes the CPU the default device.
Device gpu = Device::gpu;
auto a = random::normal({64, 64}, float32, 0.0, 1.0, std::nullopt, gpu);
auto b = random::normal({64, 64}, float32, 0.0, 1.0, std::nullopt, gpu);
eval(a, b);

metal::reset();
auto z = metal::counters();
CHECK_EQ(z.dispatches, 0);
CHECK_EQ(z.commits, 0);
CHECK_EQ(z.syncs, 0);
CHECK_EQ(z.waits, 0);

auto c = matmul(a, b, gpu);
eval(c);
auto after_eval = metal::counters();
CHECK_GE(after_eval.dispatches, 1);
CHECK_GE(after_eval.commits, 1);
CHECK_EQ(after_eval.syncs, 0);
// eval() blocks on c's completion event unless the GPU already signaled it
// before the host checked, so at most one wait.
CHECK_LE(after_eval.waits, 1);

// Re-evaluating (or reading) an evaluated array does not wait again.
eval(c);
CHECK_EQ(metal::counters().waits, after_eval.waits);

synchronize(default_stream(gpu));
auto after_sync = metal::counters();
CHECK_EQ(after_sync.syncs, 1);
CHECK_EQ(after_sync.waits, after_eval.waits + 1);
CHECK_GE(after_sync.commits, after_eval.commits + 1);
CHECK_EQ(after_sync.dispatches, after_eval.dispatches);

metal::reset();
auto r = metal::counters();
CHECK_EQ(r.dispatches, 0);
CHECK_EQ(r.commits, 0);
CHECK_EQ(r.syncs, 0);
CHECK_EQ(r.waits, 0);
}

TEST_CASE("test metal counters skip CPU-only work") {
Device cpu = Device::cpu;
auto a = random::normal({64, 64}, float32, 0.0, 1.0, std::nullopt, cpu);
auto b = random::normal({64, 64}, float32, 0.0, 1.0, std::nullopt, cpu);
eval(a, b);

metal::reset();
auto c = matmul(a, b, cpu);
eval(c);
synchronize(default_stream(cpu));
auto r = metal::counters();
CHECK_EQ(r.dispatches, 0);
CHECK_EQ(r.commits, 0);
CHECK_EQ(r.syncs, 0);
CHECK_EQ(r.waits, 0);
}

TEST_CASE("test metal counters skip encoder teardown") {
// A new thread gets its own GPU stream, so clear_streams() there does not
// touch the streams of the main thread.
std::thread t([]() {
Device gpu = Device::gpu;
auto a = random::normal({64, 64}, float32, 0.0, 1.0, std::nullopt, gpu);
eval(a);
metal::reset();
clear_streams();
});
t.join();

auto r = metal::counters();
CHECK_EQ(r.syncs, 0);
CHECK_EQ(r.waits, 0);
}
Loading