diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 3584f4c22e..52fe2f44dd 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -87,6 +87,16 @@ handled by the CUDA runtime. Metal ----- +.. envvar:: MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS + + Re-request residency for existing wired allocations at this interval in + milliseconds. This works around macOS releasing residency while the GPU is + idle. The default is ``0`` (disabled); nonpositive values disable renewal. + For example, ``1000`` renews once per second. This does not change the wired + limit set by :func:`mlx.core.set_wired_limit` or submit GPU work. Renewal + continues while the Metal device exists and can keep memory wired during + long idle periods. Requires a Metal 3 GPU on macOS 15 or iOS 18 or later. + .. envvar:: MLX_METAL_FAST_SYNCH Enable the faster Metal CPU/GPU synchronization path. The default is ``0``. diff --git a/mlx/backend/metal/resident.cpp b/mlx/backend/metal/resident.cpp index 2b8357de2a..26ab718e31 100644 --- a/mlx/backend/metal/resident.cpp +++ b/mlx/backend/metal/resident.cpp @@ -1,7 +1,8 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #include #include +#include #include #include #include @@ -43,10 +44,38 @@ ResidencySets::ResidencySets(MTL::Device* d) { } throw std::runtime_error(msg.str()); } + if (int interval = + env::get_var("MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS", 0); + interval > 0) { + refresh_thread_ = std::thread([this, interval] { + std::unique_lock lock(mtx_); + while (!refresh_cv_.wait_for( + lock, std::chrono::milliseconds(interval), [this] { + return stop_refresh_; + })) { + auto pool = new_scoped_memory_pool(); + // macOS can drop residency after GPU idle despite a standing request. + for (auto& s : sets_) { + if (s.size != 0) { + s.set->requestResidency(); + } + } + } + }); + } } } -ResidencySets::~ResidencySets() = default; +ResidencySets::~ResidencySets() { + if (refresh_thread_.joinable()) { + { + std::lock_guard lock(mtx_); + stop_refresh_ = true; + } + refresh_cv_.notify_one(); + refresh_thread_.join(); + } +} bool ResidencySets::add_set_locked(std::string* error_out) { NS::SharedPtr set; diff --git a/mlx/backend/metal/resident.h b/mlx/backend/metal/resident.h index 141f0f3a32..3339307b6c 100644 --- a/mlx/backend/metal/resident.h +++ b/mlx/backend/metal/resident.h @@ -1,11 +1,13 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #pragma once #include +#include #include #include #include +#include #include #include @@ -119,6 +121,9 @@ class ResidencySets { // taking the lock. std::atomic num_sets_{0}; mutable std::mutex mtx_; + std::condition_variable refresh_cv_; + bool stop_refresh_{false}; + std::thread refresh_thread_; }; } // namespace mlx::core::metal