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
1 change: 1 addition & 0 deletions docs/src/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ are the CPU and GPU.

python/array
python/data_types
python/config
python/devices_and_streams
python/export
python/ops
Expand Down
11 changes: 11 additions & 0 deletions docs/src/python/config.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Config
======

.. currentmodule:: mlx.core.config

.. autosummary::
:toctree: _autosummary

update
get
scoped_update
8 changes: 5 additions & 3 deletions docs/src/usage/environment_variables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ Environment Variables
=====================

MLX uses environment variables to configure compilation, numerical precision,
backend behavior, and distributed execution. Set them before starting the
process. Many variables are read when the corresponding subsystem is first
initialized and changing them later may have no effect.
backend behavior, and distributed execution. They must be set before invoking
any MLX API, and can not be changed later.

For dynamically changing the configurations in the middle of program, use the
:func:`mlx.core.config.update` API.

Boolean variables use ``0`` to disable and a nonzero integer to enable unless
otherwise noted.
Expand Down
1 change: 1 addition & 0 deletions mlx/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ target_sources(
mlx
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/array.cpp
${CMAKE_CURRENT_SOURCE_DIR}/compile.cpp
${CMAKE_CURRENT_SOURCE_DIR}/config.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device.cpp
${CMAKE_CURRENT_SOURCE_DIR}/dtype.cpp
${CMAKE_CURRENT_SOURCE_DIR}/dtype_utils.cpp
Expand Down
2 changes: 1 addition & 1 deletion mlx/backend/cuda/device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace mlx::core::cu {
namespace {

bool use_cuda_graphs() {
static bool use_graphs = env::get_var("MLX_USE_CUDA_GRAPHS", true);
static bool use_graphs = config::get("MLX_USE_CUDA_GRAPHS", true);
return use_graphs;
}

Expand Down
4 changes: 2 additions & 2 deletions mlx/backend/cuda/lru_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ class LRUCache {

// Initialize with capacity read from |env_name|.
LRUCache(const char* env_name, int default_capacity)
: LRUCache(env::get_var(env_name, default_capacity)) {
if (env::get_var("MLX_ENABLE_CACHE_THRASHING_CHECK", 1)) {
: LRUCache(config::get(env_name, default_capacity)) {
if (config::get("MLX_ENABLE_CACHE_THRASHING_CHECK", 1)) {
env_name_ = env_name;
}
}
Expand Down
5 changes: 1 addition & 4 deletions mlx/backend/cuda/scaled_dot_product_attention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -319,10 +319,7 @@ bool supports_sdpa_cudnn(
bool has_arr_mask,
bool do_causal,
Stream s) {
static bool enabled = env::get_var("MLX_CUDA_USE_CUDNN_SDPA", 1);
if (!enabled) {
return false;
}
bool enabled = config::get("MLX_CUDA_USE_CUDNN_SDPA", 1);

// cuDNN SDPA requires Ampere and later.
if (cu::device(s.device).compute_capability_major() < 8) {
Expand Down
9 changes: 4 additions & 5 deletions mlx/backend/metal/conv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ inline int max_unfold_rows(metal::Device& d, size_t row_bytes, int total_rows) {
size_t max_buffer = d.mtl_device()->maxBufferLength();
size_t max_rows = row_bytes == 0 ? total_rows : max_buffer / row_bytes;
// Force a smaller tile (tests, or to bound the unfold buffer further).
if (int forced = env::get_var("MLX_CONV_UNFOLD_TILE_ROWS", 0); forced > 0) {
if (int forced = config::get("MLX_CONV_UNFOLD_TILE_ROWS", 0); forced > 0) {
max_rows = std::min(max_rows, static_cast<size_t>(forced));
}
if (max_rows == 0) {
Expand Down Expand Up @@ -72,7 +72,7 @@ inline int winograd_batch_step(

// Limit of maximum memory can be used for the step.
size_t working_set = d.mtl_device()->recommendedMaxWorkingSetSize();
if (int env_ws = env::get_var("MLX_CONV_WINOGRAD_WORKING_SET", 0);
if (int env_ws = config::get("MLX_CONV_WINOGRAD_WORKING_SET", 0);
env_ws > 0) {
working_set = env_ws;
}
Expand All @@ -96,8 +96,7 @@ inline int winograd_batch_step(
(conv_params.C + conv_params.O) * itemsize;
auto max_n = static_cast<int64_t>(budget / bytes_per_n);
int safe_n = static_cast<int>(std::min<int64_t>(max_n, total_n));
if (int forced = env::get_var("MLX_CONV_WINOGRAD_TILE_BATCH", 0);
forced > 0) {
if (int forced = config::get("MLX_CONV_WINOGRAD_TILE_BATCH", 0); forced > 0) {
return std::min(forced, safe_n);
}

Expand Down Expand Up @@ -1450,7 +1449,7 @@ void dispatch_conv_2D_gpu(
if (!conv_params.flip && is_stride_one && is_kdil_one && is_idil_one &&
conv_params.wS[0] == 3 && conv_params.wS[1] == 3 &&
conv_params.C % 32 == 0 && conv_params.O % 32 == 0 && inp_large &&
channels_large && env::get_var("MLX_CONV_WINOGRAD", 1)) {
channels_large && config::get("MLX_CONV_WINOGRAD", 1)) {
// Only use winograd conv when having enough memory.
if (int n_step = winograd_batch_step(d, in, conv_params); n_step > 0) {
return winograd_conv_2D_gpu(
Expand Down
19 changes: 15 additions & 4 deletions mlx/backend/metal/device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ namespace {

constexpr const char* default_mtllib_path = METAL_PATH;

const std::string& metal_gpu_arch() {
static std::string gpu_arch_ = []() {
if (const char* str = std::getenv("MLX_METAL_GPU_ARCH")) {
return str;
} else {
return "";
}
}();
return gpu_arch_;
}

void set_compile_options(
MTL::CompileOptions* mtl_options,
const CompileOptions& compile_options) {
Expand Down Expand Up @@ -525,7 +536,9 @@ void CommandEncoder::wait_event(Event event, uint64_t value) {
}

bool CommandEncoder::needs_commit() const {
auto [max_ops, max_mb] = device_.get_max_ops_mb_per_buffer();
auto [max_ops, max_mb] = device_.get_default_max_ops_mb_per_buffer();
max_ops = env::max_ops_per_buffer(max_ops);
max_mb = env::max_mb_per_buffer(max_mb);
return (buffer_ops_ > max_ops) || ((buffer_sizes_ >> 20) > max_mb);
}

Expand Down Expand Up @@ -602,7 +615,7 @@ MTL::ComputeCommandEncoder* CommandEncoder::get_command_encoder() {
Device::Device() : device_(load_device()), residency_sets_(device_.get()) {
auto pool = new_scoped_memory_pool();
default_library_ = NS::TransferPtr(load_default_library(device_.get()));
arch_ = env::metal_gpu_arch();
arch_ = metal_gpu_arch();
if (arch_.empty()) {
arch_ = std::string(device_->architecture()->name()->utf8String());
}
Expand Down Expand Up @@ -638,8 +651,6 @@ Device::Device() : device_(load_device()), residency_sets_(device_.get()) {
max_mb_per_buffer_ = 40;
break;
}
max_ops_per_buffer_ = env::max_ops_per_buffer(max_ops_per_buffer_);
max_mb_per_buffer_ = env::max_mb_per_buffer(max_mb_per_buffer_);
}

Device::~Device() = default;
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 @@ -166,7 +166,7 @@ class MLX_API Device {
int get_architecture_gen() const {
return arch_gen_;
}
std::tuple<int, int> get_max_ops_mb_per_buffer() const {
std::tuple<int, int> get_default_max_ops_mb_per_buffer() const {
return std::make_tuple(max_ops_per_buffer_, max_mb_per_buffer_);
}

Expand Down
2 changes: 1 addition & 1 deletion mlx/backend/metal/fence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ struct FenceImpl {
if (!d->supportsFamily(MTL::GPUFamilyMetal3)) {
use_fast = false;
} else if (__builtin_available(macOS 15, iOS 18, *)) {
use_fast = env::metal_fast_synch();
use_fast = config::get("MLX_METAL_FAST_SYNCH", 0);
}

if (!use_fast) {
Expand Down
8 changes: 4 additions & 4 deletions mlx/backend/metal/gated_delta_update.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@ namespace {

inline int gated_delta_chunk_size(int T) {
const bool nax = metal::is_nax_available();
const int C = env::get_var("GATED_DELTA_CHUNK", T > 8 ? (nax ? 16 : 8) : 1);
const int C = config::get("GATED_DELTA_CHUNK", T > 8 ? (nax ? 16 : 8) : 1);
return (C == 16 && !nax) ? 8 : C;
}

inline int gated_delta_chunk_size_vjp() {
const bool nax = metal::is_nax_available();
return nax ? env::get_var("GATED_DELTA_CHUNK_VJP", 16) : 1;
return nax ? config::get("GATED_DELTA_CHUNK_VJP", 16) : 1;
}

inline int gated_delta_ckpt(int chunk) {
int c = env::get_var("GATED_DELTA_CKPT", 16);
int c = config::get("GATED_DELTA_CKPT", 16);
if (c != 1 && c != 4 && c != 8 && c != 16) {
c = 16;
}
Expand Down Expand Up @@ -226,7 +226,7 @@ bool GatedDeltaUpdateVJP::use_fallback(
if (s.device == Device::cpu) {
return true;
}
if (env::get_var("GATED_DELTA_VJP_FALLBACK", 0) != 0) {
if (config::get("GATED_DELTA_VJP_FALLBACK", 0) != 0) {
return true;
}
return !supported_gated_delta_shape(Hk, Dk, Hv, Dv);
Expand Down
12 changes: 8 additions & 4 deletions mlx/backend/metal/resident.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

#include "mlx/backend/metal/device.h"
#include "mlx/backend/metal/resident.h"
#include "mlx/utils.h"
#include "mlx/config.h"

namespace mlx::core::metal {

Expand All @@ -21,7 +21,11 @@ ResidencySets::ResidencySets(MTL::Device* d) {
if (__builtin_available(macOS 15, iOS 18, *)) {
device_ = d;
enabled_ = true;
int pct = env::residency_set_max_pct();
// Per-set residency-set size, as a percentage of the device's recommended
// max working-set size. Controls only how wired memory is distributed
// across residency sets, never how much is wired; see metal::ResidencySets.
// A value <= 0 or >= 100 puts everything in a single set.
int pct = config::get("MLX_RESIDENCY_SET_MAX_PCT", 5);
if (pct <= 0 || pct >= 100) {
max_bytes_per_set_ = 0; // a single set holds everything
} else {
Expand All @@ -45,7 +49,7 @@ ResidencySets::ResidencySets(MTL::Device* d) {
throw std::runtime_error(msg.str());
}
if (int interval =
env::get_var("MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS", 0);
config::get("MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS", 0);
interval > 0) {
refresh_thread_ = std::thread([this, interval] {
std::unique_lock<std::mutex> lock(mtx_);
Expand Down Expand Up @@ -98,7 +102,7 @@ bool ResidencySets::add_set_locked(std::string* error_out) {
}
sets_.push_back(Set{std::move(set), 0});
num_sets_.store(sets_.size(), std::memory_order_release);
if (env::residency_debug()) {
if (config::get("MLX_RESIDENCY_DEBUG", 0)) {
fprintf(
stderr,
"[residency] created residency set %zu (max_bytes_per_set=%zu MB)\n",
Expand Down
4 changes: 2 additions & 2 deletions mlx/backend/metal/resident.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ namespace mlx::core::metal {
// size of each set bounds the cost of one such event. Every set holds a
// standing requestResidency() and is attached to every command queue.
//
// MLX_RESIDENCY_SET_MAX_PCT (env::residency_set_max_pct) sets the per-set cap.
// The total wired budget is unaffected by it: that is still `set_wired_limit`.
// MLX_RESIDENCY_SET_MAX_PCT sets the per-set cap. The total wired budget is
// unaffected by it: that is still `set_wired_limit`.
class ResidencySets {
public:
ResidencySets(MTL::Device* d);
Expand Down
14 changes: 7 additions & 7 deletions mlx/backend/metal/scaled_dot_product_attention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ void sdpa_full_self_attention_metal(
bool pad_default = qL >= 512 && kL >= 512 && !do_causal_ && !mask && !sinks;
if ((D == 72 || D == 80) && lse == nullptr && metal::is_nax_available() &&
(q.dtype() == float16 || q.dtype() == bfloat16) &&
env::get_var("MLX_SDPA_PAD_HEAD_DIM", pad_default ? 1 : 0) == 1) {
config::get("MLX_SDPA_PAD_HEAD_DIM", pad_default ? 1 : 0) == 1) {
constexpr int pad_to = 96;
auto& enc = metal::get_command_encoder(s);
array zero = array(0, q.dtype());
Expand Down Expand Up @@ -805,7 +805,7 @@ void sdpa_vector_2pass(
blocks = 32;
}
}
if (int blocks_env = env::get_var("MLX_SDPA_BLOCKS", 0); blocks_env > 0) {
if (int blocks_env = config::get("MLX_SDPA_BLOCKS", 0); blocks_env > 0) {
// The 2-pass reduction consumes the partials in simd-width (32) chunks
// and silently drops the tail otherwise, so round up to a multiple of 32.
blocks = ((blocks_env + 31) / 32) * 32;
Expand Down Expand Up @@ -1020,7 +1020,7 @@ std::tuple<bool, std::string> has_fused_kernel(
// cost. By default, use it only for one query, GQA factor 8, and no array
// mask.
if (query_head_dim == 512) {
int min_key_sequence_length = env::get_var("MLX_SDPA_D512_MIN_KL", 1024);
int min_key_sequence_length = config::get("MLX_SDPA_D512_MIN_KL", 1024);
bool always = (min_key_sequence_length == 0);
if (!always && query_sequence_length != 1) {
msg << "the vector attention kernel for head dim 512 defaults to "
Expand Down Expand Up @@ -1122,14 +1122,14 @@ array vjp_row_slice(const array& x, int t0, int len) {
std::pair<int, int> sdpa_vjp_blocks(int B, int H, int qL, int kL, Dtype ctype) {
constexpr int kDefaultBlock = 1024;

int blk = env::get_var("MLX_SDPA_VJP_BLOCK", kDefaultBlock);
int blk = config::get("MLX_SDPA_VJP_BLOCK", kDefaultBlock);

int bq = std::min(blk, qL);
int bk = std::min(blk, kL);
if (int e = env::get_var("MLX_SDPA_VJP_BQ", 0); e > 0) {
if (int e = config::get("MLX_SDPA_VJP_BQ", 0); e > 0) {
bq = std::min(e, qL);
}
if (int e = env::get_var("MLX_SDPA_VJP_BK", 0); e > 0) {
if (int e = config::get("MLX_SDPA_VJP_BK", 0); e > 0) {
bk = std::min(e, kL);
}
return {bq, bk};
Expand Down Expand Up @@ -1642,7 +1642,7 @@ bool ScaledDotProductAttentionVJP::use_fallback(const array& q, Stream s) {
if (s.device != Device::gpu) {
return true;
}
if (env::get_var("MLX_SDPA_VJP_FALLBACK", 0) != 0) {
if (config::get("MLX_SDPA_VJP_FALLBACK", 0) != 0) {
return true;
}
auto dt = q.dtype();
Expand Down
Loading
Loading