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/python/metal.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Metal
:toctree: _autosummary

is_available
is_nax_available
device_info
start_capture
stop_capture
7 changes: 7 additions & 0 deletions docs/src/usage/environment_variables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ Metal
Enable the faster Metal CPU/GPU synchronization path. The default is ``0``.
This requires Metal 3.2 or later (macOS 15 or later, or iOS 18 or later).

.. envvar:: MLX_METAL_RUNTIME_COMPILE

Allow building Metal libraries from source at runtime. The default is
``1``. Set it to ``0`` to throw instead when a kernel needs a library that
has not been loaded yet. Libraries loaded earlier, including ones loaded by
name from a ``.metallib``, are still used.

Advanced tuning
---------------

Expand Down
6 changes: 6 additions & 0 deletions mlx/backend/metal/device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,12 @@ MTL::Library* Device::get_library(
return it->second.get();
}

if (!env::get_var("MLX_METAL_RUNTIME_COMPILE", 1)) {
throw std::runtime_error(
"[metal::Device] Library " + name +
" is not loaded and runtime compilation is disabled.");
}

auto mtl_lib = build_library_(builder(), compile_options);
library_map_.insert({name, mtl_lib});
return mtl_lib.get();
Expand Down
3 changes: 1 addition & 2 deletions mlx/backend/metal/device.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#include "mlx/array.h"
#include "mlx/backend/common/metal_kernel.h"
#include "mlx/backend/metal/metal.h"
#include "mlx/backend/metal/resident.h"
#include "mlx/device.h"

Expand Down Expand Up @@ -268,6 +269,4 @@ std::unordered_map<int, CommandEncoder>& get_command_encoders();
std::unordered_map<int, CommandEncoder>& get_global_command_encoders();
NS::SharedPtr<NS::AutoreleasePool> new_scoped_memory_pool();

bool is_nax_available();

} // namespace mlx::core::metal
4 changes: 3 additions & 1 deletion mlx/backend/metal/kernels/gemv.metal
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ instantiate_gemv_bs_blocks(complex64, complex64_t);
instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 4) \
instantiate_gemv_t(name, itype, 1, 4, 8, 4, 4, 4) \
instantiate_gemv_t(name, itype, 1, 16, 8, 4, 4, 4) \
instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4) // clang-format on
instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4) \
instantiate_gemv_t(name, itype, 1, 8, 8, 4, 4, 4) \
instantiate_gemv_t(name, itype, 4, 2, 8, 4, 4, 4) // clang-format on

// clang-format off
instantiate_gemv_t_blocks(float32, float);
Expand Down
2 changes: 2 additions & 0 deletions mlx/backend/metal/kernels/sort.metal
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ instantiate_block_sort_bn(int32, int32_t)
instantiate_block_sort_bn(float16, half)
instantiate_block_sort_bn(float32, float)
instantiate_block_sort_bn(bfloat16, bfloat16_t)
instantiate_block_sort_bn(bool_, bool)

#define instantiate_block_sort_long(itname, itype) \
instantiate_block_sort_tn(itname, itype, 32) \
Expand Down Expand Up @@ -73,6 +74,7 @@ instantiate_multi_block_sort_base(int32, int32_t)
instantiate_multi_block_sort_base(float16, half)
instantiate_multi_block_sort_base(float32, float)
instantiate_multi_block_sort_base(bfloat16, bfloat16_t)
instantiate_multi_block_sort_base(bool_, bool)

#define instantiate_multi_block_sort_long(vtname, vtype) \
instantiate_multi_block_sort(vtname, vtype, uint32, uint32_t, true, 256, 4)
Expand Down
12 changes: 5 additions & 7 deletions mlx/backend/metal/kernels/steel/utils/integral_constant.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,11 @@ using Int = integral_constant<int, val>;
// Binary Operators on Integral constants
///////////////////////////////////////////////////////////////////////////////

#define integral_const_binop(__op__, __operator__) \
template <typename T, T tv, typename U, U uv> \
METAL_FUNC constexpr auto __operator__( \
integral_constant<T, tv>, integral_constant<U, uv>) { \
constexpr auto res = tv __op__ uv; \
using res_t = metal::remove_addrspace_t<decltype(res)>; \
return integral_constant<res_t, res>{}; \
#define integral_const_binop(__op__, __operator__) \
template <typename T, T tv, typename U, U uv> \
METAL_FUNC constexpr auto __operator__( \
integral_constant<T, tv>, integral_constant<U, uv>) { \
return integral_constant<const decltype(tv __op__ uv), (tv __op__ uv)>{}; \
}

integral_const_binop(+, operator+);
Expand Down
22 changes: 17 additions & 5 deletions mlx/backend/metal/matmul.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1287,25 +1287,37 @@ void gemv_axbpy(
std::ostringstream kname;

if (transpose_mat) {
if (in_vector_len >= 8192 && out_vector_len >= 2048) {
// Specialized kernel for very small outputs
tn = out_vector_len < tn ? 1 : tn;

// A long K with few outputs launches too few simdgroups to fill the GPU,
// so split K or use smaller threadgroups
bool large_mat = in_vector_len >= 8192 && out_vector_len >= 2048;
size_t n_simdgroups =
batch_size_out * ceildiv(out_vector_len, (large_mat ? 8 : 4) * tn);
bool few_simdgroups = tn == 4 && in_vector_len >= 256 && n_simdgroups < 128;

if (large_mat && !few_simdgroups) {
sm = 4;
sn = 8;
} else {
sm = 8;
sn = 4;
}

if (out_vector_len >= 2048) {
if (few_simdgroups && out_vector_len < 1024) {
bm = 4;
bn = 2;
} else if (few_simdgroups && large_mat) {
bn = 8;
} else if (out_vector_len >= 2048) {
bn = 16;
} else if (out_vector_len >= 512) {
bn = 4;
} else {
bn = 2;
}

// Specialized kernel for very small outputs
tn = out_vector_len < tn ? 1 : tn;

n_out_per_tgp = bn * sn * tn;
kname << "gemv_t_" << type_to_name(out);

Expand Down
3 changes: 3 additions & 0 deletions mlx/backend/metal/metal.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace mlx::core::metal {
/* Check if the Metal backend is available. */
MLX_API bool is_available();

/* Check if MLX kernels can use the GPU neural accelerators (NAX). */
MLX_API bool is_nax_available();

/** Capture a GPU trace, saving it to an absolute file `path` */
MLX_API void start_capture(std::string path = "");
MLX_API void stop_capture();
Expand Down
4 changes: 4 additions & 0 deletions mlx/backend/metal/no_metal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ bool is_available() {
return false;
}

bool is_nax_available() {
return false;
}

void start_capture(std::string) {}
void stop_capture() {}

Expand Down
16 changes: 15 additions & 1 deletion mlx/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>

#if defined(__APPLE__)
#include <pthread.h>
#elif defined(__linux__)
#include <sys/syscall.h>
#include <unistd.h>
#else
#include <thread>
#endif

#include "mlx/dtype_utils.h"
#include "mlx/types/limits.h"
#include "mlx/utils.h"
Expand Down Expand Up @@ -126,8 +134,14 @@ void set_printoptions(PrintOptions options) {
}

bool is_main_thread() {
#if defined(__APPLE__)
return pthread_main_np() != 0;
#elif defined(__linux__)
return syscall(SYS_gettid) == getpid();
#else
static auto main_thread_id = std::this_thread::get_id();
return main_thread_id == std::this_thread::get_id();
#endif
}

Dtype result_type(const std::vector<array>& arrays) {
Expand Down
3 changes: 2 additions & 1 deletion mlx/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ MLX_API void set_printoptions(PrintOptions options);

MLX_API PrintFormatter& get_global_formatter();

/** Return whether current thread is the first one that called this function. */
/** Check for the process main thread on Apple platforms and Linux.
* Elsewhere, compare with the thread ID from the first call. */
bool is_main_thread();

/** Holds information about floating-point types. */
Expand Down
6 changes: 6 additions & 0 deletions python/src/metal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ void init_metal(nb::module_& m) {
R"pbdoc(
Check if the Metal back-end is available.
)pbdoc");
metal.def(
"is_nax_available",
&mx::metal::is_nax_available,
R"pbdoc(
Check if MLX kernels can use the GPU neural accelerators (NAX).
)pbdoc");
metal.def("get_active_memory", []() {
DEPRECATE("mx.metal.get_active_memory", "mx.get_active_memory");
return mx::get_active_memory();
Expand Down
18 changes: 18 additions & 0 deletions python/tests/test_blas.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def test_matrix_vector(self):
(2, 2),
(32, 32),
(64, 64),
(300, 40),
(2048, 2048),
):
for mi in (-1, 0, 1):
Expand Down Expand Up @@ -371,6 +372,8 @@ def test_matrix_vector_batched(self):
((32, 1, 128), (128, 64)),
((1, 128), (32, 128, 64)),
((1, 8, 4, 1, 128), (1, 8, 1, 128, 6)),
((3, 1, 300), (3, 300, 40)),
((2, 1, 1, 300), (1, 3, 300, 40)),
):
self.__gemv_test(
shape_mat, shape_vec, mat_first=False, np_dtype=np_dtype
Expand Down Expand Up @@ -795,6 +798,21 @@ def test_addmm(self):
self.assertListEqual(list(d_npy.shape), list(d_mlx.shape))
self.assertTrue(np.allclose(d_mlx, d_npy, atol=1e-5))

# Matmul with vector and a long K, on a local generator to keep
# the global numpy state for later tests
rng = np.random.default_rng(0)
for k, n, batch in ((512, 128, (4,)), (8192, 2048, ())):
a_npy = rng.normal(0.0, 1.0 / 128, (k,)).astype(np.float32)
b_npy = rng.normal(0.0, 1.0 / 128, batch + (k, n)).astype(np.float32)

for c_shape in ((1,), (n,), batch + (n,)):
c_npy = np.ones(c_shape).astype(np.float32)
d_npy = alpha * (a_npy @ b_npy) + beta * c_npy
d_mlx = mx.addmm(
mx.array(c_npy), mx.array(a_npy), mx.array(b_npy), alpha, beta
)
self.assertTrue(np.allclose(d_mlx, d_npy, atol=1e-5))

# Matmul with vector
a_npy = np.random.normal(0.0, 1.0 / 128, (32, 128, 16)).astype(np.float32)
b_npy = np.random.normal(0.0, 1.0 / 128, (16,)).astype(np.float32)
Expand Down
6 changes: 6 additions & 0 deletions python/tests/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,12 @@ def test_device_info_gpu(self):
self.assertTrue(len(info["device_name"]) > 0)
self.assertIn("architecture", info)

def test_metal_is_nax_available(self):
nax = mx.metal.is_nax_available()
self.assertIsInstance(nax, bool)
if not mx.metal.is_available():
self.assertFalse(nax)

def test_device_info_default(self):
info = mx.device_info()
self.assertIsInstance(info, dict)
Expand Down
20 changes: 2 additions & 18 deletions python/tests/test_fast_sdpa.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,29 +365,13 @@ def test_sdpa_full_head_dim_256(self):
def test_sdpa_full_head_dim_512_nax(self):
if mx.default_device() != mx.gpu:
self.skipTest("requires GPU")
if not mx.metal.is_nax_available():
self.skipTest("D512 full attention requires NAX")

D = 512
scale = D**-0.5
mx.random.seed(0)

q_probe = mx.random.normal(shape=(1, 2, 9, D)).astype(mx.bfloat16)
k_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16)
v_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16)
try:
mx.eval(
mx.fast.scaled_dot_product_attention(
q_probe,
k_probe,
v_probe,
scale=scale,
force_fused=True,
)
)
except ValueError as e:
if "plus head dim 512 on NAX GPUs" not in str(e):
raise
self.skipTest("D512 full attention requires NAX")

cases = [
# Multiple query tiles with GQA.
(1, 8, 2, 257, 513, None, True),
Expand Down
12 changes: 12 additions & 0 deletions python/tests/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -4557,6 +4557,18 @@ def test_argsort_nan(self):
sorted_x = mx.take(x, mx.argsort(x))
self.assertTrue(mx.array_equal(sorted_x, expected, equal_nan=True))

def test_sort_bool(self):
np.random.seed(0)
# Small sizes use the single block sort, large sizes the multi-block sort
for size in [10, 5000, 50000]:
with self.subTest(size=size):
a_np = np.random.uniform(size=size) < 0.5
a_mx = mx.array(a_np)
self.assertTrue(np.array_equal(mx.sort(a_mx), np.sort(a_np)))
self.assertEqual(mx.sort(a_mx).dtype, mx.bool_)
idx = mx.argsort(a_mx)
self.assertTrue(np.array_equal(mx.take(a_mx, idx), np.sort(a_np)))

def test_to_from_fp8(self):
vals = mx.array(
[448, 256, 192, 128, 96, 64, 48, 32, 24, 16, 12, 8, 6, 4, 3, 2, 0.015625]
Expand Down