From 535d4e4eeb575bcd9ca8d424e741f000b06b9232 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:08:20 -0700 Subject: [PATCH 01/44] feat(distributed): sealed all-sum (two ranks; partials cross only as codec-sealed frames) all_sum_sealed(x, group, stream) is evaluated on the CPU stream inside the lazy graph like the native all-sum: the local partial is sealed by a codec the embedding program installs (set_seal_codec: seal, open, context, per-frame overhead), the two frames are all-gathered over the group, the peer's frame is opened (a frame that does not authenticate fails the evaluation; there is no plaintext fallback) and the partials are added in rank order (rank 0 + rank 1) so both ranks hold the same bits. float32, bfloat16, float16; a counter advances per sealed all-sum in evaluation order, identically on both ranks, for the codec's nonces. No codec: the graph refuses to build. Co-Authored-By: Claude Opus 5.5 --- mlx/distributed/CMakeLists.txt | 3 +- mlx/distributed/primitives.h | 24 ++++++ mlx/distributed/sealed.cpp | 129 +++++++++++++++++++++++++++++++++ mlx/distributed/sealed.h | 47 ++++++++++++ 4 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 mlx/distributed/sealed.cpp create mode 100644 mlx/distributed/sealed.h diff --git a/mlx/distributed/CMakeLists.txt b/mlx/distributed/CMakeLists.txt index 807fd0fbdb..dba62b2720 100644 --- a/mlx/distributed/CMakeLists.txt +++ b/mlx/distributed/CMakeLists.txt @@ -2,7 +2,8 @@ target_sources( mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/primitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ops.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/distributed.cpp) + ${CMAKE_CURRENT_SOURCE_DIR}/distributed.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sealed.cpp) if(MLX_BUILD_CPU AND NOT WIN32) target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp) diff --git a/mlx/distributed/primitives.h b/mlx/distributed/primitives.h index 18a0d65f5f..79979a3b4d 100644 --- a/mlx/distributed/primitives.h +++ b/mlx/distributed/primitives.h @@ -3,6 +3,8 @@ #pragma once #include "mlx/distributed/distributed.h" +#include "mlx/distributed/sealed.h" +#include #include "mlx/distributed/distributed_impl.h" #include "mlx/primitives.h" @@ -67,6 +69,28 @@ class AllReduce : public DistPrimitive { ReduceType reduce_type_; }; +/// The sealed all-sum (`all_sum_sealed`, sealed.h): seal, all-gather the two +/// frames, open the peer's, add in rank order. `counter_` advances per +/// evaluation; both ranks evaluate the same graph in the same order. +class SealedAllSum : public DistPrimitive { + public: + SealedAllSum(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + const char* name() const override { + return "SealedAllSum"; + } + + private: + SealCodec codec_; + static inline std::atomic counter_{0}; +}; + class AllGather : public DistPrimitive { public: AllGather(Stream stream, Group group) : DistPrimitive(stream, group) {} diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp new file mode 100644 index 0000000000..f3f83326c0 --- /dev/null +++ b/mlx/distributed/sealed.cpp @@ -0,0 +1,129 @@ +// Copyright © 2026 Darkbloom. + +#include +#include + +#include "mlx/allocator.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/distributed/distributed_impl.h" +#include "mlx/distributed/primitives.h" +#include "mlx/distributed/sealed.h" + +namespace mlx::core::distributed { + +namespace { +std::mutex codec_mutex; +std::optional installed_codec; +} // namespace + +void set_seal_codec(SealCodec codec) { + std::lock_guard lock(codec_mutex); + if (codec.seal == nullptr || codec.open == nullptr) { + installed_codec.reset(); + } else { + installed_codec = codec; + } +} + +std::optional seal_codec() { + std::lock_guard lock(codec_mutex); + return installed_codec; +} + +array all_sum_sealed(const array& x, std::optional group_, StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + if (group.size() != 2) { + throw std::invalid_argument("[all_sum_sealed] needs exactly two ranks"); + } + if (x.dtype() != float32 && x.dtype() != bfloat16 && x.dtype() != float16) { + throw std::invalid_argument("[all_sum_sealed] sums float32, bfloat16 or float16 partials only"); + } + auto codec = seal_codec(); + if (!codec.has_value()) { + throw std::runtime_error("[all_sum_sealed] no seal codec is installed: a partial never crosses the link in the clear"); + } + auto stream = detail::communication_stream(group, s); + return array(x.shape(), x.dtype(), std::make_shared(stream, group, *codec), {x}); +} + +namespace { +template +void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast(static_cast(rank0[i]) + static_cast(rank1[i])); + } +} +template <> +void add_in_rank_order(const float* rank0, const float* rank1, float* out, size_t n) { + for (size_t i = 0; i < n; ++i) { + out[i] = rank0[i] + rank1[i]; + } +} +} // namespace + +void SealedAllSum::eval_cpu(const std::vector& inputs, std::vector& outputs) { + auto in = inputs[0].flags().row_contiguous ? inputs[0] : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + size_t n = in.nbytes(); + size_t frame = n + codec_.overhead; + array sealed({static_cast(frame)}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(frame)); + array gathered({static_cast(2 * frame)}, uint8, nullptr, {}); + gathered.set_data(allocator::malloc(2 * frame)); + array peer(in.shape(), in.dtype(), nullptr, {}); + peer.set_data(allocator::malloc(n)); + + int rank = group().rank(); + uint64_t counter = counter_++; + auto codec = codec_; + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(sealed); + encoder.dispatch([codec, src = in.data(), dst = sealed.data(), n, counter]() { + if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { + throw std::runtime_error("[all_sum_sealed] the codec refused to seal a partial"); + } + }); + distributed::detail::all_gather(group(), sealed, gathered, stream()); + encoder.set_input_array(gathered); + encoder.set_output_array(out); + encoder.dispatch([codec, frames = gathered.data(), mine = in.data(), theirs = peer.data(), + dst = out.data(), n, frame, counter, rank, dtype = in.dtype()]() { + const char* peer_frame = frames + (rank == 0 ? frame : 0); + if (codec.open(codec.ctx, peer_frame, n, theirs, counter, 1 - rank) != 0) { + throw std::runtime_error("[all_sum_sealed] a peer frame did not authenticate: refused"); + } + const char* r0 = rank == 0 ? mine : theirs; + const char* r1 = rank == 0 ? theirs : mine; + switch (dtype) { + case float32: + add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), + reinterpret_cast(dst), n / sizeof(float)); + break; + case bfloat16: + add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), + reinterpret_cast(dst), n / sizeof(bfloat16_t)); + break; + case float16: + add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), + reinterpret_cast(dst), n / sizeof(float16_t)); + break; + default: + throw std::runtime_error("[all_sum_sealed] unsupported dtype"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(gathered); + encoder.add_temporary(peer); + if (!inputs[0].flags().row_contiguous) { + encoder.add_temporary(in); + } +} + +void SealedAllSum::eval_gpu(const std::vector&, std::vector&) { + throw std::runtime_error("[SealedAllSum::eval_gpu] has no GPU implementation."); +} + +} // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h new file mode 100644 index 0000000000..547ca12f1c --- /dev/null +++ b/mlx/distributed/sealed.h @@ -0,0 +1,47 @@ +// Copyright © 2026 Darkbloom. +// +// A sealed all-sum: the two ranks' partials cross the link only as +// authenticated, encrypted frames made and opened by a codec the embedding +// program registers (Darkbloom: AES-256-GCM with directional keys from its +// keyed data plane). Evaluated on the CPU stream inside the lazy graph, like +// the native all-sum, so the model thread never synchronizes the GPU for it. +// A frame that does not open is refused: the codec reports it and the +// evaluation fails; there is no plaintext fallback. + +#pragma once + +#include +#include +#include + +#include "mlx/api.h" +#include "mlx/distributed/distributed.h" +#include "mlx/utils.h" + +namespace mlx::core::distributed { + +// seal: plaintext (n bytes) -> frame (n + overhead bytes) for `counter`; +// open: the peer's frame -> plaintext (n bytes) for `counter` from `peer`. +// Both return 0 on success. `counter` advances by one per sealed all-sum, in +// evaluation order, identically on both ranks. +using SealFn = int (*)(void* ctx, const void* plaintext, size_t n, void* frame, uint64_t counter); +using OpenFn = int (*)(void* ctx, const void* frame, size_t n, void* plaintext, uint64_t counter, int peer); + +struct SealCodec { + SealFn seal = nullptr; + OpenFn open = nullptr; + void* ctx = nullptr; + size_t overhead = 0; +}; + +// Installs (or, with a null seal, removes) the process's codec. A sealed +// all-sum without a codec is refused when the graph is built. +MLX_API void set_seal_codec(SealCodec codec); +MLX_API std::optional seal_codec(); + +// The sum of two ranks' arrays, crossing the link sealed. Two ranks only; +// float32, bfloat16 and float16; the sum is taken in rank order (rank 0 + +// rank 1) so both ranks hold the same bits. +MLX_API array all_sum_sealed(const array& x, std::optional group = std::nullopt, StreamOrDevice s = {}); + +} // namespace mlx::core::distributed From eb576eb2684f9d97dd2460db52edd717decc6b58 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:20:08 -0700 Subject: [PATCH 02/44] fix(metal): bound sorted quantized NAX tail loads Use the remaining reduction width for the final activation tile. Check row and packed-column bounds before reading affine or floating-quantized weights and scales, then zero padding lanes. Add exact-value partial-tile and NaN-neighbor regression coverage for affine, MXFP4, MXFP8 and NVFP4. The companion Swift regression reproduced 48 failing geometries and passes all 272 cases with this repair. The original MiMo and Qwen fallback failures also pass on M5 Max. AI assistance: Codex diagnosed, implemented and tested this patch under the repository owner's explicit direction. --- fork.yaml | 18 +++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 25 ++++---- mlx/backend/metal/kernels/quantized_nax.h | 52 ++++++++-------- python/tests/test_quantized.py | 62 ++++++++++++++++++++ 4 files changed, 116 insertions(+), 41 deletions(-) diff --git a/fork.yaml b/fork.yaml index 024b4ab920..5338217c4b 100644 --- a/fork.yaml +++ b/fork.yaml @@ -229,15 +229,29 @@ def: - "docs/src/usage/environment_variables.rst" - "tests/jaccl/*" - "tests/jaccl/fake_verbs/infiniband/verbs.h" + - title: "Quantized NAX partial-tile bounds" + description: | + Sorted gathered matrix products use the remaining reduction width for a + partial activation tile. Safe affine and floating-quantized weight loaders + check row and packed-column bounds before reading weights or scales, then + zero invalid lanes. This prevents finite tails from reading the next row, + including a following NaN row. Exact Python regressions cover affine, + MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + Aligned dispatch and accumulation precision remain unchanged. + globs: + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official v0.32.2 by applying upstream's changes rather than merging them, so `git` sees them as - fork commits even though every file below is byte-identical to upstream `v0.32.2` + fork commits even though the imported content matches upstream `v0.32.2` (CUDA backend, CPU SIMD, kernels, Python bindings and tests, repository CI and templates, `AGENTS.md` / `CLAUDE.md`, docs). Listed here so the page does not credit Layr-Labs with upstream's changes; the section disappears once the fork rebases onto - an upstream commit at or past v0.32.2. + an upstream commit at or past v0.32.2. Later fork changes to these paths + are described in their own sections, including quantized NAX tile bounds. globs: - ".pre-commit-config.yaml" - "AGENTS.md" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index c7f9f8fcc7..04f8262b3a 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -149,14 +149,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -165,10 +158,18 @@ struct QuantizedBlockLoader { int k = 0; for (int i = 0; i < n_steps_per_read; i++) { - T scale = dequantize_scale(scales[i]); + const bool scale_in_bounds = (bj + k) * pack_factor < src_tile_dim.x; + T scale = + scale_in_bounds ? dequantize_scale(scales[i]) : T(0); for (int j = 0; j < n_reads_per_scale; j++) { - dequantize( - src[k * bytes_per_pack], scale, dst + k * pack_factor); + if ((bj + k) * pack_factor < src_tile_dim.x) { + dequantize( + src[k * bytes_per_pack], scale, dst + k * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[k * pack_factor + p] = T(0); + } + } k++; } } @@ -954,7 +955,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index bf90bb84fa..68f0ee2dd5 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -653,14 +653,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -670,11 +663,17 @@ struct QuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -793,14 +792,7 @@ struct QuantizedBlockLoader< return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -810,11 +802,17 @@ struct QuantizedBlockLoader< T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -1634,7 +1632,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 461175f013..f0edfa7455 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1600,6 +1600,68 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y4, atol=tol)) @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") + @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") + def test_gather_qmm_sorted_partial_tiles(self): + # Exact sums expose reading a following row as reduction-tile padding. + counts = [17, 3, 31, 14] + indices = [expert for expert, count in enumerate(counts) for _ in range(count)] + rhs = mx.array(indices, dtype=mx.uint32) + experts = [0.25, 0.5, 1.0, 2.0] + for mode, dtype, k, n in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.float16, mx.bfloat16], + [32, 64, 96, 128], + [32, 96], + ): + with self.subTest(mode=mode, dtype=dtype, k=k, n=n): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 scales are 1/4, 1/2, 1, 2. + wq = mx.full((4, n, k // 8), 0x22222222, dtype=mx.uint32) + scales = mx.broadcast_to( + mx.array([40, 48, 56, 64], dtype=mx.uint8)[:, None, None], + (4, n, k // 16), + ) + packed = (wq, scales) + else: + weights = mx.broadcast_to( + mx.array(experts, dtype=dtype)[:, None, None], (4, n, k) + ) + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + for poison in [False, True]: + rows = [ + float("nan") if poison and i % 2 else float(i % 3 + 1) + for i in range(len(indices)) + ] + x = mx.broadcast_to( + mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) + ) + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=rhs, + transpose=True, + group_size=group_size, + bits=bits, + mode=mode, + sorted_indices=True, + ) + expected = mx.array( + [ + rows[row] * k * experts[expert] + for row, expert in enumerate(indices) + ], + dtype=dtype, + )[:, None, None] + self.assertEqual(actual.shape, (len(indices), 1, n)) + equal = (actual == expected) | ( + mx.isnan(actual) & mx.isnan(expected) + ) + self.assertTrue(mx.all(equal).item(), f"poison={poison}") + def test_gather_qmm_sorted_sliced_weight(self): E, R, D, N = 8, 64, 256, 64 dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 From 635cb25db88e080644bdd2c851821b6c23d21828 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:21:37 -0700 Subject: [PATCH 03/44] docs(fork): describe sealed all-sum source ownership --- fork.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/fork.yaml b/fork.yaml index b8b571aefa..e71d1a0a69 100644 --- a/fork.yaml +++ b/fork.yaml @@ -234,6 +234,19 @@ def: - "docs/src/usage/environment_variables.rst" - "tests/jaccl/*" - "tests/jaccl/fake_verbs/infiniband/verbs.h" + - title: "Two-rank sealed all-sum" + description: | + The embedding program installs an authenticated frame codec for a two-rank + floating-point all-sum. The CPU communication stream seals each partial, + gathers the frames, opens the peer frame and adds in rank order. Missing + codecs and authentication failures refuse evaluation without a plaintext + fallback. The distributed primitive retains its temporary arrays until + the queued work completes. + globs: + - "mlx/distributed/CMakeLists.txt" + - "mlx/distributed/primitives.h" + - "mlx/distributed/sealed.cpp" + - "mlx/distributed/sealed.h" - title: "Quantized NAX partial-tile bounds" description: | Sorted gathered matrix products use the remaining reduction width for a From 652399bca8fb6e21c8ddde02ed6afeb9ae22ce0b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:36:33 -0700 Subject: [PATCH 04/44] style(distributed): apply configured formatting to sealed all-sum --- mlx/distributed/primitives.h | 4 +- mlx/distributed/sealed.cpp | 85 ++++++++++++++++++++++++++---------- mlx/distributed/sealed.h | 20 +++++++-- 3 files changed, 81 insertions(+), 28 deletions(-) diff --git a/mlx/distributed/primitives.h b/mlx/distributed/primitives.h index 79979a3b4d..1011c6fc04 100644 --- a/mlx/distributed/primitives.h +++ b/mlx/distributed/primitives.h @@ -2,10 +2,10 @@ #pragma once -#include "mlx/distributed/distributed.h" -#include "mlx/distributed/sealed.h" #include +#include "mlx/distributed/distributed.h" #include "mlx/distributed/distributed_impl.h" +#include "mlx/distributed/sealed.h" #include "mlx/primitives.h" namespace mlx::core::distributed { diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index f3f83326c0..41b0704ec0 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -31,39 +31,57 @@ std::optional seal_codec() { return installed_codec; } -array all_sum_sealed(const array& x, std::optional group_, StreamOrDevice s) { +array all_sum_sealed( + const array& x, + std::optional group_, + StreamOrDevice s) { auto group = group_.has_value() ? group_.value() : distributed::init(); if (group.size() != 2) { throw std::invalid_argument("[all_sum_sealed] needs exactly two ranks"); } if (x.dtype() != float32 && x.dtype() != bfloat16 && x.dtype() != float16) { - throw std::invalid_argument("[all_sum_sealed] sums float32, bfloat16 or float16 partials only"); + throw std::invalid_argument( + "[all_sum_sealed] sums float32, bfloat16 or float16 partials only"); } auto codec = seal_codec(); if (!codec.has_value()) { - throw std::runtime_error("[all_sum_sealed] no seal codec is installed: a partial never crosses the link in the clear"); + throw std::runtime_error( + "[all_sum_sealed] no seal codec is installed: a partial never crosses the link in the clear"); } auto stream = detail::communication_stream(group, s); - return array(x.shape(), x.dtype(), std::make_shared(stream, group, *codec), {x}); + return array( + x.shape(), + x.dtype(), + std::make_shared(stream, group, *codec), + {x}); } namespace { template void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { for (size_t i = 0; i < n; ++i) { - out[i] = static_cast(static_cast(rank0[i]) + static_cast(rank1[i])); + out[i] = static_cast( + static_cast(rank0[i]) + static_cast(rank1[i])); } } template <> -void add_in_rank_order(const float* rank0, const float* rank1, float* out, size_t n) { +void add_in_rank_order( + const float* rank0, + const float* rank1, + float* out, + size_t n) { for (size_t i = 0; i < n; ++i) { out[i] = rank0[i] + rank1[i]; } } } // namespace -void SealedAllSum::eval_cpu(const std::vector& inputs, std::vector& outputs) { - auto in = inputs[0].flags().row_contiguous ? inputs[0] : contiguous_copy_cpu(inputs[0], stream()); +void SealedAllSum::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); auto& out = outputs[0]; out.set_data(allocator::malloc(out.nbytes())); size_t n = in.nbytes(); @@ -81,34 +99,54 @@ void SealedAllSum::eval_cpu(const std::vector& inputs, std::vector auto& encoder = cpu::get_command_encoder(stream()); encoder.set_input_array(in); encoder.set_output_array(sealed); - encoder.dispatch([codec, src = in.data(), dst = sealed.data(), n, counter]() { - if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { - throw std::runtime_error("[all_sum_sealed] the codec refused to seal a partial"); - } - }); + encoder.dispatch( + [codec, src = in.data(), dst = sealed.data(), n, counter]() { + if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { + throw std::runtime_error( + "[all_sum_sealed] the codec refused to seal a partial"); + } + }); distributed::detail::all_gather(group(), sealed, gathered, stream()); encoder.set_input_array(gathered); encoder.set_output_array(out); - encoder.dispatch([codec, frames = gathered.data(), mine = in.data(), theirs = peer.data(), - dst = out.data(), n, frame, counter, rank, dtype = in.dtype()]() { + encoder.dispatch([codec, + frames = gathered.data(), + mine = in.data(), + theirs = peer.data(), + dst = out.data(), + n, + frame, + counter, + rank, + dtype = in.dtype()]() { const char* peer_frame = frames + (rank == 0 ? frame : 0); if (codec.open(codec.ctx, peer_frame, n, theirs, counter, 1 - rank) != 0) { - throw std::runtime_error("[all_sum_sealed] a peer frame did not authenticate: refused"); + throw std::runtime_error( + "[all_sum_sealed] a peer frame did not authenticate: refused"); } const char* r0 = rank == 0 ? mine : theirs; const char* r1 = rank == 0 ? theirs : mine; switch (dtype) { case float32: - add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), - reinterpret_cast(dst), n / sizeof(float)); + add_in_rank_order( + reinterpret_cast(r0), + reinterpret_cast(r1), + reinterpret_cast(dst), + n / sizeof(float)); break; case bfloat16: - add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), - reinterpret_cast(dst), n / sizeof(bfloat16_t)); + add_in_rank_order( + reinterpret_cast(r0), + reinterpret_cast(r1), + reinterpret_cast(dst), + n / sizeof(bfloat16_t)); break; case float16: - add_in_rank_order(reinterpret_cast(r0), reinterpret_cast(r1), - reinterpret_cast(dst), n / sizeof(float16_t)); + add_in_rank_order( + reinterpret_cast(r0), + reinterpret_cast(r1), + reinterpret_cast(dst), + n / sizeof(float16_t)); break; default: throw std::runtime_error("[all_sum_sealed] unsupported dtype"); @@ -123,7 +161,8 @@ void SealedAllSum::eval_cpu(const std::vector& inputs, std::vector } void SealedAllSum::eval_gpu(const std::vector&, std::vector&) { - throw std::runtime_error("[SealedAllSum::eval_gpu] has no GPU implementation."); + throw std::runtime_error( + "[SealedAllSum::eval_gpu] has no GPU implementation."); } } // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h index 547ca12f1c..15093d6aef 100644 --- a/mlx/distributed/sealed.h +++ b/mlx/distributed/sealed.h @@ -24,8 +24,19 @@ namespace mlx::core::distributed { // open: the peer's frame -> plaintext (n bytes) for `counter` from `peer`. // Both return 0 on success. `counter` advances by one per sealed all-sum, in // evaluation order, identically on both ranks. -using SealFn = int (*)(void* ctx, const void* plaintext, size_t n, void* frame, uint64_t counter); -using OpenFn = int (*)(void* ctx, const void* frame, size_t n, void* plaintext, uint64_t counter, int peer); +using SealFn = int (*)( + void* ctx, + const void* plaintext, + size_t n, + void* frame, + uint64_t counter); +using OpenFn = int (*)( + void* ctx, + const void* frame, + size_t n, + void* plaintext, + uint64_t counter, + int peer); struct SealCodec { SealFn seal = nullptr; @@ -42,6 +53,9 @@ MLX_API std::optional seal_codec(); // The sum of two ranks' arrays, crossing the link sealed. Two ranks only; // float32, bfloat16 and float16; the sum is taken in rank order (rank 0 + // rank 1) so both ranks hold the same bits. -MLX_API array all_sum_sealed(const array& x, std::optional group = std::nullopt, StreamOrDevice s = {}); +MLX_API array all_sum_sealed( + const array& x, + std::optional group = std::nullopt, + StreamOrDevice s = {}); } // namespace mlx::core::distributed From 65eb14fa3f64a56c9a807004b5af1b5f93f0c13d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:42:26 -0700 Subject: [PATCH 05/44] test(metal): exercise contiguous sorted quantized activation tiles --- python/tests/test_quantized.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index f0edfa7455..e5c81c3995 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1640,7 +1640,7 @@ def test_gather_qmm_sorted_partial_tiles(self): mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) ) actual = mx.gather_qmm( - x, + mx.contiguous(x), *packed, rhs_indices=rhs, transpose=True, From f7bbf7d73b1c8779ca0c58cf338027a48d877454 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:58:51 -0700 Subject: [PATCH 06/44] Give floating-point NAX loaders a distinct Metal symbol --- fork.yaml | 5 ++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/fork.yaml b/fork.yaml index e71d1a0a69..c920175400 100644 --- a/fork.yaml +++ b/fork.yaml @@ -247,7 +247,7 @@ def: - "mlx/distributed/primitives.h" - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" - - title: "Quantized NAX partial-tile bounds" + - title: "Quantized NAX tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders @@ -255,6 +255,9 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + The floating-point NAX loader has a distinct type name: its layout + differs from the non-NAX loader, and sharing a name corrupts MXFP4 + results when the offline Metal linker combines both translation units. Aligned dispatch and accumulation precision remain unchanged. globs: - "mlx/backend/metal/kernels/quantized_nax.h" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 04f8262b3a..f4db25db46 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -79,7 +79,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct FPQuantizedNAXBlockLoader { MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; @@ -107,7 +107,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedNAXBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -222,7 +222,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); // Instantiate Loader - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, BN, BK, @@ -366,7 +366,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< T, BK, BN, @@ -815,7 +815,7 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, transpose ? BN : BK, transpose ? BK : BN, From 1fb86d3fab639d9ba0e1d08a5ceb91423b416b78 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:06:28 -0700 Subject: [PATCH 07/44] Separate incompatible quantized Metal loader implementations --- fork.yaml | 10 ++++-- mlx/backend/metal/kernels/fp_quantized.h | 32 ++++++++--------- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++--- mlx/backend/metal/kernels/quantized.h | 38 ++++++++++---------- mlx/backend/metal/kernels/quantized_nax.h | 30 ++++++++-------- 5 files changed, 62 insertions(+), 58 deletions(-) diff --git a/fork.yaml b/fork.yaml index c920175400..08fd50e876 100644 --- a/fork.yaml +++ b/fork.yaml @@ -255,12 +255,16 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. - The floating-point NAX loader has a distinct type name: its layout - differs from the non-NAX loader, and sharing a name corrupts MXFP4 - results when the offline Metal linker combines both translation units. + Each affine/floating-point, legacy/NAX loader has a distinct type name. + Their layouts or bodies differ; sharing a name corrupts MXFP4 results + when the offline Metal linker combines the translation units. The + incompatible affine/FP pack-factor helpers and legacy/NAX vector loaders + also use distinct names. Aligned dispatch and accumulation precision remain unchanged. globs: + - "mlx/backend/metal/kernels/quantized.h" - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index e6c6a1de65..579ddf95ac 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -155,8 +155,8 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); +struct FPQuantizedBlockLoader { + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -181,7 +181,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -272,7 +272,7 @@ METAL_FUNC void fp_qmv_quad_impl( uint quad_gid [[quadgroup_index_in_threadgroup]], uint quad_lid [[thread_index_in_quadgroup]]) { constexpr int quads_per_simd = SIMD_SIZE / QUAD_SIZE; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int values_per_thread = D / QUAD_SIZE; constexpr int steps_per_thread = values_per_thread < group_size ? 1 : values_per_thread / group_size; @@ -342,7 +342,7 @@ METAL_FUNC void fp_qmv_fast_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int packs_per_thread = 2; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -430,7 +430,7 @@ METAL_FUNC void fp_qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -590,7 +590,7 @@ METAL_FUNC void fp_qmv_wide_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = SIMD_SIZE / k_lanes; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int nf4 = group_size / 4; // float4 lanes per quant group @@ -705,7 +705,7 @@ METAL_FUNC void fp_qvm_impl( uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = group_size / pack_factor; @@ -831,7 +831,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -841,7 +841,7 @@ METAL_FUNC void fp_qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BN, BK, @@ -955,7 +955,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -966,7 +966,7 @@ METAL_FUNC void fp_qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BK, BN, @@ -1894,7 +1894,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BN * BK_padded]; @@ -2011,7 +2011,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2030,7 +2030,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index f4db25db46..45e1bfebd3 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -80,7 +80,7 @@ template < short group_size, short bits> struct FPQuantizedNAXBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -216,7 +216,7 @@ METAL_FUNC void fp_qmm_t_impl( (void)lid; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); @@ -361,7 +361,7 @@ METAL_FUNC void fp_qmm_n_impl( (void)lid; (void)M; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -810,7 +810,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index 7b6f36eee1..d5a2953b32 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -15,7 +15,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -577,7 +577,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -589,7 +589,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -610,7 +610,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -769,7 +769,7 @@ METAL_FUNC void qmv_fast_impl( constexpr int packs_per_thread = bits == 2 ? 1 : 2; constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -836,7 +836,7 @@ METAL_FUNC void qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -1094,7 +1094,7 @@ METAL_FUNC void qvm_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = 32 / pack_factor; @@ -1220,7 +1220,7 @@ METAL_FUNC void qmm_t_expert_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1230,7 +1230,7 @@ METAL_FUNC void qmm_t_expert_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1348,7 +1348,7 @@ METAL_FUNC void qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1358,7 +1358,7 @@ METAL_FUNC void qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1474,7 +1474,7 @@ METAL_FUNC void qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1485,7 +1485,7 @@ METAL_FUNC void qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BK, BN, @@ -2118,7 +2118,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; @@ -2713,7 +2713,7 @@ template < return; } - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = BK + 16 / sizeof(T); threadgroup T Xs[BM * BK_padded]; @@ -2798,7 +2798,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2817,7 +2817,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, @@ -2935,7 +2935,7 @@ template constexpr float eps = 1e-7; constexpr int simd_size = 32; constexpr float n_bins = (1 << bits) - 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_reduce = group_size / simd_size; constexpr int writes_per_reduce = pack_factor / values_per_reduce; @@ -3037,7 +3037,7 @@ template device T* out [[buffer(3)]], uint2 index [[thread_position_in_grid]], uint2 grid_dim [[threads_per_grid]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); size_t offset = index.x + grid_dim.x * size_t(index.y); diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 68f0ee2dd5..60893f0f0e 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -29,7 +29,7 @@ inline constexpr short get_bytes_per_pack() { } template -inline U load_vector(const device T* x, thread U* x_thread) { +inline U nax_load_vector(const device T* x, thread U* x_thread) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -108,7 +108,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { } template -inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { +inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -579,7 +579,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedNAXBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -591,7 +591,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -612,7 +612,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -706,7 +706,7 @@ template < short reduction_dim, short tgp_size, short bits> -struct QuantizedBlockLoader< +struct AffineQuantizedNAXBlockLoader< T, BROWS, BCOLS, @@ -725,7 +725,7 @@ struct QuantizedBlockLoader< bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -751,7 +751,7 @@ struct QuantizedBlockLoader< const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -959,12 +959,12 @@ METAL_FUNC void qmm_t_nax_tgp_impl( (void)lid; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BN, BK, @@ -1103,12 +1103,12 @@ METAL_FUNC void qmm_n_nax_tgp_impl( static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BK, BN, @@ -1484,12 +1484,12 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, From adbc349ba623be417993ec083afbb11d07ec42a9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:49:37 -0700 Subject: [PATCH 08/44] Fix legacy quantized partial-tile bounds --- fork.yaml | 5 +++-- mlx/backend/metal/kernels/fp_quantized.h | 19 +++++++++--------- mlx/backend/metal/kernels/quantized.h | 25 ++++++++++++------------ 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/fork.yaml b/fork.yaml index 08fd50e876..265d81018f 100644 --- a/fork.yaml +++ b/fork.yaml @@ -247,11 +247,12 @@ def: - "mlx/distributed/primitives.h" - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" - - title: "Quantized NAX tile bounds and distinct loader symbols" + - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders - check row and packed-column bounds before reading weights or scales, then + check row and packed-column bounds on both legacy and NAX paths before + reading weights or scales, then zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index 579ddf95ac..35dc88961f 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -221,14 +221,7 @@ struct FPQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -237,8 +230,14 @@ struct FPQuantizedBlockLoader { T scale = dequantize_scale(*scales); for (int i = 0; i < n_reads; i++) { - dequantize( - src[i * bytes_per_pack], scale, dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + src[i * bytes_per_pack], scale, dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index d5a2953b32..ad347e113f 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -651,14 +651,7 @@ struct AffineQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -668,11 +661,17 @@ struct AffineQuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } From 9e22e1998a3b6f7f6f4ad58dc2038ecf9f4d0cb9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:22:02 -0700 Subject: [PATCH 09/44] Enforce optional Metal backing caps and preserve CPU quantized sums --- fork.yaml | 21 + mlx/backend/common/process_allocation_cap.h | 192 +++++++ mlx/backend/cpu/quantized.cpp | 18 +- mlx/backend/cuda/allocator.cpp | 9 + mlx/backend/metal/allocator.cpp | 237 ++++++++- mlx/backend/metal/allocator.h | 10 + mlx/backend/metal/resident.cpp | 16 +- mlx/backend/no_gpu/allocator.cpp | 9 + mlx/memory.h | 6 + python/tests/test_quantized.py | 74 +++ tests/allocator_tests.cpp | 2 +- tests/standalone/process_allocation_cap.cpp | 204 ++++++++ .../process_allocation_cap_metal.cpp | 494 ++++++++++++++++++ 13 files changed, 1274 insertions(+), 18 deletions(-) create mode 100644 mlx/backend/common/process_allocation_cap.h create mode 100644 tests/standalone/process_allocation_cap.cpp create mode 100644 tests/standalone/process_allocation_cap_metal.cpp diff --git a/fork.yaml b/fork.yaml index 265d81018f..ea5756c9b8 100644 --- a/fork.yaml +++ b/fork.yaml @@ -106,12 +106,22 @@ def: overflow-checked) cache-reuse limit shared with `BufferCache`. Metal, CPU and CUDA allocators implement the same interface; the allocator's own behaviour stays the authority. These describe allocator accounting, not process RSS. (PR #15) + The public process-allocation cap API adds install-once Metal backing enforcement. + Reservations include pending allocations and the fixed heap. Owned page-aligned VM + regions use Metal no-copy buffers; credit returns after the deallocator unmaps them. + Foreign wrappers retain caller ownership. CPU/CUDA reject this optional API; soft + memory limits are unchanged. Residency insertion rolls back failed registration before + callers release buffers, including ordinary uncapped allocations. Standalone CPU and + real-Metal tests cover delayed release, churn, and injected construction failures. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" + - "mlx/backend/common/process_allocation_cap.h" + - "tests/standalone/process_allocation_cap*.cpp" - "mlx/backend/common/buffer_cache.h" - "mlx/backend/metal/allocator.h" - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/metal/resident.cpp" - "mlx/backend/cuda/allocator.h" - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" @@ -268,6 +278,17 @@ def: - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" + - title: "CPU quantized accumulation precision" + description: | + Scalar affine, MXFP4, MXFP8 and NVFP4 matrix products accumulate in FP32 + and convert once when writing each output. Both matrix orientations and + the FP group sum preserve partial sums instead of rounding every addition + to BF16 or FP16. Exact CPU regressions compare constant products with + dequantized matmul, including sorted and unsorted gathered affine paths. + Quantization, packing, indexing and Metal kernels remain unchanged. + globs: + - "mlx/backend/cpu/quantized.cpp" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official diff --git a/mlx/backend/common/process_allocation_cap.h b/mlx/backend/common/process_allocation_cap.h new file mode 100644 index 0000000000..d92723b73e --- /dev/null +++ b/mlx/backend/common/process_allocation_cap.h @@ -0,0 +1,192 @@ +// Copyright © 2026 Eigen Labs. +#pragma once + +#include +#include +#include +#include +#include + +namespace mlx::core::allocator { + +struct ProcessAllocationCapSnapshot { + bool installed{false}; + size_t limit_bytes{0}; + size_t heap_bytes{0}; + size_t live_bytes{0}; + size_t cached_bytes{0}; + size_t pending_bytes{0}; + size_t unreclaimed_bytes{0}; + size_t charged_bytes{0}; + size_t peak_bytes{0}; +}; + +// Reference release alone cannot refund backing credit. +class ProcessAllocationCap { + public: + void install(size_t limit, size_t heap) { + std::lock_guard lock(mutex_); + if (state_.installed || !limit || heap > limit) { + throw std::invalid_argument("allocation cap install refused"); + } + state_.installed = true; + state_.limit_bytes = limit; + state_.heap_bytes = heap; + state_.charged_bytes = state_.peak_bytes = heap; + } + + void reserve(size_t bytes) { + std::lock_guard lock(mutex_); + if (!state_.installed || + bytes > state_.limit_bytes - state_.charged_bytes) { + throw std::runtime_error("native allocation cap exceeded"); + } + state_.pending_bytes += bytes; + state_.charged_bytes += bytes; + if (state_.charged_bytes > state_.peak_bytes) { + state_.peak_bytes = state_.charged_bytes; + } + } + + // Only a reservation for which no backing was acquired can be rolled back. + void failed_before_acquisition(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.pending_bytes, bytes); + state_.pending_bytes -= bytes; + state_.charged_bytes -= bytes; + } + void acquired(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.pending_bytes, state_.live_bytes, bytes); + } + void cache(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.live_bytes, state_.cached_bytes, bytes); + } + void reuse(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.cached_bytes, state_.live_bytes, bytes); + } + void relinquish(size_t bytes, bool cached = false) { + std::lock_guard lock(mutex_); + transfer( + cached ? state_.cached_bytes : state_.live_bytes, + state_.unreclaimed_bytes, + bytes); + } + void destroyed(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.unreclaimed_bytes, bytes); + state_.unreclaimed_bytes -= bytes; + state_.charged_bytes -= bytes; + } + ProcessAllocationCapSnapshot snapshot() const { + std::lock_guard lock(mutex_); + return state_; + } + + private: + static void require(size_t available, size_t bytes) { + if (bytes > available) { + throw std::logic_error("allocation cap ledger mismatch"); + } + } + static void transfer(size_t& from, size_t& to, size_t bytes) { + require(from, bytes); + if (bytes > std::numeric_limits::max() - to) { + throw std::overflow_error("allocation cap ledger overflow"); + } + from -= bytes; + to += bytes; + } + mutable std::mutex mutex_; + ProcessAllocationCapSnapshot state_; +}; + +// Shared by allocator bookkeeping and the Metal deallocator block. The callback +// never takes the allocator mutex. Release must finish before credit is +// returned. +class ProcessBackingLease { + public: + using Release = bool (*)(void*, size_t); + ProcessBackingLease(std::shared_ptr cap, size_t bytes) + : cap_(std::move(cap)), bytes_(bytes) { + cap_->reserve(bytes_); + } + ~ProcessBackingLease() { + finish(); + } + void attach(void* pointer, Release release) noexcept { + std::lock_guard lock(mutex_); + pointer_ = pointer; + release_ = release; + } + void acquired() { + std::lock_guard lock(mutex_); + if (state_ != State::pending) { + throw std::logic_error("backing already retired"); + } + cap_->acquired(bytes_); + state_ = State::live; + } + void cache() { + std::lock_guard lock(mutex_); + if (state_ != State::live) { + throw std::logic_error("backing cache mismatch"); + } + cap_->cache(bytes_); + state_ = State::cached; + } + void reuse() { + std::lock_guard lock(mutex_); + if (state_ != State::cached) { + throw std::logic_error("backing reuse mismatch"); + } + cap_->reuse(bytes_); + state_ = State::live; + } + void retire() { + std::lock_guard lock(mutex_); + if (state_ != State::live && state_ != State::cached) { + throw std::logic_error("backing retirement mismatch"); + } + cap_->relinquish(bytes_, state_ == State::cached); + state_ = State::retired; + } + void finish() noexcept { + std::lock_guard lock(mutex_); + if (state_ == State::finished) { + return; + } + // Foreign wrappers have no release function: their caller retains + // ownership. + const bool released = !release_ || release_(pointer_, bytes_); + if (state_ == State::pending && released) { + cap_->failed_before_acquisition(bytes_); + } else { + if (state_ == State::pending) { + cap_->acquired(bytes_); + } + if (state_ != State::retired) { + cap_->relinquish(bytes_, state_ == State::cached); + } + if (released) { + cap_->destroyed(bytes_); + } + } + // A failed backing release is permanently charged; it cannot be retried + // after ownership has been relinquished to a deallocator callback. + state_ = State::finished; + } + + private: + enum class State { pending, live, cached, retired, finished }; + std::shared_ptr cap_; + size_t bytes_; + void* pointer_{nullptr}; + Release release_{nullptr}; + State state_{State::pending}; + std::mutex mutex_; +}; + +} // namespace mlx::core::allocator diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 15e00cd913..30b11c87d6 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -108,15 +108,16 @@ void _qmm( constexpr int bytes_per_pack = get_bytes_per_pack(bits); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const T* scales_local = scales; const T* biases_local = biases; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -147,6 +148,7 @@ void _qmm( } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -174,7 +176,7 @@ void _qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = *scales_local++; T bias = *biases_local++; @@ -458,14 +460,15 @@ void fp_qmm( constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const uint8_t* scales_local = scales; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -484,6 +487,7 @@ void fp_qmm( } } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -506,11 +510,11 @@ void fp_qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = dequantize_scale(*scales_local++); - T gsum = 0; + float gsum = 0; for (int kw = 0; kw < packs_in_group; kw++) { if constexpr (bits == 4) { gsum += (*x_local++) * static_cast(FP4_LUT[w_local[0] & 0xf]); diff --git a/mlx/backend/cuda/allocator.cpp b/mlx/backend/cuda/allocator.cpp index e483317845..b29cc3a2b3 100644 --- a/mlx/backend/cuda/allocator.cpp +++ b/mlx/backend/cuda/allocator.cpp @@ -440,6 +440,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return cu::allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return cu::allocator().set_memory_limit(limit); } diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9b80840a18..97fc684aca 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -6,6 +6,7 @@ #include "mlx/memory.h" #include +#include #include #include #include @@ -52,6 +53,7 @@ MetalAllocator::MetalAllocator(Device& d) vm_page_size, [](MTL::Buffer* buf) { return buf->length(); }, [this](MTL::Buffer* buf) { + relinquish_capped(buf, true); if (!buf->heap()) { residency_sets_.erase(buf); } @@ -136,6 +138,125 @@ size_t MetalAllocator::set_wired_limit(size_t limit) { return limit; }; +void MetalAllocator::install_process_allocation_cap(size_t bytes) { + std::unique_lock lock(mutex_); + if (buffer_allocation_attempted_) { + throw std::invalid_argument( + "allocation cap requires a pristine buffer allocator"); + } + cap_->install(bytes, heap_ ? heap_->size() : 0); + cap_installed_ = true; +} + +ProcessAllocationCapSnapshot +MetalAllocator::get_process_allocation_cap_snapshot() { + return cap_->snapshot(); +} + +void MetalAllocator::relinquish_capped(MTL::Buffer* buffer, bool cached) { + if (!cap_installed_) { + return; + } + auto entry = capped_buffers_.find(buffer); + if (entry == capped_buffers_.end()) { + throw std::logic_error("untracked capped buffer"); + } + if (entry->second) { + entry->second->retire(); + } + capped_buffers_.erase(entry); +} + +Buffer MetalAllocator::malloc_capped( + size_t size, + std::unique_lock& lock) { + if (auto* cached = buffer_cache_.reuse_from_cache(size)) { + if (auto lease = capped_buffers_.at(cached)) { + lease->reuse(); + } + active_memory_ += cached->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{cached}; + } + // Trim idle backing before refusing a new shape. Actual callbacks, not cache + // eviction, return credit; externally retained buffers remain charged. + auto snapshot = cap_->snapshot(); + const auto charge = allocator::round_allocation_size(size, vm_page_size); + if (charge > device_->maxBufferLength()) { + throw std::invalid_argument( + "page-aligned backing exceeds Metal buffer limit"); + } + if (charge > snapshot.limit_bytes - snapshot.charged_bytes || + num_resources_ >= resource_limit_ || + buffer_cache_.cache_size() > max_pool_size_) { + num_resources_ -= buffer_cache_.clear(); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + MTL::Buffer* buffer = nullptr; + std::shared_ptr lease; + if (size < small_size_ && heap_) { + buffer = heap_->newBuffer(size, resource_options); + } + if (!buffer) { + // Reserve before releasing allocator lock, including in-flight allocations. + lease = std::make_shared(cap_, charge); + ++num_resources_; + lock.unlock(); + try { + void* pages = mmap( + nullptr, + charge, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + if (pages == MAP_FAILED) { + throw std::bad_alloc(); + } + lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + buffer = device_->newBuffer( + pages, charge, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + if (!buffer) { + throw std::runtime_error("Metal no-copy allocation failed"); + } + lease->acquired(); + } catch (...) { + if (buffer) { + buffer->release(); + } else { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); + } else { + ++num_resources_; + } + try { + capped_buffers_.emplace(buffer, lease); + if (!buffer->heap()) { + residency_sets_.insert(buffer); + } + } catch (...) { + capped_buffers_.erase(buffer); + if (lease) { + lease->retire(); + } + --num_resources_; + buffer->release(); + throw; + } + active_memory_ += buffer->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{buffer}; +} + Buffer MetalAllocator::malloc(size_t size) { // Metal doesn't like empty buffers if (size == 0) { @@ -159,6 +280,10 @@ Buffer MetalAllocator::malloc(size_t size) { // Try the cache std::unique_lock lk(mutex_); + buffer_allocation_attempted_ = true; + if (cap_installed_) { + return malloc_capped(size, lk); + } MTL::Buffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { size_t mem_required = get_active_memory() + get_cache_memory() + size; @@ -211,10 +336,16 @@ Buffer MetalAllocator::malloc(size_t size) { throw std::runtime_error(msg.str()); } lk.lock(); - num_resources_++; - if (!buf->heap()) { - residency_sets_.insert(buf); + try { + if (!buf->heap()) { + residency_sets_.insert(buf); + } + } catch (...) { + lk.unlock(); + buf->release(); + throw; } + num_resources_++; } active_memory_ += buf->length(); @@ -243,7 +374,13 @@ void MetalAllocator::free(Buffer buffer) { active_memory_ -= buf->length(); if (get_cache_memory() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); + if (cap_installed_) { + if (auto lease = capped_buffers_.at(buf)) { + lease->cache(); + } + } } else { + relinquish_capped(buf, false); num_resources_--; if (!buf->heap()) { residency_sets_.erase(buf); @@ -259,15 +396,91 @@ size_t MetalAllocator::size(Buffer buffer) const { } Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { - auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + std::unique_lock lock(mutex_); + buffer_allocation_attempted_ = true; + if (!cap_installed_) { + lock.unlock(); + auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + if (!buf) { + return Buffer{nullptr}; + } + lock.lock(); + try { + residency_sets_.insert(buf); + } catch (...) { + lock.unlock(); + buf->release(); + throw; + } + active_memory_ += buf->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + num_resources_++; + return Buffer{static_cast(buf)}; + } + std::shared_ptr lease; + if (cap_installed_) { + if (!size || size % vm_page_size || + reinterpret_cast(ptr) % vm_page_size || !ptr || + size > device_->maxBufferLength()) { + throw std::invalid_argument( + "capped foreign backing must be page aligned"); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + lease = std::make_shared(cap_, size); + } + ++num_resources_; + lock.unlock(); + MTL::Buffer* buf = nullptr; + try { + if (lease) { + // Charge wrapper lifetime; never free or assume ownership of caller + // pages. + buf = device_->newBuffer( + ptr, size, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + } else { + buf = device_->newBuffer(ptr, size, resource_options, nullptr); + } + if (buf && lease) { + lease->acquired(); + } + } catch (...) { + if (buf) { + buf->release(); + } else if (lease) { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); if (!buf) { - return Buffer{nullptr}; + if (lease) { + lease->finish(); + } + --num_resources_; + throw std::runtime_error("capped Metal no-copy wrapper allocation failed"); + } + try { + if (lease) { + capped_buffers_.emplace(buf, lease); + } + residency_sets_.insert(buf); + } catch (...) { + if (lease) { + capped_buffers_.erase(buf); + lease->retire(); + } + --num_resources_; + buf->release(); + throw; } - std::unique_lock lk(mutex_); - residency_sets_.insert(buf); active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); - num_resources_++; return Buffer{static_cast(buf)}; } @@ -278,6 +491,7 @@ void MetalAllocator::release(Buffer buffer) { } std::unique_lock lk(mutex_); active_memory_ -= buf->length(); + relinquish_capped(buf, false); num_resources_--; residency_sets_.erase(buf); lk.unlock(); @@ -308,6 +522,13 @@ size_t get_allocation_size_upper_bound(size_t size) { return result; } +void install_process_allocation_cap(size_t bytes) { + metal::allocator().install_process_allocation_cap(bytes); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + return metal::allocator().get_process_allocation_cap_snapshot(); +} + size_t set_cache_limit(size_t limit) { return metal::allocator().set_cache_limit(limit); } diff --git a/mlx/backend/metal/allocator.h b/mlx/backend/metal/allocator.h index 623055e92c..b184944224 100644 --- a/mlx/backend/metal/allocator.h +++ b/mlx/backend/metal/allocator.h @@ -24,6 +24,8 @@ class MetalAllocator : public allocator::Allocator { virtual Buffer make_buffer(void* ptr, size_t size) override; virtual void release(Buffer buffer) override; + void install_process_allocation_cap(size_t bytes); + ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); MemorySnapshot get_memory_snapshot(); size_t get_active_memory() { return active_memory_; @@ -93,6 +95,14 @@ class MetalAllocator : public allocator::Allocator { static constexpr size_t resource_high_water_num_ = 9; static constexpr size_t resource_high_water_den_ = 10; + Buffer malloc_capped(size_t size, std::unique_lock& lock); + void relinquish_capped(MTL::Buffer* buffer, bool cached); + std::shared_ptr cap_{ + std::make_shared()}; + bool cap_installed_{false}; + bool buffer_allocation_attempted_{false}; + std::map> + capped_buffers_; std::mutex mutex_; }; diff --git a/mlx/backend/metal/resident.cpp b/mlx/backend/metal/resident.cpp index 2436993637..fede178a5a 100644 --- a/mlx/backend/metal/resident.cpp +++ b/mlx/backend/metal/resident.cpp @@ -150,8 +150,20 @@ void ResidencySets::insert(MTL::Allocation* buf) { if (total_wired_ + bytes > capacity_) { return; } - uint32_t idx = add_to_set_locked(buf, it->second); - sets_[idx].set->commit(); + try { + uint32_t idx = add_to_set_locked(buf, it->second); + sets_[idx].set->commit(); + } catch (...) { + // Registration must not leave a pointer to a buffer the caller will + // release. + if (it->second.set_id != kNoSet) { + const uint32_t idx = it->second.set_id; + remove_from_set_locked(buf, it->second); + sets_[idx].set->commit(); + } + buf_to_set_.erase(it); + throw; + } } void ResidencySets::erase(MTL::Allocation* buf) { diff --git a/mlx/backend/no_gpu/allocator.cpp b/mlx/backend/no_gpu/allocator.cpp index f766707bce..06f9bcd79d 100644 --- a/mlx/backend/no_gpu/allocator.cpp +++ b/mlx/backend/no_gpu/allocator.cpp @@ -213,6 +213,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return allocator::common_allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return allocator::common_allocator().set_memory_limit(limit); } diff --git a/mlx/memory.h b/mlx/memory.h index f2e7bf225f..d36201b51a 100644 --- a/mlx/memory.h +++ b/mlx/memory.h @@ -7,9 +7,15 @@ #include #include "mlx/api.h" +#include "mlx/backend/common/process_allocation_cap.h" namespace mlx::core { +using ProcessAllocationCapSnapshot = allocator::ProcessAllocationCapSnapshot; +// One-way, pristine-allocator installation. Not a whole-process/host limit. +MLX_API void install_process_allocation_cap(size_t bytes); +MLX_API ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); + struct MemorySnapshot { size_t active_memory; size_t cache_memory; diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index e5c81c3995..d860196acf 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1599,6 +1599,80 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y3, atol=tol)) self.assertTrue(mx.allclose(y1, y4, atol=tol)) + def test_cpu_quantized_accumulation_modes_and_orientations(self): + with mx.stream(mx.cpu): + for mode, dtype, transpose, k in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.bfloat16, mx.float16, mx.float32], + [False, True], + [96, 3072], + ): + with self.subTest(mode=mode, dtype=dtype, transpose=transpose, k=k): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + x = mx.full((1, k), 3, dtype=dtype) + weights = mx.full((32, k) if transpose else (k, 32), 2, dtype=dtype) + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 code 64 is exactly 2. + packed = ( + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 8), + 0x22222222, + dtype=mx.uint32, + ), + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 16), + 64, + dtype=mx.uint8, + ), + ) + else: + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + dequantized = mx.dequantize( + *packed, group_size=group_size, bits=bits, mode=mode + ) + reference = x @ (dequantized.T if transpose else dequantized) + expected = mx.full((1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + actual = mx.quantized_matmul( + x, + *packed, + transpose=transpose, + group_size=group_size, + bits=bits, + mode=mode, + ) + self.assertTrue(mx.array_equal(actual, expected)) + + def test_affine_qmm_cpu_low_precision_accumulation(self): + with mx.stream(mx.cpu): + for dtype, bits, k in product( + [mx.bfloat16, mx.float16, mx.float32], [3, 4, 6], [96, 128] + ): + with self.subTest(dtype=dtype, bits=bits, k=k): + x = mx.full((1, 1, k), 3, dtype=dtype) + weights = mx.full((1, 32, k), 2, dtype=dtype) + packed = mx.quantize(weights, group_size=32, bits=bits) + reference = x @ mx.swapaxes( + mx.dequantize(*packed, group_size=32, bits=bits), -1, -2 + ) + expected = mx.full((1, 1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + for sorted_indices in [False, True]: + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=mx.array([0], dtype=mx.uint32), + group_size=32, + bits=bits, + sorted_indices=sorted_indices, + ) + self.assertTrue(mx.array_equal(actual, expected)) + actual = mx.quantized_matmul(x, *packed, group_size=32, bits=bits) + self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") def test_gather_qmm_sorted_partial_tiles(self): diff --git a/tests/allocator_tests.cpp b/tests/allocator_tests.cpp index d5ff60525b..bab64689bc 100644 --- a/tests/allocator_tests.cpp +++ b/tests/allocator_tests.cpp @@ -182,7 +182,7 @@ TEST_CASE("test memory snapshot does not wait for stream work") { auto status = snapshot.wait_for(std::chrono::seconds(1)); release.set_value(); synchronize(stream); - snapshot.get(); + (void)snapshot.get(); CHECK_EQ(status, std::future_status::ready); } diff --git a/tests/standalone/process_allocation_cap.cpp b/tests/standalone/process_allocation_cap.cpp new file mode 100644 index 0000000000..1500baac9d --- /dev/null +++ b/tests/standalone/process_allocation_cap.cpp @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. +#include "mlx/backend/common/process_allocation_cap.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/backend/common/allocation_footprint.h" + +using namespace mlx::core::allocator; +using Cap = ProcessAllocationCap; +using Lease = ProcessBackingLease; + +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + assert(refused); +} +void invariant(const Cap& cap) { + auto s = cap.snapshot(); + assert( + s.charged_bytes == + s.heap_bytes + s.live_bytes + s.cached_bytes + s.pending_bytes + + s.unreclaimed_bytes); + assert(s.charged_bytes <= s.peak_bytes && s.peak_bytes <= s.limit_bytes); +} +std::atomic releases{0}; +bool unmap(void* p, size_t n) { + ++releases; + return munmap(p, n) == 0; +} + +using Callback = void (^)(); +Callback retainedCallback(std::shared_ptr lease) { + return Block_copy(^{ + lease->finish(); + }); +} + +int main() { + const size_t page = static_cast(getpagesize()); + { + Cap c; + refuses([&] { c.install(0, 0); }); + refuses([&] { c.install(3, 4); }); + assert(!c.snapshot().installed); + c.install(16, 4); + refuses([&] { c.install(32, 4); }); + c.reserve(12); + refuses([&] { c.reserve(1); }); + c.failed_before_acquisition(12); + assert(c.snapshot().charged_bytes == 4); + invariant(c); + Cap huge; + huge.install(SIZE_MAX, SIZE_MAX - 1); + huge.reserve(1); + refuses([&] { huge.reserve(SIZE_MAX); }); + huge.failed_before_acquisition(1); + invariant(huge); + refuses([&] { round_allocation_size(SIZE_MAX, page); }); + } + { + auto c = std::make_shared(); + c->install(4 * page, page); + // Real VM backing, real copied Blocks ABI; no Metal/device initialization. + for (int i = 0; i < 1000; ++i) { + auto lease = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + lease->attach(p, unmap); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->cache(); + lease->reuse(); + lease->retire(); + lease.reset(); + assert(c->snapshot().unreclaimed_bytes == page); + assert(c->snapshot().charged_bytes == 2 * page); + callback(); + callback(); // defensive idempotence; unmap exactly once + Block_release(callback); + assert(c->snapshot().charged_bytes == page); + invariant(*c); + } + assert( + releases == 1000); // Churn does not accumulate a fake high-water cap. + } + { + auto c = std::make_shared(); + c->install(page, 0); + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + refuses( + [&] { Lease next(c, 1); }); // retained Metal equivalent blocks refund + std::thread completion([&] { callback(); }); + completion.join(); + Block_release(callback); + Lease next(c, page); // delayed completion makes capacity reusable + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + { + Lease failed(c, page); + } // no VM acquired + assert(c->snapshot().charged_bytes == 0); + auto failed = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + failed->attach(p, unmap); + failed->finish(); // Metal constructor returned nil after VM acquisition + failed.reset(); + assert(c->snapshot().charged_bytes == 0 && releases == 1001); + Lease quarantine(c, page); + quarantine.attach(nullptr, [](void*, size_t) { return false; }); + quarantine.acquired(); + quarantine.retire(); + quarantine.finish(); + assert(c->snapshot().unreclaimed_bytes == page); + refuses([&] { Lease next(c, 1); }); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + // Foreign pages stay caller-owned even after callback and ledger refund. + auto* p = static_cast(mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + assert(p != MAP_FAILED); + p[0] = 42; + { + Lease wrapper(c, page); + wrapper.acquired(); + wrapper.retire(); + wrapper.finish(); + } + assert(p[0] == 42 && c->snapshot().charged_bytes == 0); + assert(munmap(p, page) == 0); + } + { + auto c = std::make_shared(); + c->install(1, 0); + std::atomic arrived{0}, successes{0}; + std::atomic release{false}; + std::vector threads; + for (int i = 0; i < 2; ++i) { + threads.emplace_back([&] { + std::shared_ptr lease; + try { + lease = std::make_shared(c, 1); + ++successes; + } catch (...) { + } + ++arrived; + while (!release) { + std::this_thread::yield(); + } + }); + } + while (arrived != 2) { + std::this_thread::yield(); + } + assert(successes == 1 && c->snapshot().pending_bytes == 1); + release = true; + for (auto& t : threads) { + t.join(); + } + assert(c->snapshot().charged_bytes == 0); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + std::weak_ptr weak = c; + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + c.reset(); + assert(!weak.expired()); + callback(); + Block_release(callback); + assert(weak.expired()); // callback owns ledger, not an allocator stack + // reference + } + std::cout + << "PASS: install/overflow, 1000 VM churn cycles, delayed copied block, " + "failure rollback/quarantine, foreign ownership, concurrent reserve, ledger lifetime\n"; +} diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp new file mode 100644 index 0000000000..9ebd9340b5 --- /dev/null +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -0,0 +1,494 @@ +// Copyright © 2026 Eigen Labs. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/allocator.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" + +using namespace mlx::core; +namespace a = mlx::core::allocator; +void require(bool value, const char* what) { + if (!value) { + throw std::runtime_error(what); + } +} +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + require(refused, "required refusal did not occur"); +} +auto snapshot() { + return get_process_allocation_cap_snapshot(); +} +void settled(size_t expected) { + for (int i = 0; i < 200 && snapshot().charged_bytes != expected; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require( + snapshot().charged_bytes == expected, "callback credit did not settle"); +} + +// Process-local Metal API interception; no production failure switches. +IMP original_no_copy = nullptr; +IMP original_allocate = nullptr; +IMP original_residency = nullptr; +MTL::Buffer* retained_failure_buffer = nullptr; +bool reject_no_copy = false; +MTL::Buffer* intercept_no_copy( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + if (reject_no_copy) { + reject_no_copy = false; + return nullptr; + } + auto fn = reinterpret_cast( + original_no_copy); + auto* b = fn(self, selector, p, n, opts, cleanup); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::Buffer* intercept_allocate( + id self, + SEL selector, + NS::UInteger n, + MTL::ResourceOptions opts) { + auto fn = reinterpret_cast< + MTL::Buffer* (*)(id, SEL, NS::UInteger, MTL::ResourceOptions)>( + original_allocate); + auto* b = fn(self, selector, n, opts); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::ResidencySet* +fail_residency(id, SEL, MTL::ResidencySetDescriptor*, NS::Error**) { + throw std::bad_alloc(); // insert has already added its map entry +} +struct Intercept { + Method method; + IMP previous; + Intercept(MTL::Device* device, const char* selector, IMP replacement) + : method(class_getInstanceMethod( + object_getClass(reinterpret_cast(device)), + sel_registerName(selector))), + previous(nullptr) { + require(method != nullptr, "Metal interception selector missing"); + previous = method_setImplementation(method, replacement); + } + ~Intercept() { + method_setImplementation(method, previous); + } +}; + +struct PendingMetalConstruction { + std::mutex mutex; + std::condition_variable changed; + size_t entered{0}; + bool complete{false}; + std::array retained{nullptr, nullptr}; + IMP original{nullptr}; +}; +PendingMetalConstruction* pending_construction = nullptr; +MTL::Buffer* intercept_pending( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + auto& state = *pending_construction; + auto fn = reinterpret_cast( + state.original); + // Construct real Metal buffers before holding their return to the allocator. + auto* buffer = fn(self, selector, p, n, opts, cleanup); + std::unique_lock lock(state.mutex); + const auto index = state.entered++; + if (index < state.retained.size() && buffer) { + buffer->retain(); + state.retained[index] = buffer; + } + state.changed.notify_all(); + if (index < state.retained.size()) { + state.changed.wait(lock, [&] { return state.complete; }); + } + return buffer; +} +void concurrent_case(size_t page) { + auto& device = metal::device(Device::gpu); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + const auto chunk = (cap - heap) / 2; + require( + chunk % page == 0 && chunk * 2 + heap == cap, + "nonintegral test envelope"); + PendingMetalConstruction state; + pending_construction = &state; + std::array buffers{a::Buffer(nullptr), a::Buffer(nullptr)}; + std::array errors; + bool both_pending = false, contender_refused = false; + ProcessAllocationCapSnapshot pending_snapshot; + size_t actual_bytes = 0; + a::Buffer contender(nullptr); + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_pending)); + state.original = hook.previous; + std::array workers; + for (size_t i = 0; i < workers.size(); ++i) { + workers[i] = std::thread([&, i] { + try { + buffers[i] = a::malloc(chunk); + } catch (...) { + errors[i] = std::current_exception(); + } + }); + } + { + std::unique_lock lock(state.mutex); + both_pending = state.changed.wait_for( + lock, std::chrono::seconds(5), [&] { return state.entered == 2; }); + if (both_pending && state.retained[0] && state.retained[1]) { + actual_bytes = + state.retained[0]->length() + state.retained[1]->length(); + } + } + pending_snapshot = snapshot(); + if (both_pending) { + try { + contender = a::malloc(page); + } catch (const std::exception&) { + contender_refused = true; + } + } + { + std::lock_guard lock(state.mutex); + state.complete = true; + } + state.changed.notify_all(); + for (auto& worker : workers) { + worker.join(); + } + } + pending_construction = nullptr; + require( + both_pending, + "allocator did not allow two real in-flight Metal allocations"); + require(!errors[0] && !errors[1], "real Metal construction failed"); + require(actual_bytes + heap == cap, "unexpected actual Metal backing total"); + require( + pending_snapshot.pending_bytes == 2 * chunk && + pending_snapshot.charged_bytes == cap && + pending_snapshot.live_bytes == 0, + "in-flight Metal backing was not reserved before completion"); + require( + contender_refused && !contender.ptr() && state.entered == 2, + "contender reached Metal despite exhausted pending budget"); + require( + snapshot().peak_bytes == cap && snapshot().pending_bytes == 0 && + snapshot().live_bytes == 2 * chunk, + "pending-to-live transfer changed cap charge"); + for (auto buffer : buffers) { + a::free(buffer); + } + clear_cache(); + require( + snapshot().unreclaimed_bytes == 2 * chunk && + snapshot().charged_bytes == cap, + "allocator release refunded externally retained Metal backing"); + refuses([&] { a::malloc(page); }); + state.retained[0]->release(); + settled(heap + chunk); + auto recovered = a::malloc(chunk); + require( + snapshot().charged_bytes == cap && snapshot().peak_bytes == cap, + "callback recovery failed exact-cap replacement"); + a::free(recovered); + clear_cache(); + settled(heap + chunk); + state.retained[1]->release(); + settled(heap); + require( + snapshot().pending_bytes == 0 && snapshot().unreclaimed_bytes == 0, + "concurrent allocation left stranded charges"); +} +void failure_case(const std::string& mode, size_t page) { + const bool capped = mode.find("ordinary") == std::string::npos; + const bool foreign = mode.find("foreign") != std::string::npos; + auto& device = metal::device(Device::gpu); + auto& sets = device.residency_sets(); + (void)snapshot(); // initialize allocator and its fixed heap + if (capped) { + install_process_allocation_cap(8 << 20); + } + const auto baseline = capped ? snapshot().charged_bytes : 0; + set_cache_limit(0); + if (mode == "nil-foreign") { + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(p != MAP_FAILED, "foreign map failed"); + int deleter_calls = 0; + bool threw = false; + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = hook.previous; + reject_no_copy = true; + try { + array foreign_array( + p, {static_cast(page / sizeof(float))}, float32, [&](void*) { + ++deleter_calls; + }); + } catch (const std::exception&) { + threw = true; + } + } + require(munmap(p, page) == 0, "caller unmap failed"); + require(threw, "nil wrapper silently copied instead of throwing"); + require(deleter_calls == 0, "failed wrapper invoked caller deleter"); + settled(baseline); + return; + } + set_wired_limit(8 << 20); + sets.set_max_bytes_per_set(page); + const auto wired = sets.wired_size(); + const auto resources = get_num_resources(); + const auto active = get_active_memory(); + void* foreign_pages = nullptr; + if (foreign) { + foreign_pages = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(foreign_pages != MAP_FAILED, "foreign map failed"); + } + { + Intercept no_copy( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = no_copy.previous; + Intercept allocated( + device.mtl_device(), + "newBufferWithLength:options:", + reinterpret_cast(intercept_allocate)); + original_allocate = allocated.previous; + Intercept registration( + device.mtl_device(), + "newResidencySetWithDescriptor:error:", + reinterpret_cast(fail_residency)); + original_residency = registration.previous; + refuses([&] { + if (foreign) { + (void)a::make_buffer(foreign_pages, page); + } else { + (void)a::malloc(page); + } + }); + } + require( + retained_failure_buffer != nullptr, + "failure did not reach allocated buffer"); + // Keep the object alive to diagnose stale registration without dereferencing + // freed memory. On the broken path resize wires this failed allocation. + set_wired_limit((8 << 20) + page); + require( + sets.wired_size() == wired, + "failed insert left a tracked Metal allocation"); + require( + get_num_resources() == resources && get_active_memory() == active, + "failed registration changed allocator counters"); + if (capped) { + require( + snapshot().charged_bytes == baseline + page, + "retained failure refunded early"); + } + require( + retained_failure_buffer->retainCount() == 1, + "allocator leaked failed buffer reference"); + retained_failure_buffer->release(); + retained_failure_buffer = nullptr; + if (capped) { + settled(baseline); + } + if (foreign) { + require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); + } +} +int main(int argc, char** argv) { + try { + require(argc == 2, "one fresh-process case required"); + const std::string mode = argv[1]; + const size_t page = static_cast(getpagesize()); + if (mode == "concurrent") { + concurrent_case(page); + } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { + failure_case(mode, page); + } else if (mode == "late") { + auto b = a::malloc(page); + a::free(b); + clear_cache(); + refuses([] { install_process_allocation_cap(8 << 20); }); + require(!snapshot().installed, "late install mutated state"); + } else { + // The allocator's fixed heap is created when queried, before + // installation. + require(!snapshot().installed, "process already capped"); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + const auto baseline = snapshot(); + const auto heap = baseline.heap_bytes; + require( + heap > 0 && baseline.charged_bytes == heap, + "existing heap not charged"); + require(baseline.limit_bytes == cap, "wrong cap"); + if (mode == "install") { + refuses([&] { install_process_allocation_cap(cap); }); + refuses([&] { install_process_allocation_cap(cap + page); }); + require(snapshot().limit_bytes == cap, "limit changed"); + refuses([] { a::malloc(SIZE_MAX); }); + require( + snapshot().charged_bytes == heap, "overflow leaked reservation"); + auto exact = a::malloc(cap - heap); + require(snapshot().charged_bytes == cap, "exact fill mismatch"); + refuses([&] { a::malloc(page); }); + a::free(exact); + clear_cache(); + settled(heap); + } else if (mode == "retained") { + auto b = a::malloc(cap - heap); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::free(b); + clear_cache(); + require( + snapshot().unreclaimed_bytes == cap - heap, + "release refunded early"); + require(snapshot().charged_bytes == cap, "extra reference lost charge"); + refuses([&] { a::malloc(page); }); + metal->release(); + settled(heap); + auto replacement = a::malloc(cap - heap); + a::free(replacement); + clear_cache(); + settled(heap); + } else if (mode == "churn") { + auto tiny = a::malloc(8); + require( + static_cast(tiny.ptr())->heap() != nullptr, + "fixed heap unused"); + require(snapshot().charged_bytes == heap, "heap double charged"); + a::free(tiny); + clear_cache(); + for (size_t i = 0; i < 1000; ++i) { + const auto size = page * (1 + i % 31); + auto b = a::malloc(size); + const auto bytes = snapshot().charged_bytes; + auto pointer = b.ptr(); + a::free(b); + require( + snapshot().cached_bytes > 0 && snapshot().charged_bytes == bytes, + "cache transfer refunded credit"); + auto reused = a::malloc(size); + require( + reused.ptr() == pointer && snapshot().charged_bytes == bytes, + "cache reuse allocated new backing"); + a::free(reused); + clear_cache(); + settled(heap); + } + require(snapshot().peak_bytes < cap, "churn accumulated backing"); + } else if (mode == "foreign") { + void* p = mmap( + nullptr, + page, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + require(p != MAP_FAILED, "foreign map failed"); + static_cast(p)[0] = 42; + auto b = a::make_buffer(p, page); + require(b.ptr() != nullptr, "foreign wrapper failed"); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::release(b); + require( + snapshot().charged_bytes == heap + page, + "foreign wrapper refunded early"); + metal->release(); + settled(heap); + require( + static_cast(p)[0] == 42, + "caller pages invalidated"); + refuses([&] { a::make_buffer(static_cast(p) + 1, page); }); + require(munmap(p, page) == 0, "caller unmap failed"); + } else if (mode == "gpu") { + { + // Real native graph roots stay owned through GPU evaluation and + // readback. + auto input = arange(1024, float32, Device::gpu); + auto output = + add(multiply(input, array(2.0f), Device::gpu), + array(3.0f), + Device::gpu); + async_eval(output); + synchronize(default_stream(Device::gpu)); + for (int i = 0; i < 1024; ++i) { + require( + output.data()[i] == i * 2.0f + 3.0f, + "GPU value mismatch"); + } + require(snapshot().live_bytes > 0, "evaluated roots uncharged"); + } + synchronize(default_stream(Device::gpu)); + clear_cache(); + settled(heap); + } else { + throw std::runtime_error("unknown case"); + } + require(snapshot().pending_bytes == 0, "pending reservation leaked"); + require(snapshot().charged_bytes <= cap, "cap exceeded"); + } + std::cout << "PASS " << mode << '\n'; + return 0; + } catch (const std::exception& e) { + std::cerr << "FAIL " << e.what() << '\n'; + return 1; + } +} From 4d913204912559099eff856cd56efdcc9d305d5f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:40:16 -0700 Subject: [PATCH 10/44] Cover page-backed small buffers in detached Metal footprints Keep the allocation bound stable before and after process cap installation. Add real ordinary/capped boundary coverage without changing allocation, ownership, process-cap enforcement or the policy ABI. Document the bound. Implemented and validated with OpenAI Codex. --- docs/src/usage/unified_memory.rst | 18 +++++++++ fork.yaml | 7 ++++ mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 37 ++++++++++++++++++- 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 57f54bc23b..8541fec358 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -76,3 +76,21 @@ If we time the computation fully on the GPU, we get 2.8 milliseconds. But if we run the computation with ``d1=mx.gpu`` and ``d2=mx.cpu``, then the time is only about 1.4 milliseconds, about twice as fast. These times were measured on an M1 Max. + +Native allocation footprint bounds +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The C++ ``get_allocation_footprint_policy()`` returns a detached value that +bounds one allocator buffer, including alignment and permitted cache reuse. +On Metal, every positive request has a minimum footprint of one VM page +before the cache-reuse allowance is added. This covers the page-backed +fallback used by the optional process-allocation cap, including requests +smaller than one page. A policy captured before cap installation remains +valid afterward. Zero bytes still has a zero bound; arithmetic overflow is +refused. + +For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes +have an upper bound of 32,767 bytes. The bound is conservative; it is not a +measurement of the buffer's actual backing. The cap accounts for its fixed +heap separately. Per-buffer footprint bounds and the optional cap do not +replace whole-process memory budgets or OS headroom checks. diff --git a/fork.yaml b/fork.yaml index ea5756c9b8..1822834317 100644 --- a/fork.yaml +++ b/fork.yaml @@ -113,6 +113,12 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. + Metal footprint quotations apply a one-VM-page minimum to every positive request + before adding the cache-reuse allowance, covering capped page-backed fallback even + when the policy was captured before cap installation. Standalone fresh-process + ordinary and capped cases compare actual backing with detached and direct bounds + at subpage and page boundaries; zero and overflow remain explicit controls. + The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" @@ -126,6 +132,7 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 97fc684aca..037bedbd3d 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -511,7 +511,8 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; + // Capped fallback buffers use whole VM pages, including subpage requests. + return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index 9ebd9340b5..d50feb8b1b 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -350,12 +350,47 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } +void footprint_case(size_t page, bool capped) { + const auto quoted = get_allocation_footprint_policy(); + if (capped) { + install_process_allocation_cap(8 << 20); + } + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + for (auto requested : std::array{ + 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { + auto buffer = a::malloc(requested); + const auto actual = a::allocator().size(buffer); + size_t bound = 0; + const bool valid = quoted.upper_bound(requested, bound); + const auto direct = get_allocation_size_upper_bound(requested); + a::free(buffer); + clear_cache(); + settled(heap); + std::cout << "footprint requested=" << requested << " actual=" << actual + << " bound=" << bound << '\n'; + require( + valid && direct == bound, "pre-cap policy changed after installation"); + require( + actual >= requested && actual <= bound, + "actual backing exceeds quotation"); + require( + snapshot().pending_bytes == 0, "footprint check leaked reservation"); + } + require( + get_allocation_size_upper_bound(0) == 0, + "empty allocation bound changed"); + refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "concurrent") { + if (mode == "footprint" || mode == "footprint-ordinary") { + footprint_case(page, mode == "footprint"); + } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { failure_case(mode, page); From 54975cd06be07a51128e48754729a5620e04a325 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:05:56 -0700 Subject: [PATCH 11/44] Bound startup waits and preserve capped Metal backing ownership Prefault capped no-copy backing before handing it to Metal. Add a one-shot JACCL startup wait budget with C-facing group operations and failure cleanup tests. Validate custom Metal launch dimensions and bound the 1024-thread pipeline retry to the declared geometry. CPU policy, bridge, allocation-ledger and evaluator regressions pass. Native GPU and end-to-end qualification are tracked separately. --- docs/src/dev/custom_metal_kernels.rst | 14 + docs/src/usage/unified_memory.rst | 6 + fork.yaml | 26 ++ mlx/backend/metal/allocator.cpp | 7 + mlx/backend/metal/custom_kernel.cpp | 73 ++- mlx/distributed/distributed.cpp | 16 + mlx/distributed/distributed.h | 15 + mlx/distributed/distributed_impl.h | 9 + mlx/distributed/jaccl/jaccl.cpp | 8 + mlx/distributed/jaccl/lib/README.md | 38 ++ mlx/distributed/jaccl/lib/jaccl/group.h | 9 + mlx/distributed/jaccl/lib/jaccl/mesh.h | 8 + mlx/distributed/jaccl/lib/jaccl/mesh_impl.h | 12 +- .../jaccl/lib/jaccl/progress_guard.h | 37 +- mlx/distributed/jaccl/lib/jaccl/ring.h | 8 + mlx/distributed/jaccl/lib/jaccl/ring_impl.h | 20 +- .../jaccl/lib/jaccl/startup_wait_budget.h | 112 +++++ python/tests/test_metal_threadgroup_bounds.py | 80 ++++ tests/jaccl/CMakeLists.txt | 10 + tests/jaccl/startup_wait_budget_api_tests.cpp | 75 +++ .../jaccl/startup_wait_budget_group_tests.cpp | 114 +++++ tests/jaccl/startup_wait_budget_tests.cpp | 441 ++++++++++++++++++ .../process_allocation_cap_metal.cpp | 55 ++- 23 files changed, 1167 insertions(+), 26 deletions(-) create mode 100644 mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h create mode 100644 python/tests/test_metal_threadgroup_bounds.py create mode 100644 tests/jaccl/startup_wait_budget_api_tests.cpp create mode 100644 tests/jaccl/startup_wait_budget_group_tests.cpp create mode 100644 tests/jaccl/startup_wait_budget_tests.cpp diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index 6a9471fd51..f3ad478438 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -466,3 +466,17 @@ We can then implement the backwards pass as follows: There's an even larger speed up for the vjp: ``676.4ms -> 16.7ms => 40x speed up`` + +Threadgroup compiler capacity +----------------------------- + +Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, +a thread count within UINT32_MAX, and axes within the device limits. Invalid +geometry is refused before output allocation. A capable original pipeline is +kept. For a nonempty grid containing complete 1024-wide groups, exactly +``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +uses a distinct source/library identity and must itself support the full +threadgroup. Compile errors and remaining capacity failures propagate. This +does not change shader math, precision, group/grid axes, or guarantee that a +particular shader can compile at 1024. Other geometries receive no retry. diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 8541fec358..10d925c349 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -94,3 +94,9 @@ have an upper bound of 32,767 bytes. The bound is conservative; it is not a measurement of the buffer's actual backing. The cap accounts for its fixed heap separately. Per-buffer footprint bounds and the optional cap do not replace whole-process memory budgets or OS headroom checks. + +Capped no-copy backing is touched once per VM page from the CPU before it is +wrapped as a Metal buffer. This makes the process physical footprint include +pages first written by GPU work. It preserves the allocator cap and does not +replace load admission or operating-system memory headroom. The fresh-process +``gpu-footprint`` regression checks GPU-written backing; it requires Metal. diff --git a/fork.yaml b/fork.yaml index 1822834317..3641e4a7a2 100644 --- a/fork.yaml +++ b/fork.yaml @@ -118,6 +118,8 @@ def: when the policy was captured before cap installation. Standalone fresh-process ordinary and capped cases compare actual backing with detached and direct bounds at subpage and page boundaries; zero and overflow remain explicit controls. + Capped no-copy pages are first touched on the CPU so process physical + footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" @@ -194,6 +196,18 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" + - title: "Validated custom Metal threadgroups and bounded compiler retry" + description: | + Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond + the device limits before allocating outputs. A nonempty grid with complete + x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + declaration. The original capable pipeline is retained; retry compilation + and the selected pipeline's actual capacity remain authoritative. Other + geometries refuse without clamping. Shader math and dispatch axes do not change. + globs: + - "python/tests/test_metal_threadgroup_bounds.py" + - "docs/src/dev/custom_metal_kernels.rst" - title: "JACCL: zeroed send-frame tails, a progress guard and the advertised GID" description: | JACCL is the RDMA-over-Thunderbolt backend. Upstream has changed none of the three @@ -227,6 +241,12 @@ def: `mesh.cpp` and `ring.cpp` when they create the queues). MLX's `jaccl.cpp` registers the release hook each time it wraps a new JACCL group. + Startup readiness: a per-group one-shot budget of 1..900000 ms replaces the + idle limit until its fixed monotonic deadline. Progress never renews it. Begin/end + refuse running calls; callers drain queued work and serialize scheduling. End + restores the original idle policy and refuses expired or closed groups. The MLX + Group API forwards to JACCL only; unsupported backends refuse without fallback. + Advertised GID: `Connection::info()` advertises the IPv4-mapped GID of the port, but `queue_pair_rtr` sent from GID index 1 whatever the index of that GID. The connection now remembers the index where the advertised GID was found and sends from it; @@ -242,6 +262,12 @@ def: - "mlx/distributed/jaccl/lib/jaccl/mesh.cpp" - "mlx/distributed/jaccl/lib/jaccl/mesh_impl.h" - "mlx/distributed/jaccl/lib/jaccl/progress_guard.h" + - "mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h" + - "mlx/distributed/jaccl/lib/jaccl/group.h" + - "mlx/distributed/jaccl/lib/jaccl/mesh.h" + - "mlx/distributed/jaccl/lib/jaccl/ring.h" + - "mlx/distributed/distributed.h" + - "mlx/distributed/distributed_impl.h" - "mlx/distributed/jaccl/lib/jaccl/rdma.cpp" - "mlx/distributed/jaccl/lib/jaccl/rdma.h" - "mlx/distributed/jaccl/lib/jaccl/ring.cpp" diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 037bedbd3d..9db99ed59f 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -216,6 +216,13 @@ Buffer MetalAllocator::malloc_capped( throw std::bad_alloc(); } lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + // Fault every page from the CPU before wrapping it. Pages a no-copy + // buffer first receives through the GPU are not charged to this + // process's physical footprint, which hides the model from the OS + // memory-pressure accounting and from Activity Monitor. + for (size_t offset = 0; offset < charge; offset += vm_page_size) { + static_cast(pages)[offset] = 0; + } buffer = device_->newBuffer( pages, charge, resource_options, ^(void*, NS::UInteger) { lease->finish(); diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 65c33d2448..33f502a718 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -8,6 +8,8 @@ #include #include +#include +#include namespace mlx::core::fast { @@ -18,7 +20,30 @@ void CustomKernel::eval_gpu( (void)is_precompiled_; (void)shared_memory_; + const auto [tx, ty, tz] = threadgroup_; + const auto [gx, gy, gz] = grid_; + if (tx <= 0 || ty <= 0 || tz <= 0 || gx < 0 || gy < 0 || gz < 0) { + throw std::invalid_argument("Invalid custom kernel launch dimensions."); + } + size_t tg_size = 1; + for (auto dimension : {tx, ty, tz}) { + if (static_cast(dimension) > + std::numeric_limits::max() / tg_size) { + throw std::invalid_argument( + "Custom kernel threadgroup size exceeds 32 bits."); + } + tg_size *= static_cast(dimension); + } + auto& s = stream(); + auto& d = metal::device(s.device); + const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + if (static_cast(tx) > device_max.width || + static_cast(ty) > device_max.height || + static_cast(tz) > device_max.depth) { + throw std::invalid_argument( + "Custom kernel threadgroup exceeds device dimensions."); + } for (auto i : mutable_inputs_) { if (i < 0 || i >= inputs.size()) { @@ -56,13 +81,45 @@ void CustomKernel::eval_gpu( checked_inputs.push_back(check_input(in)); } - auto& d = metal::device(s.device); - std::string lib_name = fmt::format( "{}_{:x}_{}", name_, std::hash{}(source_), compile_options_); auto lib = d.get_library( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); + auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && + gx % tx == 0 && gy > 0 && gz > 0; + if (tg_size > max_tg_size && retry_geometry) { + const std::string declaration = "[[kernel]] void " + name_ + "("; + const auto position = source_.find(declaration); + if (position != std::string::npos && + source_.find(declaration, position + declaration.size()) == + std::string::npos) { + // Keep the dispatch geometry and give the compiler its required size. + auto constrained_source = source_; + constrained_source.insert( + position, + "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + + ")]] "); + auto constrained_name = + lib_name + "_required_tg_" + std::to_string(tg_size); + auto constrained_lib = d.get_library( + constrained_name, compile_options_, [&constrained_source] { + return metal::utils() + constrained_source; + }); + kernel = d.get_kernel(name_, constrained_lib); + max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + } + } + if (tg_size > max_tg_size) { + std::ostringstream msg; + msg << "Thread group size (" << tg_size << ") is greater than " + << " the maximum allowed threads per threadgroup (" << max_tg_size + << "). Kernel: " << name_ << "; threadgroup=(" << tx << "," << ty << "," + << tz << "); grid=(" << gx << "," << gy << "," << gz << ")."; + throw std::invalid_argument(msg.str()); + } + auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); int index = 0; @@ -96,18 +153,6 @@ void CustomKernel::eval_gpu( index++; } - const auto [tx, ty, tz] = threadgroup_; - auto tg_size = tx * ty * tz; - auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - if (tg_size > max_tg_size) { - std::ostringstream msg; - msg << "Thread group size (" << tg_size << ") is greater than " - << " the maximum allowed threads per threadgroup (" << max_tg_size - << ")."; - throw std::invalid_argument(msg.str()); - } - - const auto [gx, gy, gz] = grid_; MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); MTL::Size grid_dims = MTL::Size(gx, gy, gz); diff --git a/mlx/distributed/distributed.cpp b/mlx/distributed/distributed.cpp index d8fca8b160..98cba6d7ac 100644 --- a/mlx/distributed/distributed.cpp +++ b/mlx/distributed/distributed.cpp @@ -138,6 +138,22 @@ Group Group::split(int color, int key /* = -1 */) const { return Group(group_->split(color, key)); } +void Group::begin_startup_wait_budget(int64_t timeout_ms) const { + if (!group_) { + throw std::runtime_error( + "[distributed] Cannot set a budget on a null group."); + } + group_->begin_startup_wait_budget(timeout_ms); +} + +void Group::end_startup_wait_budget() const { + if (!group_) { + throw std::runtime_error( + "[distributed] Cannot end a budget on a null group."); + } + group_->end_startup_wait_budget(); +} + namespace { std::unordered_map>& diff --git a/mlx/distributed/distributed.h b/mlx/distributed/distributed.h index 0d6e4d41ef..fd312e133a 100644 --- a/mlx/distributed/distributed.h +++ b/mlx/distributed/distributed.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include @@ -61,6 +62,20 @@ struct MLX_API Group { */ Group split(int color, int key = -1) const; + /** + * Start one JACCL readiness budget of 1..900000 ms from the current + * monotonic time. Progress does not renew it. Other backends refuse. + * Drain queued work and serialize scheduling around begin/end; both require + * no running calls. The budget cannot restart after end or expiry. + */ + void begin_startup_wait_budget(int64_t timeout_ms) const; + + /** + * End an unexpired budget and restore the original idle timeout for later + * calls. Refuses unused, ended, expired or failed groups; never reopens one. + */ + void end_startup_wait_budget() const; + const std::shared_ptr& raw_group() const { return group_; } diff --git a/mlx/distributed/distributed_impl.h b/mlx/distributed/distributed_impl.h index d889587abc..ca0f46d1be 100644 --- a/mlx/distributed/distributed_impl.h +++ b/mlx/distributed/distributed_impl.h @@ -21,6 +21,15 @@ class GroupImpl { virtual int size() = 0; virtual std::shared_ptr split(int color, int key = -1) = 0; + virtual void begin_startup_wait_budget(int64_t) { + throw std::runtime_error( + "[distributed] Startup wait budgets require a JACCL group."); + } + virtual void end_startup_wait_budget() { + throw std::runtime_error( + "[distributed] Startup wait budgets require a JACCL group."); + } + // Actual communication operations virtual void all_sum(const array& input, array& output, Stream stream) = 0; virtual void all_gather(const array& input, array& output, Stream stream) = 0; diff --git a/mlx/distributed/jaccl/jaccl.cpp b/mlx/distributed/jaccl/jaccl.cpp index e13fc549f5..0b95c8a561 100644 --- a/mlx/distributed/jaccl/jaccl.cpp +++ b/mlx/distributed/jaccl/jaccl.cpp @@ -80,6 +80,14 @@ class JACCLGroup : public GroupImpl { return group_->size(); } + void begin_startup_wait_budget(int64_t timeout_ms) override { + group_->begin_startup_wait_budget(timeout_ms); + } + + void end_startup_wait_budget() override { + group_->end_startup_wait_budget(); + } + void all_sum(const array& input, array& output, Stream stream) override { auto in_ptr = input.data(); auto out_ptr = output.data(); diff --git a/mlx/distributed/jaccl/lib/README.md b/mlx/distributed/jaccl/lib/README.md index 92d80c3199..5e2bb9c713 100644 --- a/mlx/distributed/jaccl/lib/README.md +++ b/mlx/distributed/jaccl/lib/README.md @@ -372,3 +372,41 @@ The name JACCL (pronounced Jackal) stands for Jack and Angelos’ Collective Communication Library and it is an obvious pun to Nvidia’s NCCL but also tribute to Jack Beasley who led the development of RDMA over Thunderbolt at Apple. + +### One-shot startup readiness budget + +MLX callers can use `Group::begin_startup_wait_budget(int64_t timeout_ms) const` +and `Group::end_startup_wait_budget() const` on an initialized JACCL group. +The standalone JACCL group exposes the same operations. Other MLX backends +and unsupported JACCL group implementations throw; there is no fallback. + +Begin accepts 1..900000 ms and checks the monotonic deadline before publishing +state. Each actual mesh or ring group owns one policy shared by its wires. +The deadline starts at begin, includes time spent loading, and stays fixed +across calls and completions. During startup it replaces the idle limit. +Successful completions check expiry too; empty polls sample it every 1024 +polls. This bounds polling waits, not arbitrary computation or blocked system +calls. Keep the embedding runtime's hard startup deadline and cancellation. + +Drain queued work and serialize scheduling around begin and end. A running +call makes either transition fail. The caller must retain the group and must +not move/destroy its implementation while calls run. This API does not make +concurrent initialization or backend-cache clearing safe. + +Only an unused group can begin. Invalid arguments or deadline overflow leave +it unused. Only an active, unexpired, open and idle group can end; duplicate +end is refused. Expiry cannot be cleared by end, and begin can never renew or +reopen a used budget. Expiry observed by polling follows the existing failure +path: stop wires, close resources, then the configured throw or teardown-exit +with status 75 and the memory release hook. Ending does not create a transport +success, clear a failure, or reopen a group. + +After a successful end, later calls use the original environment/default idle +policy (normally 30000 ms). Existing zero/negative environment handling stays +unchanged, but the startup API always requires a positive finite budget. +The API accepts a relative duration; an external absolute deadline must still +be checked by the caller because dispatch/bridge time precedes core begin. + +`tests/jaccl/startup_wait_budget_tests.cpp` uses a controllable clock with the +real policy/guard. The group tests exercise real mesh/ring dispatch and cleanup +against simulated verbs. These CPU tests do not qualify native RDMA or loading. diff --git a/mlx/distributed/jaccl/lib/jaccl/group.h b/mlx/distributed/jaccl/lib/jaccl/group.h index 603765a511..66d160cb72 100644 --- a/mlx/distributed/jaccl/lib/jaccl/group.h +++ b/mlx/distributed/jaccl/lib/jaccl/group.h @@ -3,7 +3,9 @@ #pragma once #include +#include #include +#include namespace jaccl { @@ -17,6 +19,13 @@ class Group { virtual int rank() = 0; virtual int size() = 0; + virtual void begin_startup_wait_budget(int64_t) { + throw std::runtime_error("[jaccl] Startup wait budget is unsupported."); + } + virtual void end_startup_wait_budget() { + throw std::runtime_error("[jaccl] Startup wait budget is unsupported."); + } + virtual void all_sum(const void* input, void* output, size_t n_bytes, int dtype) = 0; diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh.h b/mlx/distributed/jaccl/lib/jaccl/mesh.h index 8e5164aee2..d60f01e525 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh.h @@ -32,6 +32,14 @@ class MeshGroup : public Group { return size_; } + void begin_startup_wait_budget(int64_t timeout_ms) override { + mesh_.begin_startup_wait_budget(timeout_ms); + } + + void end_startup_wait_budget() override { + mesh_.end_startup_wait_budget(); + } + void all_sum(const void* input, void* output, size_t n_bytes, int dtype) override; diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index fd8e21ca15..ef6575dc81 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -34,6 +34,14 @@ class MeshImpl { MeshImpl() : rank_(0), size_(1) {} + void begin_startup_wait_budget(int64_t timeout_ms) { + wait_budget_->begin(timeout_ms, *failed_); + } + + void end_startup_wait_budget() { + wait_budget_->end(*failed_); + } + template void all_reduce(const T* in, T* out, int64_t size, ReduceOp reduce_op) { // Fully connected all reduce with deterministic reduction order. @@ -543,7 +551,7 @@ class MeshImpl { class Call : public ProgressGuard { public: Call(MeshImpl& mesh, const char* op) - : ProgressGuard(op, *mesh.failed_), + : ProgressGuard(op, *mesh.failed_, mesh.wait_budget_.get()), mesh_(mesh), exceptions_(std::uncaught_exceptions()) { require_open(*mesh.failed_); @@ -666,6 +674,8 @@ class MeshImpl { std::span buffers_; std::span scatter_buffers_; std::unique_ptr staging_mem_; + std::unique_ptr wait_budget_ = + std::make_unique(); std::unique_ptr> failed_ = std::make_unique>(false); }; diff --git a/mlx/distributed/jaccl/lib/jaccl/progress_guard.h b/mlx/distributed/jaccl/lib/jaccl/progress_guard.h index a2009dd972..4a56deb37c 100644 --- a/mlx/distributed/jaccl/lib/jaccl/progress_guard.h +++ b/mlx/distributed/jaccl/lib/jaccl/progress_guard.h @@ -17,6 +17,8 @@ #include #include +#include "jaccl/startup_wait_budget.h" + namespace jaccl { constexpr int64_t DEFAULT_PROGRESS_TIMEOUT_MS = 30000; @@ -186,12 +188,30 @@ inline void require_open(const std::atomic& failed) { * owner of the group closes it and then, unless failure_action() is Throw, * calls teardown_exit(). */ -class ProgressGuard { +template +class BasicProgressGuard { public: - ProgressGuard(const char* op, std::atomic& failed) - : op_(op), failed_(failed), timeout_ms_(progress_timeout_ms()) {} + BasicProgressGuard( + const char* op, + std::atomic& failed, + BasicStartupWaitBudget* startup = nullptr) + : op_(op), failed_(failed), timeout_ms_(progress_timeout_ms()) { + if (startup != nullptr) { + call_.emplace(*startup); + startup_deadline_ = call_->deadline(); + } + } void check(const ibv_wc* wc, int n) { + if (startup_deadline_ && + (n != 0 || ++startup_polls_ % PROGRESS_SAMPLE_POLLS == 0)) { + if (failed_.load()) { + throw WireStopped(); + } + if (Clock::now() >= *startup_deadline_) { + fail("the absolute startup wait budget expired"); + } + } if (n > 0) { idle_polls_ = 0; for (int i = 0; i < n; i++) { @@ -221,10 +241,10 @@ class ProgressGuard { if (failed_.load()) { throw WireStopped(); } - if (timeout_ms_ <= 0) { + if (startup_deadline_ || timeout_ms_ <= 0) { return; } - auto now = std::chrono::steady_clock::now(); + auto now = Clock::now(); // The first sample after a completion starts the measurement. if (idle_polls_ == PROGRESS_SAMPLE_POLLS) { idle_since_ = now; @@ -254,8 +274,13 @@ class ProgressGuard { std::atomic& failed_; int64_t timeout_ms_; int64_t idle_polls_{0}; - std::chrono::steady_clock::time_point idle_since_; + typename Clock::time_point idle_since_; + std::optional::Call> call_; + std::optional startup_deadline_; + uint64_t startup_polls_{0}; std::string failure_; }; +using ProgressGuard = BasicProgressGuard<>; + } // namespace jaccl diff --git a/mlx/distributed/jaccl/lib/jaccl/ring.h b/mlx/distributed/jaccl/lib/jaccl/ring.h index c901c15a85..56a05153b5 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring.h +++ b/mlx/distributed/jaccl/lib/jaccl/ring.h @@ -34,6 +34,14 @@ class RingGroup : public Group { return size_; } + void begin_startup_wait_budget(int64_t timeout_ms) override { + ring_.begin_startup_wait_budget(timeout_ms); + } + + void end_startup_wait_budget() override { + ring_.end_startup_wait_budget(); + } + void all_sum(const void* input, void* output, size_t n_bytes, int dtype) override; diff --git a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h index d2c6f9b957..ab34b68e5e 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h @@ -55,6 +55,14 @@ class RingImpl { RingImpl() : rank_(0), size_(1), n_conns_(0), pool_(nullptr) {} + void begin_startup_wait_budget(int64_t timeout_ms) { + wait_budget_->begin(timeout_ms, *failed_); + } + + void end_startup_wait_budget() { + wait_budget_->end(*failed_); + } + // Copy the received chunk into the output. Used by the all gather passes. struct CopyOp { template @@ -374,7 +382,7 @@ class RingImpl { } }; - ProgressGuard guard("ring reduce_scatter", *failed_); + ProgressGuard guard("ring reduce_scatter", *failed_, wait_budget_.get()); for (int k = 0; k < size_ - 1; k++) { // Step 0 forwards this rank's own input; later steps forward the partial // accumulated in the output by the previous step. @@ -512,7 +520,8 @@ class RingImpl { }; set_limits(); - ProgressGuard guard("ring all_reduce/all_gather", *failed_); + ProgressGuard guard( + "ring all_reduce/all_gather", *failed_, wait_budget_.get()); for (int k = 0; k < size_ - 1; k++) { // Step 0 sends this rank's own input; later steps send the accumulated // partial from out_ptr. @@ -650,7 +659,7 @@ class RingImpl { } // Main loop - ProgressGuard guard("ring send", *failed_); + ProgressGuard guard("ring send", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -725,7 +734,7 @@ class RingImpl { } // Main loop - ProgressGuard guard("ring recv", *failed_); + ProgressGuard guard("ring recv", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -806,6 +815,7 @@ class RingImpl { // teardown_exit(). template void dispatch_wires(int n_wires, Fn&& fn) { + StartupWaitBudget::Call call(*wait_budget_); require_open(*failed_); auto run = [&](int lw) { @@ -885,6 +895,8 @@ class RingImpl { std::span send_buffers_; std::span recv_buffers_; ThreadPool* pool_; + std::unique_ptr wait_budget_ = + std::make_unique(); std::unique_ptr> failed_ = std::make_unique>(false); }; diff --git a/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h b/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h new file mode 100644 index 0000000000..8b0e0b53ff --- /dev/null +++ b/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h @@ -0,0 +1,112 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace jaccl { + +constexpr int64_t MAX_STARTUP_WAIT_BUDGET_MS = 900000; + +// Clock injection is local to the type; production uses steady_clock. +template +class BasicStartupWaitBudget { + public: + using TimePoint = typename Clock::time_point; + + void begin(int64_t timeout_ms, const std::atomic& failed) { + if (timeout_ms <= 0 || timeout_ms > MAX_STARTUP_WAIT_BUDGET_MS) { + throw std::invalid_argument( + "[jaccl] Startup budget must be 1..900000 ms."); + } + std::lock_guard lock(mutex_); + require_idle_open(failed); + if (state_ != State::Unused) { + throw std::logic_error("[jaccl] Startup budget can only begin once."); + } + using Duration = typename Clock::duration; + static_assert(Clock::is_steady); + static_assert( + std::chrono::duration_cast(Duration::max()) + .count() >= MAX_STARTUP_WAIT_BUDGET_MS); + const auto delta = std::chrono::duration_cast( + std::chrono::milliseconds(timeout_ms)); + const auto now = Clock::now(); + if (now.time_since_epoch() > Duration::max() - delta) { + throw std::overflow_error( + "[jaccl] Startup deadline overflows the clock."); + } + deadline_ = now + delta; + state_ = State::Active; + } + + void end(const std::atomic& failed) { + std::lock_guard lock(mutex_); + require_idle_open(failed); + if (state_ != State::Active) { + throw std::logic_error("[jaccl] No active startup budget to end."); + } + if (Clock::now() >= *deadline_) { + throw std::logic_error("[jaccl] Cannot end an expired startup budget."); + } + state_ = State::Ended; + } + + // Each operation holds a lease until all its wires and teardown finish. + class Call { + public: + explicit Call(BasicStartupWaitBudget& owner) : owner_(owner) { + std::lock_guard lock(owner_.mutex_); + if (owner_.state_ == State::Active) { + deadline_ = owner_.deadline_; + } + ++owner_.calls_; + } + + Call(const Call&) = delete; + Call& operator=(const Call&) = delete; + + ~Call() { + std::lock_guard lock(owner_.mutex_); + --owner_.calls_; + } + + const std::optional& deadline() const { + return deadline_; + } + + private: + BasicStartupWaitBudget& owner_; + std::optional deadline_; + }; + + private: + enum class State { Unused, Active, Ended }; + + void require_idle_open(const std::atomic& failed) const { + if (failed.load()) { + throw std::runtime_error( + "[jaccl] The group is closed after an earlier failure and cannot be " + "used again."); + } + if (calls_ != 0) { + throw std::logic_error( + "[jaccl] Startup transition requires an idle group."); + } + } + + std::mutex mutex_; + State state_{State::Unused}; + std::size_t calls_{0}; + std::optional deadline_; +}; + +using StartupWaitBudget = BasicStartupWaitBudget<>; + +} // namespace jaccl diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py new file mode 100644 index 0000000000..f074676be6 --- /dev/null +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -0,0 +1,80 @@ +# Custom Metal launch validation. + +import unittest + +import mlx.core as mx + + +@unittest.skipIf(not mx.metal.is_available(), "Metal is unavailable; not a pass") +class ThreadgroupBoundsTests(unittest.TestCase): + def test_invalid_dimensions_precede_compilation(self): + # A compiler attempt would raise RuntimeError instead of ValueError. + cases = [ + ((0, 1, 1), (1024, 1, 1), "dimensions"), + ((1, 0, 1), (1024, 1, 1), "dimensions"), + ((1, 1, 0), (1024, 1, 1), "dimensions"), + ((-1, 1, 1), (1024, 1, 1), "dimensions"), + ((1, -1, 1), (1024, 1, 1), "dimensions"), + ((1, 1, -1), (1024, 1, 1), "dimensions"), + ((1024, 1, 1), (-1, 1, 1), "dimensions"), + ((1024, 1, 1), (1, -1, 1), "dimensions"), + ((1024, 1, 1), (1, 1, -1), "dimensions"), + ((65536, 65536, 1), (1024, 1, 1), "32 bits"), + ( + (2147483647, 2147483647, 2147483647), + (1024, 1, 1), + "32 bits", + ), + ((2147483647, 1, 1), (1024, 1, 1), "device dimensions"), + ((1, 2147483647, 1), (1024, 1, 1), "device dimensions"), + ((1, 1, 2147483647), (1024, 1, 1), "device dimensions"), + ] + for index, (group, grid, message) in enumerate(cases): + with self.subTest(group=group, grid=grid): + kernel = mx.fast.metal_kernel( + name=f"invalid_geometry_{index}", + input_names=[], + output_names=["out"], + source="INTENTIONAL_INVALID_METAL;", + ensure_row_contiguous=True, + ) + with self.assertRaisesRegex(ValueError, message): + outputs = kernel( + inputs=[], + grid=grid, + threadgroup=group, + output_shapes=[(1,)], + output_dtypes=[mx.uint32], + init_value=0, + stream=mx.gpu, + ) + mx.eval(outputs) + + def test_legal_launch_keeps_threads_and_values(self): + for group in [32, 256, 1024]: + kernel = mx.fast.metal_kernel( + name="thread_count_and_math", + input_names=["a"], + output_names=["out", "count"], + source=""" + uint i = thread_position_in_grid.x; + out[i] = a[i] * 2.0f + 1.0f; + count[i] = threads_per_threadgroup.x; + """, + ) + a = mx.arange(2048, dtype=mx.float32) + out, count = kernel( + inputs=[a], + grid=(2048, 1, 1), + threadgroup=(group, 1, 1), + output_shapes=[(2048,), (2048,)], + output_dtypes=[mx.float32, mx.uint32], + stream=mx.gpu, + ) + mx.eval(out, count) + self.assertTrue(mx.array_equal(out, a * 2 + 1).item()) + self.assertTrue(mx.all(count == group).item()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/jaccl/CMakeLists.txt b/tests/jaccl/CMakeLists.txt index 2f7eec9eee..b003dd4642 100644 --- a/tests/jaccl/CMakeLists.txt +++ b/tests/jaccl/CMakeLists.txt @@ -26,6 +26,16 @@ endfunction() jaccl_test(send_frame_tests) jaccl_test(progress_guard_tests) +jaccl_test(startup_wait_budget_tests) +jaccl_test(startup_wait_budget_group_tests) +jaccl_test(startup_wait_budget_api_tests) +target_include_directories(startup_wait_budget_api_tests PRIVATE ../..) +add_test(NAME startup_wait_budget_api COMMAND startup_wait_budget_api_tests) +add_test(NAME startup_wait_budget_groups + COMMAND startup_wait_budget_group_tests) +set_tests_properties(startup_wait_budget_groups + PROPERTIES ENVIRONMENT "JACCL_TIMEOUT_ACTION=throw") +add_test(NAME startup_wait_budget COMMAND startup_wait_budget_tests) add_test(NAME send_frame COMMAND send_frame_tests) diff --git a/tests/jaccl/startup_wait_budget_api_tests.cpp b/tests/jaccl/startup_wait_budget_api_tests.cpp new file mode 100644 index 0000000000..28bd34336f --- /dev/null +++ b/tests/jaccl/startup_wait_budget_api_tests.cpp @@ -0,0 +1,75 @@ +// Copyright © 2026 Apple Inc. +#include +#include +#include "jaccl/group.h" +#include "mlx/distributed/distributed_impl.h" + +using mlx::core::array; +using mlx::core::Stream; +using mlx::core::StreamOrDevice; +using mlx::core::distributed::Group; +using mlx::core::distributed::detail::GroupImpl; +static_assert(std::is_same_v< + decltype(&Group::begin_startup_wait_budget), + void (Group::*)(int64_t) const>); +static_assert(std::is_same_v< + decltype(&Group::end_startup_wait_budget), + void (Group::*)() const>); +class Unsupported : public GroupImpl { + public: + Stream communication_stream(StreamOrDevice) override { + throw std::runtime_error("unused"); + } + int rank() override { + return 0; + } + int size() override { + return 1; + } + std::shared_ptr split(int, int) override { + return nullptr; + } + void all_sum(const array&, array&, Stream) override {} + void all_max(const array&, array&, Stream) override {} + void all_min(const array&, array&, Stream) override {} + void all_gather(const array&, array&, Stream) override {} + void sum_scatter(const array&, array&, Stream) override {} + void send(const array&, int, Stream) override {} + void recv(array&, int, Stream) override {} +}; +class UnsupportedStandalone : public jaccl::Group { + public: + int rank() override { + return 0; + } + int size() override { + return 1; + } + void all_sum(const void*, void*, size_t, int) override {} + void all_max(const void*, void*, size_t, int) override {} + void all_min(const void*, void*, size_t, int) override {} + void all_gather(const void*, void*, size_t) override {} + void sum_scatter(const void*, void*, size_t, int) override {} + void send(const void*, size_t, int) override {} + void recv(void*, size_t, int) override {} + void barrier() override {} +}; +template +void refuses(Fn fn) { + try { + fn(); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error("unsupported backend accepted startup budget"); +} +int main() { + Unsupported group; + UnsupportedStandalone standalone; + refuses([&] { group.begin_startup_wait_budget(1000); }); + refuses([&] { group.end_startup_wait_budget(); }); + refuses([&] { standalone.begin_startup_wait_budget(1000); }); + refuses([&] { standalone.end_startup_wait_budget(); }); + std::cout + << "PASS exact public const API types\nPASS unsupported GroupImpl begin/end\nPASS unsupported standalone begin/end\npassed=3 failed=0 skipped=0 native_rdma=0\n"; +} diff --git a/tests/jaccl/startup_wait_budget_group_tests.cpp b/tests/jaccl/startup_wait_budget_group_tests.cpp new file mode 100644 index 0000000000..9940085da4 --- /dev/null +++ b/tests/jaccl/startup_wait_budget_group_tests.cpp @@ -0,0 +1,114 @@ +// Copyright © 2026 Apple Inc. +// CPU simulated verbs only. Real MeshImpl/RingImpl call and cleanup paths. +#include +#include +#include "fixture.h" + +void require(bool value) { + fixture::require(value, "startup group assertion failed"); +} +template +void refuses(Fn fn, const std::string& text) { + try { + fn(); + } catch (const std::exception& e) { + require(std::string(e.what()).find(text) != std::string::npos); + return; + } + throw std::runtime_error("expected refusal"); +} +void mesh_success_end() { + fixture::MeshPair pair; + for (auto& node : pair.nodes) { + node->begin_startup_wait_budget(10000); + } + char input = 42, output = 0; + fixture::both( + [&] { pair.nodes[0]->send(&input, 1, 1); }, + [&] { pair.nodes[1]->recv(&output, 1, 0); }); + require(input == output); + pair.fabric.require_drained(); + for (auto& node : pair.nodes) { + node->end_startup_wait_budget(); + refuses([&] { node->begin_startup_wait_budget(10000); }, "only begin once"); + } + fixture::both( + [&] { pair.nodes[0]->send(&input, 1, 1); }, + [&] { pair.nodes[1]->recv(&output, 1, 0); }); + pair.fabric.require_drained(); +} +void ring_success_end(int wires) { + fixture::RingPair pair(wires); + for (auto& node : pair.nodes) { + node->begin_startup_wait_budget(10000); + } + std::vector input(99, 42), output(99, 0); + fixture::both( + [&] { pair.nodes[0]->send(input.data(), 99, 1, wires); }, + [&] { pair.nodes[1]->recv(output.data(), 99, 0, wires); }); + require(input == output); + pair.fabric.require_drained(); + for (auto& node : pair.nodes) { + node->end_startup_wait_budget(); + } + fixture::both( + [&] { pair.nodes[0]->send(input.data(), 99, 1, wires); }, + [&] { pair.nodes[1]->recv(output.data(), 99, 0, wires); }); + pair.fabric.require_drained(); +} +void mesh_expiry_cleanup() { + fixture::MeshPair pair; + auto& node = *pair.nodes[0]; + node.begin_startup_wait_budget(1); + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + char output = 0; + const auto qp = fixture::ledger().destroy_queue_pair_calls.load(); + const auto cq = fixture::ledger().destroy_completion_queue_calls.load(); + const auto mr = fixture::ledger().deregister_calls.load(); + refuses([&] { node.recv(&output, 1, 1); }, "absolute startup"); + require(fixture::ledger().destroy_queue_pair_calls == qp + 1); + require(fixture::ledger().destroy_completion_queue_calls == cq + 1); + require(fixture::ledger().deregister_calls > mr); + refuses([&] { node.end_startup_wait_budget(); }, "closed"); + refuses([&] { node.begin_startup_wait_budget(10000); }, "closed"); + refuses([&] { node.recv(&output, 1, 1); }, "closed"); +} +void ring_expiry_cleanup(int wires) { + fixture::RingPair pair(wires); + auto& node = *pair.nodes[0]; + node.begin_startup_wait_budget(1); + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + std::vector output(99, 0); + const auto qp = fixture::ledger().destroy_queue_pair_calls.load(); + const auto cq = fixture::ledger().destroy_completion_queue_calls.load(); + const auto mr = fixture::ledger().deregister_calls.load(); + refuses([&] { node.recv(output.data(), 99, 1, wires); }, "absolute startup"); + require(fixture::ledger().destroy_queue_pair_calls == qp + 2 * wires); + require(fixture::ledger().destroy_completion_queue_calls == cq + 2 * wires); + require(fixture::ledger().deregister_calls > mr); + refuses([&] { node.end_startup_wait_budget(); }, "closed"); + refuses([&] { node.begin_startup_wait_budget(10000); }, "closed"); + refuses([&] { node.recv(output.data(), 99, 1, wires); }, "closed"); +} +int main() { + jaccl::set_memory_release(nullptr); + require(jaccl::failure_action() == jaccl::FailureAction::Throw); + mesh_success_end(); + std::cout << "PASS mesh success/end/later-serving\n"; + for (int wires : {1, 2}) { + ring_success_end(wires); + std::cout << "PASS ring success/end/later-serving wires=" << wires << "\n"; + } + mesh_expiry_cleanup(); + std::cout << "PASS mesh expiry/cleanup/closed\n"; + for (int wires : {1, 2}) { + ring_expiry_cleanup(wires); + std::cout << "PASS ring expiry/cleanup/closed wires=" << wires << "\n"; + } + require( + fixture::ledger().queue_pairs == 0 && + fixture::ledger().completion_queues == 0 && + fixture::ledger().regions == 0); + std::cout + << "PASS fake resource ledger empty\npassed=7 failed=0 skipped=0 native_rdma=0\n"; +} diff --git a/tests/jaccl/startup_wait_budget_tests.cpp b/tests/jaccl/startup_wait_budget_tests.cpp new file mode 100644 index 0000000000..67114bb0ed --- /dev/null +++ b/tests/jaccl/startup_wait_budget_tests.cpp @@ -0,0 +1,441 @@ +// Copyright © 2026 Apple Inc. +// Standalone CPU policy tests: use the real policy and guard with a fake clock. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct FakeClock { + using duration = std::chrono::nanoseconds; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + static constexpr bool is_steady = true; + static inline std::atomic ticks{0}; + static time_point now() { + return time_point(duration(ticks.load())); + } + static void ms(int64_t n) { + ticks.store(n * 1000000); + } +}; + +#include "jaccl/progress_guard.h" + +using Policy = jaccl::BasicStartupWaitBudget; +using Guard = jaccl::BasicProgressGuard; +using namespace std::chrono_literals; + +void require(bool ok) { + if (!ok) { + throw std::runtime_error("assertion failed"); + } +} +template +void refuses(Fn fn, const std::string& message = "") { + try { + fn(); + } catch (const E& e) { + require( + message.empty() || + std::string(e.what()).find(message) != std::string::npos); + return; + } + throw std::runtime_error("expected refusal"); +} +void sample(Guard& g) { + for (int i = 0; i < jaccl::PROGRESS_SAMPLE_POLLS; ++i) { + g.check(nullptr, 0); + } +} +ibv_wc success{}; + +void default_idle() { + std::atomic failed{false}; + Guard g("default", failed); + sample(g); + FakeClock::ms(30000); + sample(g); + require(!failed); + FakeClock::ms(30001); + refuses([&] { sample(g); }, "no completion for 30001"); + require(failed); +} +void default_progress_resets_idle() { + std::atomic failed{false}; + Policy p; + Guard g("default group", failed, &p); + sample(g); + FakeClock::ms(29000); + g.check(&success, 1); + sample(g); + FakeClock::ms(59000); + sample(g); + require(!failed); + FakeClock::ms(59001); + refuses([&] { sample(g); }); +} +void startup_deadline() { + std::atomic failed{false}; + Policy p; + p.begin(120000, failed); + Guard g("startup", failed, &p); + sample(g); + FakeClock::ms(30001); + sample(g); + FakeClock::ms(119999); + sample(g); + require(!failed); + FakeClock::ms(120000); + refuses([&] { sample(g); }, "absolute startup"); + require(failed); +} +void progress_cannot_renew() { + std::atomic failed{false}; + Policy p; + p.begin(60000, failed); + Guard g("progress", failed, &p); + for (int i = 1; i < 60; ++i) { + FakeClock::ms(i * 1000); + g.check(&success, 1); + } + FakeClock::ms(60000); + refuses([&] { g.check(&success, 1); }, "absolute startup"); + require(failed); +} +void deadline_shared_across_calls() { + std::atomic failed{false}; + Policy p; + p.begin(60000, failed); + { + Guard first("first", failed, &p); + FakeClock::ms(40000); + first.check(&success, 1); + } + Guard second("second", failed, &p); + FakeClock::ms(60000); + refuses([&] { second.check(&success, 1); }); +} +void end_restores_idle() { + std::atomic failed{false}; + Policy p; + p.begin(120000, failed); + { + Guard startup("startup", failed, &p); + FakeClock::ms(40000); + startup.check(&success, 1); + } + p.end(failed); + Guard serving("serving", failed, &p); + sample(serving); + FakeClock::ms(70000); + sample(serving); + require(!failed); + FakeClock::ms(70001); + refuses([&] { sample(serving); }, "no completion"); +} +void invalid_does_not_consume() { + std::atomic failed{false}; + Policy p; + for (int64_t n : + {int64_t(-1), + int64_t(0), + int64_t(900001), + std::numeric_limits::max(), + std::numeric_limits::min()}) { + refuses([&] { p.begin(n, failed); }); + } + p.begin(1, failed); + Guard g("minimum", failed, &p); + FakeClock::ms(1); + refuses([&] { g.check(&success, 1); }); +} +void maximum_budget() { + std::atomic failed{false}; + Policy p; + p.begin(900000, failed); + Guard g("maximum", failed, &p); + FakeClock::ms(899999); + g.check(&success, 1); + FakeClock::ms(900000); + refuses([&] { g.check(&success, 1); }); +} +void checked_overflow() { + std::atomic failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::max() - 999999); + refuses([&] { p.begin(1, failed); }); + FakeClock::ms(0); + p.begin(1, failed); + p.end(failed); +} +void exact_clock_limit() { + std::atomic failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::max() - 1000000); + p.begin(1, failed); + Guard g("clock limit", failed, &p); + FakeClock::ticks.store(std::numeric_limits::max()); + refuses([&] { g.check(&success, 1); }); +} +void negative_clock_epoch() { + std::atomic failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::min()); + p.begin(900000, failed); + p.end(failed); +} +void one_shot() { + std::atomic failed{false}; + Policy p; + refuses([&] { p.end(failed); }); + p.begin(1000, failed); + refuses([&] { p.begin(900000, failed); }); + p.end(failed); + refuses([&] { p.end(failed); }); + refuses([&] { p.begin(1000, failed); }); +} +void expired_end_refuses() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + FakeClock::ms(1000); + refuses([&] { p.end(failed); }, "expired"); + refuses([&] { p.begin(1000, failed); }); + Guard g("still expired", failed, &p); + refuses([&] { g.check(&success, 1); }); + require(failed); +} +void closed_group_stays_closed() { + std::atomic failed{true}; + Policy p; + refuses([&] { p.begin(1000, failed); }); + require(failed); + std::atomic another_failed{false}; + Policy q; + q.begin(1000, another_failed); + another_failed = true; + refuses([&] { q.end(another_failed); }); + refuses([&] { q.begin(1000, another_failed); }); + require(another_failed); +} +void transitions_refuse_running_calls() { + std::atomic failed{false}; + Policy p; + { + Guard g("default live", failed, &p); + refuses([&] { p.begin(1000, failed); }, "idle"); + } + p.begin(1000, failed); + { + Guard g("startup live", failed, &p); + refuses([&] { p.end(failed); }, "idle"); + } + p.end(failed); +} +void two_groups() { + std::atomic a_failed{false}, b_failed{false}; + Policy a, b; + a.begin(120000, a_failed); + Guard ga("A", a_failed, &a), gb("B", b_failed, &b); + sample(ga); + sample(gb); + FakeClock::ms(30001); + sample(ga); + refuses([&] { sample(gb); }); + require(!a_failed && b_failed); +} +void two_active_groups() { + std::atomic a_failed{false}, b_failed{false}; + Policy a, b; + a.begin(1000, a_failed); + b.begin(2000, b_failed); + Guard ga("active A", a_failed, &a), gb("active B", b_failed, &b); + FakeClock::ms(1000); + refuses([&] { ga.check(&success, 1); }); + gb.check(&success, 1); + require(!b_failed); + FakeClock::ms(2000); + refuses([&] { gb.check(&success, 1); }); +} +void shared_wires() { + std::atomic failed{false}; + Policy p; + p.begin(60000, failed); + Guard a("wire A", failed, &p), b("wire B", failed, &p); + FakeClock::ms(60000); + refuses([&] { a.check(&success, 1); }, "absolute startup"); + refuses([&] { sample(b); }); +} +void late_wire_keeps_failure_kind() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + failed = true; + Guard late("late wire", failed, &p); + refuses([&] { late.check(&success, 1); }); +} + +void concurrent_begin() { + std::atomic failed{false}; + Policy p; + std::atomic won{0}, refused{0}; + std::vector threads; + for (int i = 0; i < 16; ++i) { + threads.emplace_back([&] { + try { + p.begin(1000, failed); + ++won; + } catch (const std::logic_error&) { + ++refused; + } + }); + } + for (auto& t : threads) { + t.join(); + } + require(won == 1 && refused == 15); + p.end(failed); +} +void concurrent_transition_and_wires() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + std::atomic ready{0}; + std::atomic release{false}; + std::vector threads; + for (int i = 0; i < 8; ++i) { + threads.emplace_back([&] { + Guard g("wire", failed, &p); + ++ready; + while (!release.load()) { + std::this_thread::yield(); + } + g.check(&success, 1); + }); + } + while (ready != 8) { + std::this_thread::yield(); + } + refuses([&] { p.end(failed); }, "idle"); + release = true; + for (auto& t : threads) { + t.join(); + } + p.end(failed); +} +void hardware_error_preserved() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + Guard g("hardware", failed, &p); + ibv_wc wc{}; + wc.status = IBV_WC_WR_FLUSH_ERR; + refuses([&] { g.check(&wc, 1); }, "work completion failed"); + require(failed); +} +void poll_error_preserved() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + Guard g("poll", failed, &p); + refuses([&] { g.check(nullptr, -1); }, "could not be polled"); + require(failed); +} + +int environment_policy() { + std::atomic failed{false}; + Policy p; + const int64_t timeout = jaccl::progress_timeout_ms(); + { + Guard g("environment default", failed, &p); + sample(g); + FakeClock::ms(1000000); + if (timeout > 0) { + refuses([&] { sample(g); }); + } else { + sample(g); + require(!failed); + } + } + failed = false; + FakeClock::ms(0); + Policy startup; + startup.begin(1000, failed); + { + Guard g("environment startup", failed, &startup); + FakeClock::ms(500); + g.check(&success, 1); + FakeClock::ms(1000); + refuses([&] { g.check(&success, 1); }, "absolute startup"); + } + failed = false; + FakeClock::ms(0); + Policy ended; + ended.begin(1000, failed); + ended.end(failed); + { + Guard g("environment ended", failed, &ended); + sample(g); + FakeClock::ms(1000000); + if (timeout > 0) { + refuses([&] { sample(g); }); + } else { + sample(g); + require(!failed); + } + } + std::cout << "PASS environment default/startup/end timeout=" << timeout + << "\n"; + return 0; +} + +int main(int argc, char**) { + if (argc > 1) { + return environment_policy(); + } + const std::vector>> tests = { + {"default_idle", default_idle}, + {"default_progress_resets_idle", default_progress_resets_idle}, + {"startup_deadline", startup_deadline}, + {"progress_cannot_renew", progress_cannot_renew}, + {"deadline_shared_across_calls", deadline_shared_across_calls}, + {"end_restores_idle", end_restores_idle}, + {"invalid_does_not_consume", invalid_does_not_consume}, + {"maximum_budget", maximum_budget}, + {"checked_overflow", checked_overflow}, + {"exact_clock_limit", exact_clock_limit}, + {"negative_clock_epoch", negative_clock_epoch}, + {"one_shot", one_shot}, + {"expired_end_refuses", expired_end_refuses}, + {"closed_group_stays_closed", closed_group_stays_closed}, + {"transitions_refuse_running_calls", transitions_refuse_running_calls}, + {"two_groups", two_groups}, + {"two_active_groups", two_active_groups}, + {"shared_wires", shared_wires}, + {"late_wire_keeps_failure_kind", late_wire_keeps_failure_kind}, + {"concurrent_begin", concurrent_begin}, + {"concurrent_transition_and_wires", concurrent_transition_and_wires}, + {"hardware_error_preserved", hardware_error_preserved}, + {"poll_error_preserved", poll_error_preserved}, + }; + int passed = 0; + for (const auto& [name, test] : tests) { + FakeClock::ms(0); + try { + test(); + ++passed; + std::cout << "PASS " << name << "\n"; + } catch (const std::exception& e) { + std::cerr << "FAIL " << name << ": " << e.what() << "\n"; + return 1; + } + } + std::cout << "passed=" << passed << " failed=0 skipped=0 native_rdma=0\n"; +} diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index d50feb8b1b..ed5c4959f7 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Eigen Labs. +#include #include #include #include @@ -383,12 +384,64 @@ void footprint_case(size_t page, bool capped) { refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); } +// Capped backing is owned no-copy VM. Pages first written by the GPU must +// still be charged to this process, or the OS cannot see the model's memory. +size_t physical_footprint() { + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + require( + task_info( + mach_task_self(), + TASK_VM_INFO, + reinterpret_cast(&info), + &count) == KERN_SUCCESS, + "task footprint unavailable"); + return static_cast(info.phys_footprint); +} + +bool footprint_growth_at_least(size_t before, size_t after, size_t expected) { + return after >= before && after - before >= expected; +} + +void footprint_delta_case() { + require( + !footprint_growth_at_least(1024, 1023, 512), + "decrease wrapped into growth"); + require( + !footprint_growth_at_least(1024, 1024, 1), "unchanged footprint grew"); + require(!footprint_growth_at_least(1024, 1535, 512), "short growth passed"); + require(footprint_growth_at_least(1024, 1536, 512), "exact growth failed"); + require( + !footprint_growth_at_least(SIZE_MAX, 0, 1), "maximum baseline wrapped"); +} + +void gpu_footprint_case() { + const size_t bytes = size_t(512) << 20; + install_process_allocation_cap(size_t(2) << 30); + const auto before = physical_footprint(); + { + auto filled = + full({int(bytes / sizeof(float))}, 1.0f, float32, Device::gpu); + eval(filled); + synchronize(default_stream(Device::gpu)); + const auto after = physical_footprint(); + require( + footprint_growth_at_least(before, after, bytes - (bytes >> 4)), + "GPU-written capped backing missing from process footprint"); + } + clear_cache(); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "footprint" || mode == "footprint-ordinary") { + if (mode == "footprint-delta") { + footprint_delta_case(); + } else if (mode == "gpu-footprint") { + gpu_footprint_case(); + } else if (mode == "footprint" || mode == "footprint-ordinary") { footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); From 3a1791192aaf6b834d8e2a12fde623026045a4ec Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:32:34 -0700 Subject: [PATCH 12/44] fix(metal): retry 512-thread kernels with explicit compiler capacity --- docs/src/dev/custom_metal_kernels.rst | 8 ++++---- fork.yaml | 4 ++-- mlx/backend/metal/custom_kernel.cpp | 4 ++-- python/tests/test_metal_threadgroup_bounds.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index f3ad478438..8c160167ef 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -473,10 +473,10 @@ Threadgroup compiler capacity Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, a thread count within UINT32_MAX, and axes within the device limits. Invalid geometry is refused before output allocation. A capable original pipeline is -kept. For a nonempty grid containing complete 1024-wide groups, exactly -``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL -``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +kept. For a nonempty grid containing complete 512- or 1024-wide groups, exactly +``(512, 1, 1)`` or ``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(requestedWidth)`` declaration attribute. The retry uses a distinct source/library identity and must itself support the full threadgroup. Compile errors and remaining capacity failures propagate. This does not change shader math, precision, group/grid axes, or guarantee that a -particular shader can compile at 1024. Other geometries receive no retry. +particular shader can compile at the requested width. Other geometries receive no retry. diff --git a/fork.yaml b/fork.yaml index 3641e4a7a2..5370fa1e43 100644 --- a/fork.yaml +++ b/fork.yaml @@ -200,8 +200,8 @@ def: description: | Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond the device limits before allocating outputs. A nonempty grid with complete - x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient - pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + x-axis multiples of the group width and groups (512,1,1) or (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(requestedWidth) on its unique generated declaration. The original capable pipeline is retained; retry compilation and the selected pipeline's actual capacity remain authoritative. Other geometries refuse without clamping. Shader math and dispatch axes do not change. diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 33f502a718..3ee8f3d029 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -87,8 +87,8 @@ void CustomKernel::eval_gpu( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && - gx % tx == 0 && gy > 0 && gz > 0; + const bool retry_geometry = (tx == 512 || tx == 1024) && ty == 1 && tz == 1 && + gx >= tx && gx % tx == 0 && gy > 0 && gz > 0; if (tg_size > max_tg_size && retry_geometry) { const std::string declaration = "[[kernel]] void " + name_ + "("; const auto position = source_.find(declaration); diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py index f074676be6..49466d0440 100644 --- a/python/tests/test_metal_threadgroup_bounds.py +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -51,7 +51,7 @@ def test_invalid_dimensions_precede_compilation(self): mx.eval(outputs) def test_legal_launch_keeps_threads_and_values(self): - for group in [32, 256, 1024]: + for group in [32, 256, 512, 1024]: kernel = mx.fast.metal_kernel( name="thread_count_and_math", input_names=["a"], From 61fd8a805408702d6e56668a41acd22af9715306 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:18:51 -0700 Subject: [PATCH 13/44] jaccl: 1 MiB RDMA frames; mesh pipeline from MESH_PIPELINE Raise the largest JACCL frame from 512 KiB to 1 MiB (BUFFER_SIZES 9) and size the mesh pipeline from MESH_PIPELINE (2), asserted at compile time. Measured on two M5 Ultra over Thunderbolt 5: a 16 MiB bf16 all-sum drops from 3.02 ms to 2.69 ms; GLM-5.3-Flash TP2 prefill on a 3.9K-token prompt goes from 2,130 to 2,289 tok/s. 2 MiB frames and a pipeline of 4 fail in the driver. Co-Authored-By: Claude Opus 5.5 --- mlx/distributed/jaccl/lib/jaccl/mesh_impl.h | 4 +++- mlx/distributed/jaccl/lib/jaccl/rdma.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index ef6575dc81..682a837a43 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -55,7 +55,9 @@ class MeshImpl { Call call(*this, "mesh all_reduce"); auto [sz, buffer_size] = buffer_size_from_message(size * sizeof(T)); int64_t N = buffer_size / sizeof(T); - constexpr int PIPELINE = 2; + // Frames in flight per peer (staging holds this many; NUM_BUFFERS >= it). + constexpr int PIPELINE = MESH_PIPELINE; + static_assert(MESH_PIPELINE <= NUM_BUFFERS, "mesh pipeline exceeds registered buffers"); constexpr int WC_NUM = PIPELINE * MESH_MAX_PEERS * 2; int64_t total = static_cast(size); int num_peers = size_ - 1; diff --git a/mlx/distributed/jaccl/lib/jaccl/rdma.h b/mlx/distributed/jaccl/lib/jaccl/rdma.h index f2023ca515..082302dc32 100644 --- a/mlx/distributed/jaccl/lib/jaccl/rdma.h +++ b/mlx/distributed/jaccl/lib/jaccl/rdma.h @@ -24,7 +24,7 @@ constexpr int MAX_RECV_WR = 32; // outstanding. A queue sized exactly to the outstanding work has no headroom, // and a provider may drop a completion on a full queue without an error. constexpr int COMPLETION_QUEUE_DEPTH = 4 * (MAX_SEND_WR + MAX_RECV_WR); -constexpr int BUFFER_SIZES = 8; +constexpr int BUFFER_SIZES = 9; constexpr int NUM_BUFFERS = 2; constexpr int FRAME_SIZE = 4096; From f0db8cfebaf666348fa8e68f17d567dfaf535f6c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:18:51 -0700 Subject: [PATCH 14/44] fix(metal): order the fast-synch GPU wait after pending passes; parallel sealed add A GPU pass that spins on a CPU-stream fence (MLX_METAL_FAST_SYNCH=1) had no dependency on earlier passes still in flight on its queue. Without hazard tracking Metal may start it first; when an earlier pass is what the awaited CPU work needs (GPU -> CPU -> GPU, e.g. the sealed all-sum), the GPU spins forever at 100 %. Traced on two M5 Ultra (GLM-5.3-Flash TP2): a committed buffer of plain elementwise ops stayed scheduled-not-started while the spin ran. The spin's pass now waits on every pending pass (CommandEncoder::wait_for_all_pending); the CPU work it waits for already follows them, so nothing is lost. Sealed TP2 then runs: prefill 1,913 tok/s, decode 50.7 tok/s (event sync instead: 13 tok/s). The sealed all-sum's rank-order add is split across cores (256K-element spans via dispatch_apply); the order of the two addends is unchanged, so the result is bit-identical. 32 MiB fp32 sealed sum: 20-25 ms -> 5.9 ms. Co-Authored-By: Claude Opus 5.5 --- mlx/backend/metal/device.cpp | 8 ++++++++ mlx/backend/metal/device.h | 8 ++++++++ mlx/backend/metal/fence.cpp | 7 +++++++ mlx/distributed/sealed.cpp | 22 ++++++++++++++++++++-- 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index c4d7de0586..f61112c89f 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -464,6 +464,13 @@ void CommandEncoder::end_encoding() { } } } + if (wait_all_pending_) { + for (auto& [_, pending] : prev_ce_outputs_) { + if (waiting_on.insert(pending).second) { + encoder_->waitForFence(pending.get()); + } + } + } for (auto& out : all_outputs_) { prev_ce_outputs_[out] = fence_; } @@ -489,6 +496,7 @@ void CommandEncoder::end_encoding() { encoder_->endEncoding(); encoder_.reset(); needs_barrier_ = false; + wait_all_pending_ = false; concurrent_ = false; prev_inputs_.clear(); next_inputs_.clear(); diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 5599047bf9..f6beacea9c 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -90,6 +90,13 @@ class MLX_API CommandEncoder { } void barrier(); + + // The current pass waits for every pass still in flight on this queue, not + // only those that wrote its inputs (see Fence::wait). + void wait_for_all_pending() { + wait_all_pending_ = true; + } + void end_encoding(); void wait_event(Event event, uint64_t value); void signal_event(Event event, uint64_t value); @@ -130,6 +137,7 @@ class MLX_API CommandEncoder { NS::SharedPtr encoder_; NS::SharedPtr fence_; bool needs_barrier_{false}; + bool wait_all_pending_{false}; bool concurrent_{false}; std::vector temporaries_; std::unordered_set prev_inputs_; diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 70dd0e33bd..7d12724c84 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -67,6 +67,13 @@ void Fence::wait(Stream stream, const array& x) { // Register outputs to ensure that no kernels which depends on the // output starts before this one is done compute_encoder.register_output_array(x); + // The spin must not start ahead of GPU work encoded before it: without + // hazard tracking Metal may run this pass before an earlier pass still in + // flight, and when that pass is what the awaited CPU work depends on (a + // GPU -> CPU -> GPU chain, e.g. a CPU-stream collective) the GPU spins + // forever. Waiting on every pending pass costs nothing here: the CPU work + // this spin waits for already follows them. + compute_encoder.wait_for_all_pending(); auto kernel = d.get_kernel("fence_wait"); MTL::Size kernel_dims = MTL::Size(1, 1, 1); diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index 41b0704ec0..d925ebddd3 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -1,5 +1,7 @@ // Copyright © 2026 Darkbloom. +#include +#include #include #include @@ -58,14 +60,14 @@ array all_sum_sealed( namespace { template -void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { +void add_span(const T* rank0, const T* rank1, T* out, size_t n) { for (size_t i = 0; i < n; ++i) { out[i] = static_cast( static_cast(rank0[i]) + static_cast(rank1[i])); } } template <> -void add_in_rank_order( +void add_span( const float* rank0, const float* rank1, float* out, @@ -74,6 +76,22 @@ void add_in_rank_order( out[i] = rank0[i] + rank1[i]; } } +// The same element-wise sum (one rounding, rank 0 + rank 1), split across +// cores for prefill-sized partials; small partials stay on this thread. +template +void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { + constexpr size_t kSpan = size_t(1) << 18; + if (n <= kSpan) { + add_span(rank0, rank1, out, n); + return; + } + size_t spans = (n + kSpan - 1) / kSpan; + dispatch_apply(spans, DISPATCH_APPLY_AUTO, ^(size_t i) { + size_t begin = i * kSpan; + size_t count = std::min(kSpan, n - begin); + add_span(rank0 + begin, rank1 + begin, out + begin, count); + }); +} } // namespace void SealedAllSum::eval_cpu( From 872fa012d853064ac7c254e579fb1377c3f15d11 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:53:32 -0700 Subject: [PATCH 15/44] [Metal] Batch per-primitive buffer retention into one handler per command buffer Port of the owner's mlx-m5u 8c4bf63fe: instead of one completion handler per primitive retaining its inputs, a command buffer collects them and one handler releases them all. Host time only; no kernel or graph changes. GLM-5.3-Flash TP2 decode on two M5 Ultra (with the larger buffer-size bound): 16.75 -> 15.92 ms a step together with the next commit; tokens identical. Co-Authored-By: Claude Opus 5.5 --- mlx/backend/metal/device.cpp | 6 ++++++ mlx/backend/metal/device.h | 15 ++++++++++++++ mlx/backend/metal/eval.cpp | 39 ++++++++++++++++++------------------ mlx/backend/metal/fence.cpp | 8 ++++---- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index f61112c89f..b32bc35514 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -531,10 +531,13 @@ void CommandEncoder::commit(std::function completion) { [&error_ = error_, wait_events = std::move(wait_events_), signal_events = std::move(signal_events_), + retained = std::move(retained_), completion = std::move(completion)](MTL::CommandBuffer* cbuf) mutable { if (completion) { completion(); } + // The buffer finished: release what its primitives kept alive. + retained.clear(); // If any of the waited event has error in it, poison the encoder. for (auto& event : wait_events) { if (error_.store_if_valid(event.load_error())) { @@ -569,6 +572,9 @@ void CommandEncoder::commit(std::function completion) { buffer_ = NS::RetainPtr(queue_->commandBufferWithUnretainedReferences()); buffer_ops_ = 0; buffer_sizes_ = 0; + // The moved-from vector is valid but unspecified: reset it explicitly. + retained_ = {}; + retained_.reserve(256); } void CommandEncoder::synchronize() { diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index f6beacea9c..92920156b2 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -108,6 +108,17 @@ class MLX_API CommandEncoder { return buffer_.get(); } + // Keep an object (array data, a fence) alive until the command buffer that + // is current now completes. Everything retained is released by the single + // completion handler commit() installs, instead of one Metal completion + // handler (an Objective-C block plus a hash set) per encoded primitive. + // A primitive that commits mid-eval (e.g. the expert-tile route's retract + // check) retains into the replacement buffer, which completes after the + // committed one on this queue, so the lifetime is never shorter. + void retain_until_completed(std::shared_ptr object) { + retained_.push_back(std::move(object)); + } + private: MTL::ComputeCommandEncoder* get_command_encoder(); @@ -151,6 +162,10 @@ class MLX_API CommandEncoder { // A map of prior command encoder outputs to their corresponding fence. std::unordered_map> prev_ce_outputs_; std::mutex outputs_mtx_; + + // Objects kept alive until the current command buffer completes + // (`retain_until_completed`); moved into its completion handler at commit. + std::vector> retained_; }; class MLX_API Device { diff --git a/mlx/backend/metal/eval.cpp b/mlx/backend/metal/eval.cpp index aac9771878..b275e1ca76 100644 --- a/mlx/backend/metal/eval.cpp +++ b/mlx/backend/metal/eval.cpp @@ -44,33 +44,32 @@ void eval(array& arr) { encoder.get_command_buffer(), arr.primitive()); arr.primitive().eval_gpu(arr.inputs(), outputs); } - std::unordered_set> buffers; + // Keep the inputs and siblings alive until the command buffer completes; + // the output is skipped when an input donated its buffer to it. Retention + // is batched per command buffer (`retain_until_completed`): a hash set plus + // a Metal completion handler per primitive dominated host-side encode time + // for decode-sized kernels. Retained AFTER eval_gpu, into the encoder's + // current buffer: a primitive that synchronizes mid-eval (e.g. the + // expert-tile route's descriptor retract check) commits and replaces the + // buffer, and the current one holds the tail of this primitive's work, + // which is exactly what the inputs must outlive. A duplicate input is + // retained twice, which only costs one more reference. + auto* out_data = arr.data_shared_ptr().get(); for (auto& in : arr.inputs()) { - buffers.insert(in.data_shared_ptr()); - } - for (auto& s : arr.siblings()) { - buffers.insert(s.data_shared_ptr()); + if (in.data_shared_ptr().get() != out_data) { + encoder.retain_until_completed(in.data_shared_ptr()); + } } - // Remove the output if it was donated to by an input - if (auto it = buffers.find(arr.data_shared_ptr()); it != buffers.end()) { - buffers.erase(it); + for (auto& sib : arr.siblings()) { + if (sib.data_shared_ptr().get() != out_data) { + encoder.retain_until_completed(sib.data_shared_ptr()); + } } if (encoder.needs_commit()) { encoder.end_encoding(); scheduler::notify_new_task(s); - encoder.commit([s, buffers = std::move(buffers)]() { - scheduler::notify_task_completion(s); - }); - } else { - // Fetch the command buffer AFTER eval_gpu: primitives that synchronize - // mid-eval (e.g. the expert-tile route's descriptor retract check) - // commit and REPLACE the encoder's buffer, so a pointer captured before - // eval_gpu would be stale here — attaching the buffer-liveness handler - // to it is a use-after-free. The current buffer holds the tail of this - // primitive's work, which is exactly what the inputs must outlive. - encoder.get_command_buffer()->addCompletedHandler( - [buffers = std::move(buffers)](MTL::CommandBuffer* cbuf) {}); + encoder.commit([s]() { scheduler::notify_task_completion(s); }); } } diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 7d12724c84..77082ccb65 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -84,8 +84,8 @@ void Fence::wait(Stream stream, const array& x) { compute_encoder.set_bytes(f.count, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims); - compute_encoder.get_command_buffer()->addCompletedHandler( - [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); + // The fence buffer must outlive the pass that spins on it. + compute_encoder.retain_until_completed(fence_); } void Fence::update(Stream stream, const array& x, bool cross_device) { @@ -135,8 +135,8 @@ void Fence::update(Stream stream, const array& x, bool cross_device) { compute_encoder.set_bytes(f.count, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims); - compute_encoder.get_command_buffer()->addCompletedHandler( - [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); + // The fence buffer must outlive the pass that writes it. + compute_encoder.retain_until_completed(fence_); } } // namespace mlx::core From 5711fa5b2d44b70b0e10eadeefff6339fe7c8c33 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:53:32 -0700 Subject: [PATCH 16/44] [Metal] Cache generated custom-kernel source and library name per kernel Port of the owner's mlx-m5u 42f2dcefb: a custom kernel's generated Metal source and library name are built once per kernel and template instance instead of on every launch. Host time only. Co-Authored-By: Claude Opus 5.5 --- mlx/backend/common/metal_kernel.cpp | 107 +++++++++++++++++++++------- mlx/backend/metal/custom_kernel.cpp | 12 +++- mlx/fast_primitives.h | 8 ++- 3 files changed, 99 insertions(+), 28 deletions(-) diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index 0efb605a3b..20389b25eb 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -2,7 +2,12 @@ #include #include +#include +#include #include +#include + +#include #include "mlx/backend/common/compiled.h" #include "mlx/backend/metal/metal.h" @@ -313,6 +318,25 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( } } + // The generated source is a pure function of this kernel object (header, + // body, names, attributes, shape infos, atomic and mutable inputs: all + // fixed here) and of the per-call key built below: the template + // definition and, per input, its dtype and how it is passed (mutable, + // scalar, constant or device; a 0-d mutable input also drops its shape + // parameters). Cache the source and its Metal library name per key, so a + // repeated call neither regenerates the (often multi-KB) source nor hashes + // it again at dispatch time. Shared by every copy of the returned function. + struct GeneratedSource { + std::string source; + std::string library_name; + }; + struct SourceCache { + std::mutex mtx; + std::unordered_map> + entries; + }; + auto source_cache = std::make_shared(); + return [=, shape_infos = std::move(shape_infos), attributes = std::move(attributes)]( @@ -371,30 +395,60 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( kernel_name += get_type_string(dtype); } - std::string kernel_source = write_signature( - kernel_name, - header, - source, - input_names, - inputs, - output_names, - output_dtypes, - template_args, - attributes, - shape_infos, - atomic_outputs, - mutable_inputs); + // `kernel_name` already encodes the template hash, every dtype and the + // m/s/c passing of each input; the full template definition and the + // 0-d-ness of mutable inputs complete the key (see `SourceCache`). + std::string cache_key = kernel_name; + cache_key += '|'; + cache_key += template_def; + for (int i : mutable_inputs) { + cache_key += inputs[i].ndim() == 0 ? 'z' : 'n'; + } + std::shared_ptr generated; + { + std::lock_guard lock(source_cache->mtx); + if (auto it = source_cache->entries.find(cache_key); + it != source_cache->entries.end()) { + generated = it->second; + } + } + if (!generated) { + std::string kernel_source = write_signature( + kernel_name, + header, + source, + input_names, + inputs, + output_names, + output_dtypes, + template_args, + attributes, + shape_infos, + atomic_outputs, + mutable_inputs); - if (!template_args.empty()) { - template_def = kernel_name + template_def; - kernel_source += "\ntemplate [[host_name(\""; - kernel_source += kernel_name; - kernel_source += "\")]] [[kernel]] decltype("; - kernel_source += template_def; - kernel_source += ") "; - kernel_source += template_def; - kernel_source += ";\n"; + if (!template_args.empty()) { + auto instantiation = kernel_name + template_def; + kernel_source += "\ntemplate [[host_name(\""; + kernel_source += kernel_name; + kernel_source += "\")]] [[kernel]] decltype("; + kernel_source += instantiation; + kernel_source += ") "; + kernel_source += instantiation; + kernel_source += ";\n"; + } + // Exactly the name CustomKernel::eval_gpu derived before. + auto library_name = fmt::format( + "{}_{:x}_{}", + kernel_name, + std::hash{}(kernel_source), + compile_options.serialize()); + generated = std::make_shared( + GeneratedSource{std::move(kernel_source), std::move(library_name)}); + std::lock_guard lock(source_cache->mtx); + source_cache->entries.emplace(cache_key, generated); } + const std::string& kernel_source = generated->source; if (verbose) { std::cout << "Generated source code for `" << name << "`:" << std::endl @@ -420,7 +474,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( false, 0, compile_options.serialize(), - mutable_inputs), + mutable_inputs, + generated->library_name), inputs); } return array::make_arrays( @@ -429,7 +484,7 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::make_shared( s, std::move(kernel_name), - std::move(kernel_source), + kernel_source, grid, threadgroup, shape_infos, @@ -438,7 +493,9 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::vector{}, false, 0, - compile_options.serialize()), + compile_options.serialize(), + std::vector{}, + generated->library_name), std::move(inputs)); }; } diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 3ee8f3d029..6bb5b62e12 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -81,8 +81,16 @@ void CustomKernel::eval_gpu( checked_inputs.push_back(check_input(in)); } - std::string lib_name = fmt::format( - "{}_{:x}_{}", name_, std::hash{}(source_), compile_options_); + // Hashing the whole generated source (often tens of KB) on every dispatch + // dominated the host cost of decode-sized custom kernels; the kernel + // builder precomputes the identical name once per generated source. + std::string lib_name = library_name_.empty() + ? fmt::format( + "{}_{:x}_{}", + name_, + std::hash{}(source_), + compile_options_) + : library_name_; auto lib = d.get_library( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 0a1a945cdd..28f5ef6423 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -448,7 +448,8 @@ class CustomKernel : public Primitive { bool is_precompiled, int shared_memory, CompileOptions::Data compile_options = {}, - std::vector mutable_inputs = {}) + std::vector mutable_inputs = {}, + std::string library_name = "") : Primitive(stream), name_(std::move(name)), source_(std::move(source)), @@ -461,6 +462,7 @@ class CustomKernel : public Primitive { is_precompiled_(is_precompiled), shared_memory_(shared_memory), compile_options_(compile_options), + library_name_(std::move(library_name)), mutable_inputs_(std::move(mutable_inputs)) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) @@ -499,6 +501,10 @@ class CustomKernel : public Primitive { bool is_precompiled_; int shared_memory_; CompileOptions::Data compile_options_; + // Metal library name precomputed by `metal_kernel` (name, source hash and + // compile options); empty for kernels built elsewhere (e.g. imported + // graphs), which hash the source at dispatch as before. + std::string library_name_; protected: std::vector mutable_inputs_; From 8c6f9e772b69e0806fda1a73ff6576d080599298 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:44:38 -0700 Subject: [PATCH 17/44] [distributed] Stream the sealed all-sum in 256 KiB pieces over a two-rank JACCL exchange On a two-rank JACCL mesh, `SealedAllSum` now runs one CPU-stream task in which each 256 KiB sealed piece (its own AES-256-GCM tag) is sent as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto. Other groups (ring, TCP, more ranks) keep the v1 seal-gather-open path unchanged. - `MeshImpl::exchange` (new, `mesh_impl.h`): receives posted before any send, at most two frames in flight each way, a frame leaves only when its bytes are sealed (`ready` is polled, never blocks, so a landed receive is always copied out and reposted); no self-copy, smallest size class for the last frame, frame schedule a function of n only. - `sealed_stream.h`: piece layout (P = 256 KiB - 16, four sealed pieces per 1 MiB frame), seal lanes capped at 8 on the user-interactive queue, the add in place per piece with v1's expression and rank-0-first operand order (bit-identical results). - Security as v1: every piece is one AES-GCM box under its direction and generation key, nonce (piece, sender, counter) sealed once; the receiver derives piece count and lengths from n and P, never from the wire; the authenticated data is v1's plus P, so neither layout's piece verifies as the other's; a piece that does not open latches the codec and fails the sum, and a refused seal sends zeros so both ranks refuse in lockstep. - v1 fix: a refused seal now zeroes its frame before throwing (the following gather could otherwise send a recycled buffer's stale bytes in the clear). - C ABI: additive (`mlx_distributed_set_streamed_seal_codec`, two callback typedefs); `mlx_distributed_set_seal_codec` unchanged. Measured on two M5 Ultra over Thunderbolt 5 (GLM-5.3-Flash TP2, sealed bf16 partials, 15.7K-token prompt, 8,192-token chunks as two micro-batches): prefill 3,554 -> 3,812 tok/s, output tokens identical. A tampered piece at sealed counter 0 and at 200 is refused on both ranks, and both end without hanging. `tests/jaccl/exchange_tests.cpp` (fake verbs, real MeshImpl and streamed-sum code, stand-in keyed codec) passes under ASan/UBSan and TSan: sizes 1 B to 3 MiB, bitwise equality with v1 for fp32/bf16/fp16 over 1-65 pieces, tamper, seal failure, closed group. Co-Authored-By: Claude Opus 5.5 --- mlx/distributed/distributed_impl.h | 16 + mlx/distributed/jaccl/jaccl.cpp | 13 + mlx/distributed/jaccl/lib/jaccl/group.h | 18 + mlx/distributed/jaccl/lib/jaccl/mesh.h | 13 + mlx/distributed/jaccl/lib/jaccl/mesh_impl.h | 84 ++++ mlx/distributed/primitives.h | 8 +- mlx/distributed/sealed.cpp | 101 ++++- mlx/distributed/sealed.h | 39 +- mlx/distributed/sealed_stream.h | 293 +++++++++++++ tests/jaccl/CMakeLists.txt | 4 + tests/jaccl/exchange_tests.cpp | 457 ++++++++++++++++++++ 11 files changed, 1036 insertions(+), 10 deletions(-) create mode 100644 mlx/distributed/sealed_stream.h create mode 100644 tests/jaccl/exchange_tests.cpp diff --git a/mlx/distributed/distributed_impl.h b/mlx/distributed/distributed_impl.h index ca0f46d1be..32ac950a84 100644 --- a/mlx/distributed/distributed_impl.h +++ b/mlx/distributed/distributed_impl.h @@ -39,6 +39,22 @@ class GroupImpl { virtual void all_min(const array& input, array& output, Stream stream) = 0; virtual void sum_scatter(const array& input, array& output, Stream stream) = 0; + + // Two ranks, on the calling thread (a CPU-stream task): send n bytes while + // the peer's n bytes land in recv. ready(end) tells if send[0, end) is + // final; it is polled and must not block. arrived(end) runs when + // recv[0, end) holds the peer's bytes. Neither callback may throw. + virtual bool supports_exchange() { + return false; + } + virtual void exchange( + const char* /* send */, + char* /* recv */, + size_t /* n */, + const std::function& /* ready */, + const std::function& /* arrived */) { + throw std::runtime_error("[distributed] This group cannot exchange."); + } }; /* Define the MLX stream that the communication should happen in. */ diff --git a/mlx/distributed/jaccl/jaccl.cpp b/mlx/distributed/jaccl/jaccl.cpp index 0b95c8a561..b18c465d3e 100644 --- a/mlx/distributed/jaccl/jaccl.cpp +++ b/mlx/distributed/jaccl/jaccl.cpp @@ -88,6 +88,19 @@ class JACCLGroup : public GroupImpl { group_->end_startup_wait_budget(); } + bool supports_exchange() override { + return group_->supports_exchange(); + } + + void exchange( + const char* send, + char* recv, + size_t n, + const std::function& ready, + const std::function& arrived) override { + group_->exchange(send, recv, n, ready, arrived); + } + void all_sum(const array& input, array& output, Stream stream) override { auto in_ptr = input.data(); auto out_ptr = output.data(); diff --git a/mlx/distributed/jaccl/lib/jaccl/group.h b/mlx/distributed/jaccl/lib/jaccl/group.h index 66d160cb72..c413287f17 100644 --- a/mlx/distributed/jaccl/lib/jaccl/group.h +++ b/mlx/distributed/jaccl/lib/jaccl/group.h @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -50,6 +51,23 @@ class Group { virtual void send(const void* input, size_t n_bytes, int dst) = 0; virtual void recv(void* output, size_t n_bytes, int src) = 0; virtual void barrier() = 0; + + /** + * Two ranks: send n_bytes while the peer's n_bytes land in output. A frame + * goes out when ready(end) says input[0, end) is final; arrived(end) runs + * when output[0, end) is filled. See MeshImpl::exchange. + */ + virtual bool supports_exchange() { + return false; + } + virtual void exchange( + const char* /* input */, + char* /* output */, + size_t /* n_bytes */, + const std::function& /* ready */, + const std::function& /* arrived */) { + throw std::runtime_error("[jaccl] This group cannot exchange."); + } }; /** diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh.h b/mlx/distributed/jaccl/lib/jaccl/mesh.h index d60f01e525..2f3dde1c15 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh.h @@ -59,6 +59,19 @@ class MeshGroup : public Group { void barrier() override; + bool supports_exchange() override { + return size_ == 2; + } + + void exchange( + const char* input, + char* output, + size_t n_bytes, + const std::function& ready, + const std::function& arrived) override { + mesh_.exchange(input, output, n_bytes, ready, arrived); + } + private: template void all_reduce( diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index 682a837a43..8d4e5b0f20 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -294,6 +294,90 @@ class MeshImpl { } } + // Two ranks: send n_bytes from in_ptr while the peer's n_bytes land in + // out_ptr, with no self copy. Frame j goes out when ready(end of frame j) + // tells that its bytes are final. ready is polled between completions, so + // the receives are posted again in time. arrived(end) runs when + // out_ptr[0, end) is filled. The last frame uses the smallest buffer that + // holds it. Both ranks size each frame from n_bytes. + void exchange( + const char* in_ptr, + char* out_ptr, + int64_t n_bytes, + const std::function& ready, + const std::function& arrived) { + if (size_ != 2 || n_bytes <= 0) { + throw std::invalid_argument( + "[jaccl] An exchange needs two ranks and a nonempty message."); + } + Call call(*this, "mesh exchange"); + const int peer = 1 - rank_; + const int top = buffer_size_from_message(MAX_BUFFER_SIZE).first; + const int64_t N = int64_t(FRAME_SIZE) << top; + const int64_t frames = (n_bytes + N - 1) / N; + auto length = [&](int64_t j) { return std::min(N, n_bytes - j * N); }; + auto size_class = [&](int64_t j) { + int sz = 0; + while (sz < top && (int64_t(FRAME_SIZE) << sz) < length(j)) { + sz++; + } + return sz; + }; + constexpr int PIPELINE = MESH_PIPELINE; + constexpr int WC_NUM = 2 * PIPELINE; + + int64_t recv_posted = 0; + int64_t received = 0; + int64_t sent = 0; + int64_t send_done = 0; + bool send_busy[PIPELINE] = {}; + auto post_recv = [&]() { + recv_from(size_class(recv_posted), peer, int(recv_posted % PIPELINE)); + recv_posted++; + }; + auto post_ready_sends = [&]() { + while (sent < frames && !send_busy[sent % PIPELINE] && + ready(size_t(sent * N + length(sent)))) { + int buff = int(sent % PIPELINE); + int sz = size_class(sent); + send_buffer(sz, buff).stage_send(in_ptr + sent * N, length(sent)); + send_to(sz, peer, buff); + send_busy[buff] = true; + sent++; + } + }; + + while (recv_posted < std::min(PIPELINE, frames)) { + post_recv(); + } + post_ready_sends(); + while (received < frames || send_done < frames) { + ibv_wc wc[WC_NUM]; + int n = connections_[peer].poll(WC_NUM, wc); + call.check(wc, n); + for (int i = 0; i < n; i++) { + int work_type = wc[i].wr_id >> 16; + int buff = (wc[i].wr_id >> 8) & 0xff; + if (work_type == SEND_WR) { + send_busy[buff] = false; + send_done++; + } else { + // Receives complete in the order they were posted. + std::memcpy( + out_ptr + received * N, + recv_buffer(size_class(received), buff, peer).begin(), + length(received)); + received++; + if (recv_posted < frames) { + post_recv(); + } + arrived(size_t(std::min(n_bytes, received * N))); + } + } + post_ready_sends(); + } + } + template void sum_scatter(const T* in, T* out, int64_t count, ReduceOp reduce_op) { // Fully connected reduce scatter. diff --git a/mlx/distributed/primitives.h b/mlx/distributed/primitives.h index 1011c6fc04..f5a9b0d631 100644 --- a/mlx/distributed/primitives.h +++ b/mlx/distributed/primitives.h @@ -70,8 +70,10 @@ class AllReduce : public DistPrimitive { }; /// The sealed all-sum (`all_sum_sealed`, sealed.h): seal, all-gather the two -/// frames, open the peer's, add in rank order. `counter_` advances per -/// evaluation; both ranks evaluate the same graph in the same order. +/// frames, open the peer's, add in rank order. With a streamed codec on a +/// group that can exchange, one task does this piece by piece +/// (sealed_stream.h). `counter_` advances per evaluation; both ranks +/// evaluate the same graph in the same order. class SealedAllSum : public DistPrimitive { public: SealedAllSum(Stream stream, Group group, SealCodec codec) @@ -87,6 +89,8 @@ class SealedAllSum : public DistPrimitive { } private: + void eval_streamed(const array& in, array& out); + SealCodec codec_; static inline std::atomic counter_{0}; }; diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index d925ebddd3..9a3d60eba6 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -1,6 +1,7 @@ // Copyright © 2026 Darkbloom. #include +#include #include #include #include @@ -11,6 +12,7 @@ #include "mlx/distributed/distributed_impl.h" #include "mlx/distributed/primitives.h" #include "mlx/distributed/sealed.h" +#include "mlx/distributed/sealed_stream.h" namespace mlx::core::distributed { @@ -20,6 +22,16 @@ std::optional installed_codec; } // namespace void set_seal_codec(SealCodec codec) { + if (codec.seal != nullptr && codec.open != nullptr && + (codec.seal_piece != nullptr || codec.open_piece != nullptr)) { + if (!codec.streamed() || codec.piece_bytes < 4096 || + codec.piece_bytes > (size_t(16) << 20) || + codec.piece_bytes % 16 != 0) { + throw std::invalid_argument( + "[set_seal_codec] a streamed codec needs both piece callbacks and " + "piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]"); + } + } std::lock_guard lock(codec_mutex); if (codec.seal == nullptr || codec.open == nullptr) { installed_codec.reset(); @@ -102,6 +114,13 @@ void SealedAllSum::eval_cpu( : contiguous_copy_cpu(inputs[0], stream()); auto& out = outputs[0]; out.set_data(allocator::malloc(out.nbytes())); + if (codec_.streamed() && group().raw_group()->supports_exchange()) { + eval_streamed(in, out); + if (!inputs[0].flags().row_contiguous) { + cpu::get_command_encoder(stream()).add_temporary(in); + } + return; + } size_t n = in.nbytes(); size_t frame = n + codec_.overhead; array sealed({static_cast(frame)}, uint8, nullptr, {}); @@ -117,13 +136,19 @@ void SealedAllSum::eval_cpu( auto& encoder = cpu::get_command_encoder(stream()); encoder.set_input_array(in); encoder.set_output_array(sealed); - encoder.dispatch( - [codec, src = in.data(), dst = sealed.data(), n, counter]() { - if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { - throw std::runtime_error( - "[all_sum_sealed] the codec refused to seal a partial"); - } - }); + encoder.dispatch([codec, + src = in.data(), + dst = sealed.data(), + n, + frame, + counter]() { + if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { + // The gather after this task still runs: never send stale bytes. + std::memset(dst, 0, frame); + throw std::runtime_error( + "[all_sum_sealed] the codec refused to seal a partial"); + } + }); distributed::detail::all_gather(group(), sealed, gathered, stream()); encoder.set_input_array(gathered); encoder.set_output_array(out); @@ -178,6 +203,68 @@ void SealedAllSum::eval_cpu( } } +// One CPU-stream task that seals, sends, opens and adds piece by piece +// (sealed_stream.h). Each rank receives only the peer's frame. +void SealedAllSum::eval_streamed(const array& in, array& out) { + detail::PieceLayout layout(in.nbytes(), codec_.piece_bytes); + if (layout.count > 0xFFFF) { + throw std::invalid_argument( + "[all_sum_sealed] a partial needs more than 65,535 sealed pieces"); + } + detail::AddPieceFn add; + switch (in.dtype()) { + case float32: + add = detail::add_piece; + break; + case bfloat16: + add = detail::add_piece; + break; + case float16: + add = detail::add_piece; + break; + default: + throw std::runtime_error("[all_sum_sealed] unsupported dtype"); + } + array sealed({static_cast(layout.frame())}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(layout.frame())); + array received({static_cast(layout.frame())}, uint8, nullptr, {}); + received.set_data(allocator::malloc(layout.frame())); + + int rank = group().rank(); + uint64_t counter = counter_++; + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(out); + encoder.dispatch([codec = codec_, + layout, + counter, + rank, + add, + group = group().raw_group(), + src = in.data(), + dst = out.data(), + mine = sealed.data(), + theirs = received.data()]() { + detail::StreamedSum sum( + codec, layout, counter, rank, src, dst, mine, theirs, add); + bool ok = sum.run([&group]( + const char* send, + char* recv, + size_t n, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + group->exchange(send, recv, n, ready, arrived); + }); + if (!ok) { + throw std::runtime_error( + "[all_sum_sealed] a piece did not seal or a peer piece did not " + "authenticate: refused"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(received); +} + void SealedAllSum::eval_gpu(const std::vector&, std::vector&) { throw std::runtime_error( "[SealedAllSum::eval_gpu] has no GPU implementation."); diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h index 15093d6aef..cc5deb424e 100644 --- a/mlx/distributed/sealed.h +++ b/mlx/distributed/sealed.h @@ -38,15 +38,52 @@ using OpenFn = int (*)( uint64_t counter, int peer); +// The streamed frame: piece k holds plaintext +// [k * piece_bytes, min(n, (k + 1) * piece_bytes)) as its ciphertext, then a +// kSealTagBytes tag; the pieces are in order. seal_piece writes +// len + kSealTagBytes bytes; open_piece reads them and writes len bytes. +// Calls for one counter can run at the same time, on any thread, in any +// order; `pieces` and `total` (n) are the same for each piece of a counter. +// Both return 0 on success. +constexpr size_t kSealTagBytes = 16; +using SealPieceFn = int (*)( + void* ctx, + const void* plaintext, + size_t len, + void* sealed, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total); +using OpenPieceFn = int (*)( + void* ctx, + const void* sealed, + size_t len, + void* plaintext, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer); + struct SealCodec { SealFn seal = nullptr; OpenFn open = nullptr; void* ctx = nullptr; size_t overhead = 0; + // Optional. A group that can exchange (two-rank JACCL mesh) then streams + // the pieces; other groups use seal and open. + SealPieceFn seal_piece = nullptr; + OpenPieceFn open_piece = nullptr; + size_t piece_bytes = 0; + bool streamed() const { + return seal_piece != nullptr && open_piece != nullptr; + } }; // Installs (or, with a null seal, removes) the process's codec. A sealed -// all-sum without a codec is refused when the graph is built. +// all-sum without a codec is refused when the graph is built. A streamed +// codec needs piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]. MLX_API void set_seal_codec(SealCodec codec); MLX_API std::optional seal_codec(); diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h new file mode 100644 index 0000000000..8d4e3aa16b --- /dev/null +++ b/mlx/distributed/sealed_stream.h @@ -0,0 +1,293 @@ +// Copyright © 2026 Darkbloom. +// +// The streamed sealed sum. Worker threads seal the pieces in order; the +// exchange sends each frame when its pieces are sealed; each peer piece is +// opened and added when its bytes land. Only the head and the tail of the +// transfer wait for crypto. + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "mlx/distributed/sealed.h" + +namespace mlx::core::distributed::detail { + +using ReadyFn = std::function; +using ArrivedFn = std::function; +// exchange(send, recv, bytes, ready, arrived): see GroupImpl::exchange. +using ExchangeFn = std::function< + void(const char*, char*, size_t, const ReadyFn&, const ArrivedFn&)>; + +// The streamed frame of an n-byte partial. +struct PieceLayout { + size_t bytes; + size_t piece; + size_t count; + PieceLayout(size_t n, size_t piece_bytes) + : bytes(n), + piece(piece_bytes), + count(std::max(1, (n + piece_bytes - 1) / piece_bytes)) {} + size_t plain(size_t k) const { + return k * piece; + } + size_t length(size_t k) const { + return std::min(piece, bytes - k * piece); + } + size_t sealed(size_t k) const { + return k * (piece + kSealTagBytes); + } + size_t sealed_end(size_t k) const { + return sealed(k) + length(k) + kSealTagBytes; + } + size_t frame() const { + return bytes + count * kSealTagBytes; + } +}; + +// `out` holds the peer's addend. It becomes rank 0's addend + rank 1's, both +// widened to float and rounded once, as the gathered path adds them. +template +void add_peer_in_rank_order( + int rank, + const T* __restrict mine, + T* __restrict out, + size_t n) { + if (rank == 0) { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast( + static_cast(mine[i]) + static_cast(out[i])); + } + } else { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast( + static_cast(out[i]) + static_cast(mine[i])); + } + } +} + +using AddPieceFn = void (*)(int rank, const char* mine, char* out, size_t len); + +template +void add_piece(int rank, const char* mine, char* out, size_t len) { + add_peer_in_rank_order( + rank, + reinterpret_cast(mine), + reinterpret_cast(out), + len / sizeof(T)); +} + +// MLX_SEALED_QOS=0 keeps the caller's QoS (as the gathered path does). +inline bool raise_qos() { + static const bool on = [] { + const char* value = std::getenv("MLX_SEALED_QOS"); + return value == nullptr || std::strcmp(value, "0") != 0; + }(); + return on; +} + +// Threads that seal at the same time (MLX_SEALED_SEAL_LANES, 1..64). Eight +// stay ahead of the wire and leave cores to the GPU driver and the opens. +inline size_t seal_lanes() { + static const size_t lanes = [] { + const char* value = std::getenv("MLX_SEALED_SEAL_LANES"); + long parsed = value ? std::strtol(value, nullptr, 10) : 0; + return parsed >= 1 && parsed <= 64 ? size_t(parsed) : size_t(8); + }(); + return lanes; +} + +// One streamed sealed sum, run on the calling thread (a CPU-stream task). +class StreamedSum { + public: + StreamedSum( + const SealCodec& codec, + const PieceLayout& layout, + uint64_t counter, + int rank, + const char* mine, + char* out, + char* sealed, + char* received, + AddPieceFn add) + : codec_(codec), + layout_(layout), + counter_(counter), + rank_(rank), + mine_(mine), + out_(out), + sealed_(sealed), + received_(received), + add_(add), + ready_(std::make_unique[]>(layout.count)) {} + + // False when a piece did not seal or a peer piece did not open. No worker + // runs after this returns or throws. + bool run(const ExchangeFn& exchange) { + if (layout_.count == 1) { + // One piece (decode): no worker hand-off. + seal(0); + exchange( + sealed_, + received_, + layout_.frame(), + [](size_t) { return true; }, + [this](size_t end) { + if (end == layout_.frame()) { + open_and_add(0); + } + }); + return !failed_.load(); + } + QosOverride boost; + Workers workers; + StreamedSum* self = this; + size_t lanes = std::min(layout_.count, seal_lanes()); + for (size_t i = 0; i < lanes; ++i) { + workers.async(^{ + self->seal_in_order(); + }); + } + size_t sealed_prefix = 0; + size_t dispatched = 0; + exchange( + sealed_, + received_, + layout_.frame(), + [&](size_t end) { + while (sealed_prefix < layout_.count && + ready_[sealed_prefix].load(std::memory_order_acquire)) { + ++sealed_prefix; + } + return sealed_prefix == layout_.count || + layout_.sealed(sealed_prefix) >= end; + }, + [&](size_t end) { + for (; dispatched < layout_.count && + layout_.sealed_end(dispatched) <= end; + ++dispatched) { + size_t k = dispatched; + workers.async(^{ + self->open_and_add(k); + }); + } + }); + workers.wait(); + return !failed_.load(); + } + + private: + // Waits for every block before the frames and `out` can be released. + class Workers { + public: + Workers() + : group_(dispatch_group_create()), + queue_(dispatch_get_global_queue( + raise_qos() ? QOS_CLASS_USER_INTERACTIVE : qos_class_self(), + 0)) {} + Workers(const Workers&) = delete; + Workers& operator=(const Workers&) = delete; + ~Workers() { + wait(); + dispatch_release(group_); + } + void async(dispatch_block_t block) { + dispatch_group_async(group_, queue_, block); + } + void wait() { + dispatch_group_wait(group_, DISPATCH_TIME_FOREVER); + } + + private: + dispatch_group_t group_; + dispatch_queue_t queue_; + }; + + // The polling thread runs at the workers' QoS while they run. + class QosOverride { + public: + QosOverride() + : token_( + raise_qos() ? pthread_override_qos_class_start_np( + pthread_self(), QOS_CLASS_USER_INTERACTIVE, 0) + : nullptr) {} + QosOverride(const QosOverride&) = delete; + QosOverride& operator=(const QosOverride&) = delete; + ~QosOverride() { + if (token_ != nullptr) { + pthread_override_qos_class_end_np(token_); + } + } + + private: + pthread_override_t token_; + }; + + void seal_in_order() { + for (size_t k; (k = next_seal_.fetch_add(1)) < layout_.count;) { + seal(k); + } + } + + void seal(size_t k) { + char* dst = sealed_ + layout_.sealed(k); + size_t len = layout_.length(k); + if (codec_.seal_piece( + codec_.ctx, + mine_ + layout_.plain(k), + len, + dst, + counter_, + static_cast(k), + static_cast(layout_.count), + layout_.bytes) != 0) { + // Never send stale bytes. The peer refuses the zero piece. + std::memset(dst, 0, len + kSealTagBytes); + failed_.store(true); + } + ready_[k].store(true, std::memory_order_release); + } + + void open_and_add(size_t k) { + char* dst = out_ + layout_.plain(k); + size_t len = layout_.length(k); + if (codec_.open_piece( + codec_.ctx, + received_ + layout_.sealed(k), + len, + dst, + counter_, + static_cast(k), + static_cast(layout_.count), + layout_.bytes, + 1 - rank_) != 0) { + failed_.store(true); + return; + } + add_(rank_, mine_ + layout_.plain(k), dst, len); + } + + const SealCodec codec_; + const PieceLayout layout_; + const uint64_t counter_; + const int rank_; + const char* const mine_; + char* const out_; + char* const sealed_; + char* const received_; + const AddPieceFn add_; + std::unique_ptr[]> ready_; + std::atomic next_seal_{0}; + std::atomic failed_{false}; +}; + +} // namespace mlx::core::distributed::detail diff --git a/tests/jaccl/CMakeLists.txt b/tests/jaccl/CMakeLists.txt index b003dd4642..75324951e9 100644 --- a/tests/jaccl/CMakeLists.txt +++ b/tests/jaccl/CMakeLists.txt @@ -30,6 +30,10 @@ jaccl_test(startup_wait_budget_tests) jaccl_test(startup_wait_budget_group_tests) jaccl_test(startup_wait_budget_api_tests) target_include_directories(startup_wait_budget_api_tests PRIVATE ../..) +jaccl_test(exchange_tests) +target_include_directories(exchange_tests PRIVATE ../..) +add_test(NAME exchange COMMAND exchange_tests) +set_tests_properties(exchange PROPERTIES ENVIRONMENT "JACCL_TIMEOUT_ACTION=throw") add_test(NAME startup_wait_budget_api COMMAND startup_wait_budget_api_tests) add_test(NAME startup_wait_budget_groups COMMAND startup_wait_budget_group_tests) diff --git a/tests/jaccl/exchange_tests.cpp b/tests/jaccl/exchange_tests.cpp new file mode 100644 index 0000000000..d579062d04 --- /dev/null +++ b/tests/jaccl/exchange_tests.cpp @@ -0,0 +1,457 @@ +// Copyright © 2026 Darkbloom. + +// Tests of the two-rank mesh exchange and of the streamed sealed sum with +// simulated verbs. The codec here is a stand-in: a keyed XOR stream and a +// 16-byte keyed hash per piece. It finds changed bytes, wrong pieces and wrong +// counters, as the real AES-GCM codec does; it is not cryptography. + +#include +#include +#include + +#include "fixture.h" +#include "mlx/distributed/sealed_stream.h" + +namespace { + +using mlx::core::bfloat16_t; +using mlx::core::float16_t; +namespace sealed = mlx::core::distributed; +namespace detail = mlx::core::distributed::detail; + +constexpr int64_t kFrame = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + +int64_t class_bytes(int64_t length) { + int64_t bytes = FRAME_SIZE; + while (bytes < length && bytes < kFrame) { + bytes *= 2; + } + return bytes; +} + +std::vector pattern(int64_t n, int seed) { + std::vector v(n); + std::mt19937 random(seed); + for (auto& c : v) { + c = char(random()); + } + return v; +} + +// Frames: full ones, then the last in the smallest buffer that holds it. +void exchange_frames(const std::vector& frames, int64_t n) { + const int64_t count = (n + kFrame - 1) / kFrame; + fixture::require(int64_t(frames.size()) == count, "Unexpected frame count"); + for (int64_t j = 0; j < count; ++j) { + const int64_t length = std::min(kFrame, n - j * kFrame); + fixture::require( + int64_t(frames[j].bytes.size()) == class_bytes(length), + "Unexpected frame size class"); + fixture::zero_tail(frames[j], length); + } +} + +void exchange_sizes() { + for (int64_t n : + {int64_t(1), + int64_t(16), + int64_t(4096), + int64_t(4097), + int64_t(8208), + kFrame, + kFrame + 1, + 2 * kFrame, + 3 * kFrame + 2064}) { + fixture::MeshPair pair; + std::array, 2> input{pattern(n, 1), pattern(n, 2)}; + std::array, 2> output{ + std::vector(n + 1, 0x29), std::vector(n + 1, 0x29)}; + std::array, 2> arrived; + auto run = [&](int rank) { + // Each frame is refused twice before it is ready. + int polls = 0; + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [&](size_t) { return ++polls % 3 == 0; }, + [&, rank](size_t end) { arrived[rank].push_back(end); }); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + for (int rank = 0; rank < 2; ++rank) { + const auto& peer = input[1 - rank]; + fixture::require( + std::equal(peer.begin(), peer.end(), output[rank].begin()) && + output[rank].back() == 0x29, + "Exchange changed the peer's bytes or wrote past the end"); + const auto& ends = arrived[rank]; + fixture::require( + !ends.empty() && ends.back() == size_t(n) && + std::is_sorted(ends.begin(), ends.end()) && + std::adjacent_find(ends.begin(), ends.end()) == ends.end(), + "arrived() must report increasing ends up to the message size"); + exchange_frames(fixture::selected(pair.fabric, rank, rank, 0), n); + } + pair.fabric.require_drained(); + } +} + +// A frame leaves only when ready() says its bytes are final. +void exchange_waits_for_ready() { + const int64_t n = 5 * kFrame + 100; + fixture::MeshPair pair; + pair.fabric.idle_wait = std::chrono::milliseconds(0); + std::array, 2> final{pattern(n, 3), pattern(n, 4)}; + std::array, 2> input{ + std::vector(n, char(fixture::sentinel)), + std::vector(n, char(fixture::sentinel))}; + std::array, 2> output{ + std::vector(n), std::vector(n)}; + std::array, 2> written{0, 0}; + auto run = [&](int rank) { + std::thread writer([&, rank] { + for (int64_t at = 0; at < n; at += 300000) { + std::this_thread::sleep_for(std::chrono::microseconds(200)); + int64_t end = std::min(n, at + 300000); + std::copy( + final[rank].begin() + at, + final[rank].begin() + end, + input[rank].begin() + at); + written[rank].store(end, std::memory_order_release); + } + }); + try { + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [&, rank](size_t end) { + return written[rank].load(std::memory_order_acquire) >= end; + }, + [](size_t) {}); + } catch (...) { + writer.join(); + throw; + } + writer.join(); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + fixture::require( + output[0] == final[1] && output[1] == final[0], + "A frame left before its bytes were final"); + pair.fabric.require_drained(); +} + +// A failed completion closes the group: the call throws, later calls refuse. +void exchange_failure() { + const int64_t n = 3 * kFrame; + fixture::MeshPair pair; + pair.fabric.expire_after(std::chrono::milliseconds(1000)); + fixture::endpoint(pair.links[1][0]).fault.fail_receive = 1; + std::array, 2> input{pattern(n, 5), pattern(n, 6)}; + std::array, 2> output{ + std::vector(n), std::vector(n)}; + std::array errors; + auto run = [&](int rank) { + try { + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [](size_t) { return true; }, + [](size_t) {}); + } catch (const std::exception& error) { + errors[rank] = error.what(); + } + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + fixture::require( + errors[1].find("mesh exchange") != std::string::npos && + errors[1].find("failed with status") != std::string::npos, + "A failed completion must fail the exchange"); + std::string later; + try { + pair.nodes[1]->exchange( + input[1].data(), + output[1].data(), + 16, + [](size_t) { return true; }, + [](size_t) {}); + } catch (const std::exception& error) { + later = error.what(); + } + fixture::require( + later.find("closed") != std::string::npos, + "A closed group must refuse a later exchange"); +} + +// The stand-in codec. +struct Codec { + int rank; + std::atomic refused{false}; + int64_t refuse_seal = -1; + int64_t tamper = -1; + bool jitter = false; + + static uint64_t mix(uint64_t x) { + x += 0x9e3779b97f4a7c15ull; + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull; + x = (x ^ (x >> 27)) * 0x94d049bb133111ebull; + return x ^ (x >> 31); + } + static uint64_t key(uint64_t counter, int sender, uint32_t piece) { + return mix(counter * 0x10001 ^ uint64_t(sender) << 60 ^ uint64_t(piece)); + } + static void + crypt(const char* in, char* out, size_t len, uint64_t key) { + for (size_t i = 0; i < len; ++i) { + out[i] = char(in[i] ^ char(mix(key ^ (i / 8)) >> (8 * (i % 8)))); + } + } + static void tag( + const char* ct, + size_t len, + uint64_t key, + uint32_t pieces, + size_t total, + char* out) { + uint64_t a = mix(key ^ pieces), b = mix(key ^ total ^ 0x5555); + for (size_t i = 0; i < len; ++i) { + a = mix(a ^ uint8_t(ct[i])); + b = b * 0x100000001b3ull ^ uint8_t(ct[i]); + } + std::memcpy(out, &a, 8); + std::memcpy(out + 8, &b, 8); + } + + static int seal( + void* ctx, + const void* plaintext, + size_t len, + void* sealed, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total) { + auto& self = *static_cast(ctx); + if (self.refused || int64_t(piece) == self.refuse_seal) { + return 1; + } + if (self.jitter) { + std::this_thread::sleep_for(std::chrono::microseconds(piece % 5 * 40)); + } + uint64_t k = key(counter, self.rank, piece); + auto out = static_cast(sealed); + crypt(static_cast(plaintext), out, len, k); + tag(out, len, k, pieces, total, out + len); + if (int64_t(piece) == self.tamper) { + out[len / 2] ^= 1; + } + return 0; + } + + static int open( + void* ctx, + const void* sealed, + size_t len, + void* plaintext, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer) { + auto& self = *static_cast(ctx); + if (self.refused || peer != 1 - self.rank) { + return 1; + } + uint64_t k = key(counter, peer, piece); + auto in = static_cast(sealed); + char expected[sealed::kSealTagBytes]; + tag(in, len, k, pieces, total, expected); + if (std::memcmp(expected, in + len, sizeof(expected)) != 0) { + self.refused = true; + return 1; + } + crypt(in, static_cast(plaintext), len, k); + return 0; + } + + sealed::SealCodec codec(size_t piece_bytes) { + sealed::SealCodec c; + c.seal_piece = seal; + c.open_piece = open; + c.ctx = this; + c.piece_bytes = piece_bytes; + return c; + } +}; + +struct SumResult { + std::array ok{}; + std::array, 2> out; + std::array, 2> partial; +}; + +template +SumResult streamed_sum( + fixture::MeshPair& pair, + std::array& codecs, + size_t elements, + size_t piece_bytes, + uint64_t counter) { + SumResult r; + const size_t n = elements * sizeof(T); + detail::PieceLayout layout(n, piece_bytes); + auto run = [&](int rank) { + r.partial[rank] = pattern(n, 10 + rank); + r.out[rank].assign(n, char(fixture::sentinel)); + // Stale bytes, as a reused allocation can hold. + std::vector mine(layout.frame(), char(fixture::sentinel)); + std::vector theirs(layout.frame(), char(fixture::sentinel)); + detail::StreamedSum sum( + codecs[rank].codec(piece_bytes), + layout, + counter, + rank, + r.partial[rank].data(), + r.out[rank].data(), + mine.data(), + theirs.data(), + detail::add_piece); + r.ok[rank] = sum.run([&, rank]( + const char* send, + char* recv, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + pair.nodes[rank]->exchange(send, recv, bytes, ready, arrived); + }); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + pair.fabric.require_drained(); + return r; +} + +// The gathered path's sum: rank 0's addend + rank 1's, widened, rounded once. +template +std::vector reference(const SumResult& r) { + std::vector sum(r.partial[0].size()); + auto a = reinterpret_cast(r.partial[0].data()); + auto b = reinterpret_cast(r.partial[1].data()); + auto out = reinterpret_cast(sum.data()); + for (size_t i = 0; i < sum.size() / sizeof(T); ++i) { + out[i] = static_cast(static_cast(a[i]) + static_cast(b[i])); + } + return sum; +} + +template +void identical(size_t elements, size_t piece_bytes, bool jitter) { + fixture::MeshPair pair; + pair.fabric.idle_wait = std::chrono::milliseconds(0); + std::array codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].jitter = codecs[1].jitter = jitter; + auto r = streamed_sum(pair, codecs, elements, piece_bytes, 7); + auto expected = reference(r); + fixture::require(r.ok[0] && r.ok[1], "A streamed sum was refused"); + fixture::require( + r.out[0] == expected && r.out[1] == expected, + "The streamed sum differs from the gathered sum, bit for bit"); +} + +void streamed_sum_identical() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + identical(4096, piece, false); // decode: one piece + identical(4096, piece, false); + identical(2048 * 1024, piece, false); // 4 MiB, 17 pieces + identical(2048 * 1024, piece, true); + identical(1 << 20, 100000, true); // pieces that straddle frames + identical(4096 * 2048, piece, false); // 16 MiB, 65 pieces +} + +void streamed_sum_tamper() { + fixture::MeshPair pair; + std::array codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].tamper = 5; + auto r = streamed_sum( + pair, codecs, 1 << 20, (256 << 10) - sealed::kSealTagBytes, 9); + fixture::require( + !r.ok[1] && codecs[1].refused, + "A changed byte in a peer piece must refuse the sum"); +} + +void streamed_sum_seal_failure() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + fixture::MeshPair pair; + std::array codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].refuse_seal = 3; + auto r = streamed_sum(pair, codecs, 1 << 20, piece, 11); + fixture::require( + !r.ok[0] && !r.ok[1], "A piece that did not seal must fail both ranks"); + // The piece that did not seal went out as zeros, not as stale bytes. + std::vector wire; + for (const auto& f : fixture::selected(pair.fabric, 0, 0, 0)) { + wire.insert(wire.end(), f.bytes.begin(), f.bytes.end()); + } + detail::PieceLayout layout(size_t(1 << 20) * sizeof(float), piece); + fixture::require( + std::all_of( + wire.begin() + layout.sealed(3), + wire.begin() + layout.sealed_end(3), + [](char c) { return c == 0; }), + "A piece that did not seal must cross as zeros"); +} + +void piece_layout() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + detail::PieceLayout bf16(size_t(16) << 20, piece); + fixture::require( + bf16.count == 65 && bf16.sealed(4) == size_t(kFrame) && + bf16.frame() == (size_t(16) << 20) + 65 * 16, + "Four sealed pieces fill each 1 MiB frame"); + detail::PieceLayout decode(8192, piece); + fixture::require( + decode.count == 1 && decode.frame() == 8208, "A decode sum is one piece"); + detail::PieceLayout empty(0, piece); + fixture::require( + empty.count == 1 && empty.length(0) == 0 && empty.frame() == 16, + "An empty partial is one empty piece"); +} + +bool group(void (*check)(), const char* name) { + try { + check(); + std::cout << "PASS " << name << '\n'; + return true; + } catch (const std::exception& error) { + std::cout << "FAIL " << name << ": " << error.what() << '\n'; + return false; + } +} + +} // namespace + +int main() { + bool passed = group(piece_layout, "streamed piece layout"); + passed &= group(exchange_sizes, "exchange sizes, tail class, arrived ends"); + passed &= group(exchange_waits_for_ready, "exchange sends only ready bytes"); + passed &= group( + streamed_sum_identical, "streamed sum bit-identical to gathered sum"); + passed &= group(streamed_sum_tamper, "streamed sum refuses a changed byte"); + passed &= group( + streamed_sum_seal_failure, "streamed sum seal failure sends zeros"); + passed &= group(exchange_failure, "exchange failure closes the group"); + const auto& ledger = fixture::ledger(); + if (ledger.queue_pairs != 0 || ledger.completion_queues != 0 || + ledger.regions != 0) { + std::cout << "FAIL fake verbs objects remain after the checks\n"; + passed = false; + } + return passed ? 0 : 1; +} From 6034a788fc8bd3f8e5757a99704d7fd0b46aab92 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 18/44] [Metal] Opt-in fused coherent fence update for CPU-stream inputs With `MLX_METAL_FUSED_FENCE_UPDATE=1` (and `MLX_METAL_FAST_SYNCH=1`), the `input_coherent` rewrite, the system fence and `fence_update` become one dispatch (`fence_update_coherent`): every word of the partial still gets a coherent store and a system fence before the timestamp; larger inputs use a monotonic arrival count. Off by default; with it off the dispatch sequence is today's. Synchronization only: outputs are unchanged (GLM-5.3-Flash TP2 on two M5 Ultra: 256 tokens identical, no hangs). Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/environment_variables.rst | 6 +++ fork.yaml | 14 +++++++ mlx/backend/metal/fence.cpp | 36 ++++++++++++++++- mlx/backend/metal/kernels/fence.metal | 49 ++++++++++++++++++++++++ mlx/utils.h | 6 +++ 5 files changed, 110 insertions(+), 1 deletion(-) diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index ec537b8b2f..62c206c1b8 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -114,6 +114,12 @@ 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_FUSED_FENCE_UPDATE + + With ``MLX_METAL_FAST_SYNCH=1``, make a GPU array visible to the CPU with + one dispatch instead of two: the coherent rewrite of the array and the + fence timestamp. The default is ``0``. + Advanced tuning --------------- diff --git a/fork.yaml b/fork.yaml index 5370fa1e43..03cc374120 100644 --- a/fork.yaml +++ b/fork.yaml @@ -290,6 +290,20 @@ def: - "mlx/distributed/primitives.h" - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" + - title: "Fused cross-device fence update" + description: | + Opt-in (`MLX_METAL_FUSED_FENCE_UPDATE=1`, fast synch only). A GPU array that the CPU + reads in the same eval is made coherent and its fence timestamp is written in one + dispatch (`fence_update_coherent`) instead of `input_coherent` then `fence_update`. + Every word is still rewritten with system-coherent stores before a system-scope fence. + The last threadgroup to finish writes the timestamp. The fence buffer carries an + arrival count that only increases, so an unfinished earlier dispatch can delay a + timestamp but cannot release it early. Synchronization only: results do not change. + globs: + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/metal/kernels/fence.metal" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 77082ccb65..a329297d3e 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -18,9 +18,11 @@ struct FenceImpl { if (!use_fast) { event = std::make_unique(stream); } else { - auto buf = allocator::malloc(sizeof(uint32_t)).ptr(); + // The timestamp, then the fence_update_coherent arrival count. + auto buf = allocator::malloc(2 * sizeof(uint32_t)).ptr(); fence = static_cast(buf); cpu_value()[0] = 0; + cpu_value()[1] = 0; } } @@ -31,6 +33,8 @@ struct FenceImpl { } bool use_fast{false}; uint32_t count{0}; + // Threadgroups that fence_update_coherent counted in (mod 2^32). + uint32_t arrivals{0}; void* fence; std::unique_ptr event; @@ -109,6 +113,36 @@ void Fence::update(Stream stream, const array& x, bool cross_device) { auto& d = metal::device(stream.device); auto& compute_encoder = metal::get_command_encoder(stream); + if (cross_device && env::metal_fused_fence_update()) { + uint32_t words = (x.data_size() * x.itemsize() + sizeof(uint32_t) - 1) / + sizeof(uint32_t); + constexpr uint32_t threads = 1024; + constexpr uint32_t words_per_group = threads * 8; + uint32_t groups = + std::max(1, (words + words_per_group - 1) / words_per_group); + uint32_t target = 0; + if (groups > 1) { + f.arrivals += groups; + target = f.arrivals; + } + auto kernel = d.get_kernel("fence_update_coherent"); + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(x, 0); + compute_encoder.set_bytes(words, 1); + auto buf = static_cast(f.fence); + compute_encoder.set_buffer(buf, 2); + compute_encoder.set_bytes(f.count, 3); + compute_encoder.set_buffer(buf, 4, sizeof(uint32_t)); + compute_encoder.set_bytes(target, 5); + // After every earlier kernel, as fence_update. This also keeps two + // updates of this fence from overlapping, which `arrivals` requires. + compute_encoder.barrier(); + compute_encoder.dispatch_threadgroups( + MTL::Size(groups, 1, 1), MTL::Size(threads, 1, 1)); + compute_encoder.retain_until_completed(fence_); + return; + } + // Launch input visibility kernels if (cross_device) { auto kernel = d.get_kernel("input_coherent"); diff --git a/mlx/backend/metal/kernels/fence.metal b/mlx/backend/metal/kernels/fence.metal index cd5f9016b9..44e5b29dc0 100644 --- a/mlx/backend/metal/kernels/fence.metal +++ b/mlx/backend/metal/kernels/fence.metal @@ -36,6 +36,55 @@ constexpr constant metal::thread_scope thread_scope_system = metal::thread_scope_system); } +// input_coherent and fence_update in one dispatch. The last threadgroup to +// finish its words writes the timestamp. `arrivals` only increases: this +// dispatch moves it from target - groups to target (mod 2^32), so an +// unfinished earlier dispatch can stop the timestamp but never release it +// early. One threadgroup does not use `arrivals`. +[[kernel]] void fence_update_coherent( + volatile coherent(system) device uint* input [[buffer(0)]], + const constant uint& size [[buffer(1)]], + volatile coherent(system) device uint* timestamp [[buffer(2)]], + constant uint& value [[buffer(3)]], + device metal::atomic_uint* arrivals [[buffer(4)]], + constant uint& target [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], + uint groups [[threadgroups_per_grid]], + uint index [[thread_index_in_threadgroup]], + uint threads [[threads_per_threadgroup]]) { + for (uint i = group * threads + index; i < size; i += groups * threads) { + input[i] = input[i]; + } + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + metal::threadgroup_barrier(metal::mem_flags::mem_device); + if (index != 0) { + return; + } + if (groups > 1) { + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + uint previous = metal::atomic_fetch_add_explicit( + arrivals, 1u, metal::memory_order_relaxed); + if (previous + 1u != target) { + return; + } + } + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + timestamp[0] = value; + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); +} + // single thread kernel to spin wait for timestamp value [[kernel]] void fence_wait( volatile coherent(system) device uint* timestamp [[buffer(0)]], diff --git a/mlx/utils.h b/mlx/utils.h index 0c62ba30d9..59372483d5 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -211,6 +211,12 @@ inline bool metal_fast_synch() { return metal_fast_synch; } +// A cross-device fast fence update in one dispatch (fence_update_coherent). +inline bool metal_fused_fence_update() { + static bool fused = get_var("MLX_METAL_FUSED_FENCE_UPDATE", 0); + return fused; +} + inline bool enable_tf32() { static bool enable_tf32_ = get_var("MLX_ENABLE_TF32", 1); return enable_tf32_; From a7d4079fdeba094cf8bddcbdfffd3590adb9bc4f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 19/44] [Metal] Opt-in fenced inputs for custom kernels With `MLX_METAL_FENCED_INPUTS=1` (needs fast synch), a custom kernel can declare an input produced by a CPU-stream collective as fenced: thread 0 of each threadgroup waits on the fence before reading it (`MLX_FENCED_INPUT_WAIT`), and MLX skips the separate `fence_wait` dispatch. The pass still waits on every pending pass first (`wait_for_all_pending`, the ordering that fixed the fast-synch deadlock), plus a barrier before the kernel. Falls back to `fence_wait` when the input needs a copy, another GPU stream feeds the CPU in the same eval, or the graph is exported. Off by default; outputs are unchanged (tokens identical on the GLM TP2 pair). Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/environment_variables.rst | 7 ++ fork.yaml | 25 +++++ mlx/backend/common/metal_kernel.cpp | 134 ++++++++++++++++++++++- mlx/backend/cuda/fence.cpp | 4 + mlx/backend/metal/custom_kernel.cpp | 35 ++++++ mlx/backend/metal/fence.cpp | 106 ++++++++++++++---- mlx/backend/metal/fenced_input.h | 32 ++++++ mlx/backend/no_gpu/fence.cpp | 4 + mlx/fast.h | 17 +++ mlx/fast_primitives.h | 19 +++- mlx/fence.h | 5 + mlx/transforms.cpp | 18 ++- mlx/utils.h | 6 + 13 files changed, 381 insertions(+), 31 deletions(-) create mode 100644 mlx/backend/metal/fenced_input.h diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 62c206c1b8..80d1c1b544 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -120,6 +120,13 @@ Metal one dispatch instead of two: the coherent rewrite of the array and the fence timestamp. The default is ``0``. +.. envvar:: MLX_METAL_FENCED_INPUTS + + With ``MLX_METAL_FAST_SYNCH=1``, a custom kernel made with + ``metal_kernel_with_fenced_inputs`` waits itself for a fenced input that a + CPU stream makes in the same evaluation, and MLX does not encode a separate + fence wait for that input. The default is ``0``. + Advanced tuning --------------- diff --git a/fork.yaml b/fork.yaml index 03cc374120..9383f7169c 100644 --- a/fork.yaml +++ b/fork.yaml @@ -304,6 +304,31 @@ def: - "mlx/backend/metal/kernels/fence.metal" - "mlx/utils.h" - "docs/src/usage/environment_variables.rst" + - title: "Fenced custom-kernel inputs" + description: | + Opt-in (`MLX_METAL_FENCED_INPUTS=1`, fast synch only). `metal_kernel_with_fenced_inputs` + declares inputs that can come from a CPU stream in the same eval, such as a CPU-stream + all-sum. The source calls `MLX_FENCED_INPUT_WAIT(name)` before it reads such an input. + MLX then gives the CPU fence and its count to the kernel instead of a `fence_wait` + dispatch, and thread 0 of each threadgroup spins on it. The kernel starts after every + pass and kernel encoded before it (`wait_for_all_pending` and a barrier), as the + `fence_wait` pass does, so the CPU work it waits for never waits for it. MLX keeps the + separate wait when the input is copied first, when another GPU stream feeds the CPU + in the same eval, and while exporting. The declaration is not part of the exported + schema. Synchronization only: results do not change. + globs: + - "mlx/fence.h" + - "mlx/transforms.cpp" + - "mlx/fast.h" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/metal/fenced_input.h" + - "mlx/backend/no_gpu/fence.cpp" + - "mlx/backend/cuda/fence.cpp" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index 20389b25eb..8bc86e600b 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -55,6 +55,52 @@ Stream resolve_metal_kernel_stream(StreamOrDevice s) { return Stream(-1, Device::gpu); } +// MLX_FENCED_INPUT_WAIT(name): thread 0 of each threadgroup spins until the +// CPU fence reaches the count, as fence_wait does. A count of 0 does not wait. +constexpr const char* fenced_input_wait = R"( +#pragma METAL internals : enable +#ifndef __METAL_MEMORY_SCOPE_SYSTEM__ +#define __METAL_MEMORY_SCOPE_SYSTEM__ 3 +#endif +inline void mlx_fenced_input_wait( + volatile coherent(system) device uint* fence, + uint count, + uint index) { + constexpr metal::thread_scope scope = + static_cast(__METAL_MEMORY_SCOPE_SYSTEM__); + if (count == 0) { + return; + } + if (index == 0) { + while (true) { + metal::atomic_thread_fence( + metal::mem_flags::mem_device, metal::memory_order_seq_cst, scope); + if (fence[0] >= count) { + break; + } + } + } + metal::threadgroup_barrier(metal::mem_flags::mem_device); + metal::atomic_thread_fence( + metal::mem_flags::mem_device, metal::memory_order_seq_cst, scope); +} +#define MLX_FENCED_INPUT_WAIT(name) mlx_fenced_input_wait( \ + name##_fence, name##_fence_count, thread_index_in_threadgroup) +)"; + +constexpr const char* fenced_input_no_wait = + "\n#define MLX_FENCED_INPUT_WAIT(name) ((void)0)\n"; + +bool fenced_inputs_enabled() { +#ifdef __APPLE__ + if (__builtin_available(macOS 15, iOS 18, *)) { + return env::metal_fenced_inputs() && env::metal_fast_synch() && + !detail::in_export_tracing(); + } +#endif + return false; +} + std::string write_signature( std::string func_name, const std::string& header, @@ -67,10 +113,13 @@ std::string write_signature( const std::vector& attributes, const std::vector>& shape_infos, bool atomic_outputs, - const std::vector& mutable_inputs) { + const std::vector& mutable_inputs, + const char* fence_preamble, + const std::vector& fenced_inputs) { std::string kernel_source; kernel_source.reserve(header.size() + source.size() + 16384); kernel_source += header; + kernel_source += fence_preamble; // Auto-generate a function signature based on `template_args` // and the dtype/shape of the arrays passed as `inputs`. if (!template_args.empty()) { @@ -171,6 +220,14 @@ std::string write_signature( } index++; } + // Fenced inputs: the CPU fence and its count (attributes follow). + for (int i : fenced_inputs) { + const auto& name = input_names[i]; + kernel_source += " volatile coherent(system) device uint* " + name + + "_fence [[buffer(" + std::to_string(index++) + ")]],\n"; + kernel_source += " constant uint& " + name + "_fence_count [[buffer(" + + std::to_string(index++) + ")]],\n"; + } index = 0; for (const auto& attr : attributes) { @@ -261,6 +318,30 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( bool ensure_row_contiguous, bool atomic_outputs, const CompileOptions& compile_options) { + return metal_kernel_with_fenced_inputs( + name, + input_names, + output_names, + source, + mutable_input_names, + {}, + header, + ensure_row_contiguous, + atomic_outputs, + compile_options); +} + +CustomKernelFunction metal_kernel_with_fenced_inputs( + const std::string& name, + const std::vector& input_names, + const std::vector& output_names, + const std::string& source, + const std::vector& mutable_input_names, + const std::vector& fenced_input_names, + const std::string& header, + bool ensure_row_contiguous, + bool atomic_outputs, + const CompileOptions& compile_options) { std::vector mutable_inputs; for (const auto& mutable_name : mutable_input_names) { auto it = std::find(input_names.begin(), input_names.end(), mutable_name); @@ -276,6 +357,38 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( mutable_inputs.push_back(index); } std::sort(mutable_inputs.begin(), mutable_inputs.end()); + std::vector fenced_inputs; + for (const auto& fenced_name : fenced_input_names) { + auto it = std::find(input_names.begin(), input_names.end(), fenced_name); + if (it == input_names.end() || + std::count(input_names.begin(), input_names.end(), fenced_name) != 1) { + throw std::invalid_argument("Fenced input must name one kernel input."); + } + int index = static_cast(it - input_names.begin()); + if (std::find(fenced_inputs.begin(), fenced_inputs.end(), index) != + fenced_inputs.end() || + std::find(mutable_inputs.begin(), mutable_inputs.end(), index) != + mutable_inputs.end()) { + throw std::invalid_argument( + "A fenced kernel input must be unique and not mutable."); + } + for (const auto& suffix : {"_fence", "_fence_count"}) { + auto param = fenced_name + suffix; + if (std::count(input_names.begin(), input_names.end(), param) || + std::count(output_names.begin(), output_names.end(), param)) { + throw std::invalid_argument( + "Kernel argument name " + param + " is used by a fenced input."); + } + } + if (source.find("MLX_FENCED_INPUT_WAIT(" + fenced_name + ")") == + std::string::npos) { + throw std::invalid_argument( + "The kernel source must call MLX_FENCED_INPUT_WAIT(" + fenced_name + + ") before it reads the fenced input."); + } + fenced_inputs.push_back(index); + } + std::sort(fenced_inputs.begin(), fenced_inputs.end()); if (output_names.empty()) { throw std::invalid_argument( "[metal_kernel] Must specify at least one output."); @@ -313,7 +426,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::vector attributes; for (const auto& [attr, dtype] : metal_attributes) { - if (source.find(attr) != std::string::npos) { + if (source.find(attr) != std::string::npos || + (!fenced_inputs.empty() && attr == "thread_index_in_threadgroup")) { attributes.push_back(" " + dtype + " " + attr + " [[" + attr + "]]"); } } @@ -404,6 +518,10 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( for (int i : mutable_inputs) { cache_key += inputs[i].ndim() == 0 ? 'z' : 'n'; } + const bool fenced = !fenced_inputs.empty() && fenced_inputs_enabled(); + if (!fenced_inputs.empty()) { + cache_key += fenced ? 'f' : 'u'; + } std::shared_ptr generated; { std::lock_guard lock(source_cache->mtx); @@ -425,7 +543,11 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( attributes, shape_infos, atomic_outputs, - mutable_inputs); + mutable_inputs, + fenced_inputs.empty() ? "" + : fenced ? fenced_input_wait + : fenced_input_no_wait, + fenced ? fenced_inputs : std::vector{}); if (!template_args.empty()) { auto instantiation = kernel_name + template_def; @@ -475,7 +597,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( 0, compile_options.serialize(), mutable_inputs, - generated->library_name), + generated->library_name, + fenced ? fenced_inputs : std::vector{}), inputs); } return array::make_arrays( @@ -495,7 +618,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( 0, compile_options.serialize(), std::vector{}, - generated->library_name), + generated->library_name, + fenced ? fenced_inputs : std::vector{}), std::move(inputs)); }; } diff --git a/mlx/backend/cuda/fence.cpp b/mlx/backend/cuda/fence.cpp index 3a3acdba09..64c605a0b0 100644 --- a/mlx/backend/cuda/fence.cpp +++ b/mlx/backend/cuda/fence.cpp @@ -24,6 +24,10 @@ void Fence::wait(Stream s, const array&) { cast().event.wait(); } +bool Fence::wait_in_consumer(Stream, const array&, int) { + return false; +} + void Fence::update(Stream s, const array& a, bool cross_device) { auto& f = cast(); if (cross_device) { diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 6bb5b62e12..c45395adb5 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -2,6 +2,7 @@ #include "mlx/backend/common/metal_kernel.h" #include "mlx/backend/gpu/copy.h" +#include "mlx/backend/metal/fenced_input.h" #include "mlx/backend/metal/jit/includes.h" #include "mlx/backend/metal/utils.h" #include "mlx/fast_primitives.h" @@ -55,6 +56,22 @@ void CustomKernel::eval_gpu( } } + // Waits on fenced inputs that Fence::wait_in_consumer gave to this kernel. + // An input that is copied first is read before the kernel: wait for it now. + std::vector fenced; + if (!fenced_inputs_.empty()) { + fenced = metal::take_fenced_inputs(this); + for (auto it = fenced.begin(); it != fenced.end();) { + auto& in = inputs[it->input]; + if (ensure_row_contiguous_ && !in.flags().row_contiguous) { + metal::encode_fence_wait(s, in, *it); + it = fenced.erase(it); + } else { + ++it; + } + } + } + std::vector copies; for (auto& out : outputs) { @@ -160,6 +177,24 @@ void CustomKernel::eval_gpu( compute_encoder.set_output_array(out, index); index++; } + for (int i : fenced_inputs_) { + auto it = std::find_if( + fenced.begin(), fenced.end(), [i](auto& f) { return f.input == i; }); + if (it != fenced.end()) { + metal::bind_fenced_input(compute_encoder, *it, index); + } else { + // No CPU-stream producer in this eval: a count of 0 does not wait. + compute_encoder.set_input_array(checked_inputs[i], index); + compute_encoder.set_bytes(uint32_t(0), index + 1); + } + index += 2; + } + if (!fenced.empty()) { + // As Fence::wait: start after every pass and kernel encoded before, so + // the CPU work that the kernel waits for never waits for the kernel. + compute_encoder.wait_for_all_pending(); + compute_encoder.barrier(); + } MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index a329297d3e..a144ca5605 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -1,13 +1,15 @@ // Copyright © 2024 Apple Inc. #include "mlx/fence.h" #include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/fenced_input.h" +#include "mlx/fast_primitives.h" #include "mlx/scheduler.h" #include "mlx/utils.h" namespace mlx::core { struct FenceImpl { - FenceImpl(Stream stream) { + FenceImpl(Stream stream) : cpu_stream(stream.device == Device::cpu) { auto d = metal::device(stream.device).mtl_device(); if (!d->supportsFamily(MTL::GPUFamilyMetal3)) { use_fast = false; @@ -32,6 +34,7 @@ struct FenceImpl { } } bool use_fast{false}; + bool cpu_stream; uint32_t count{0}; // Threadgroups that fence_update_coherent counted in (mod 2^32). uint32_t arrivals{0}; @@ -44,27 +47,19 @@ struct FenceImpl { } }; -Fence::Fence(Stream stream) { - fence_ = std::make_shared(stream); -} - -void Fence::wait(Stream stream, const array& x) { - auto& f = *static_cast(fence_.get()); - - if (!f.use_fast) { - f.event->wait(stream); - return; - } +namespace { - if (stream.device == Device::cpu) { - scheduler::enqueue(stream, [fence_ = fence_, count = f.count]() mutable { - auto& f = *static_cast(fence_.get()); - while (f.cpu_value()[0] < count) { - } - }); - return; - } +std::vector& given_waits() { + static thread_local std::vector waits; + return waits; +} +void encode_wait( + Stream stream, + const array& x, + const std::shared_ptr& fence, + uint32_t count) { + auto& f = *static_cast(fence.get()); auto& d = metal::device(stream.device); auto& compute_encoder = metal::get_command_encoder(stream); @@ -85,11 +80,37 @@ void Fence::wait(Stream stream, const array& x) { auto buf = static_cast(f.fence); compute_encoder.set_buffer(buf, 0); - compute_encoder.set_bytes(f.count, 1); + compute_encoder.set_bytes(count, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims); // The fence buffer must outlive the pass that spins on it. - compute_encoder.retain_until_completed(fence_); + compute_encoder.retain_until_completed(fence); +} + +} // namespace + +Fence::Fence(Stream stream) { + fence_ = std::make_shared(stream); +} + +void Fence::wait(Stream stream, const array& x) { + auto& f = *static_cast(fence_.get()); + + if (!f.use_fast) { + f.event->wait(stream); + return; + } + + if (stream.device == Device::cpu) { + scheduler::enqueue(stream, [fence_ = fence_, count = f.count]() mutable { + auto& f = *static_cast(fence_.get()); + while (f.cpu_value()[0] < count) { + } + }); + return; + } + + encode_wait(stream, x, fence_, f.count); } void Fence::update(Stream stream, const array& x, bool cross_device) { @@ -173,4 +194,45 @@ void Fence::update(Stream stream, const array& x, bool cross_device) { compute_encoder.retain_until_completed(fence_); } +bool Fence::wait_in_consumer(Stream stream, const array& consumer, int input) { + auto& f = *static_cast(fence_.get()); + if (!env::metal_fenced_inputs() || !f.use_fast || !f.cpu_stream || + stream.device != Device::gpu) { + return false; + } + auto kernel = dynamic_cast(&consumer.primitive()); + if (!kernel || !kernel->fenced_input(input)) { + return false; + } + given_waits().push_back({&consumer.primitive(), input, fence_, f.count}); + return true; +} + +namespace metal { + +std::vector take_fenced_inputs(const Primitive* consumer) { + auto& waits = given_waits(); + std::vector taken; + for (auto& w : waits) { + if (w.consumer == consumer) { + taken.push_back(std::move(w)); + } + } + waits.clear(); + return taken; +} + +void bind_fenced_input(CommandEncoder& enc, const FencedInput& w, int index) { + auto& f = *static_cast(w.fence.get()); + enc.set_buffer(static_cast(f.fence), index); + enc.set_bytes(w.count, index + 1); + enc.retain_until_completed(w.fence); +} + +void encode_fence_wait(Stream stream, const array& x, const FencedInput& w) { + encode_wait(stream, x, w.fence, w.count); +} + +} // namespace metal + } // namespace mlx::core diff --git a/mlx/backend/metal/fenced_input.h b/mlx/backend/metal/fenced_input.h new file mode 100644 index 0000000000..fb3f5e5cbe --- /dev/null +++ b/mlx/backend/metal/fenced_input.h @@ -0,0 +1,32 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include +#include + +#include "mlx/array.h" +#include "mlx/backend/metal/device.h" + +namespace mlx::core::metal { + +// The wait of a custom kernel on a fenced input from a CPU stream, given to +// the kernel by Fence::wait_in_consumer instead of a fence_wait dispatch. +struct FencedInput { + const Primitive* consumer; + int input; + std::shared_ptr fence; + uint32_t count; +}; + +// Remove the waits given to `consumer` and return them. Discard all others. +std::vector take_fenced_inputs(const Primitive* consumer); + +// Bind the timestamp buffer at `index` and the count at `index + 1`. +void bind_fenced_input(CommandEncoder& enc, const FencedInput& f, int index); + +// Encode the wait as Fence::wait does, for an input read before the kernel. +void encode_fence_wait(Stream stream, const array& x, const FencedInput& f); + +} // namespace mlx::core::metal diff --git a/mlx/backend/no_gpu/fence.cpp b/mlx/backend/no_gpu/fence.cpp index 05852c860b..86fbe09783 100644 --- a/mlx/backend/no_gpu/fence.cpp +++ b/mlx/backend/no_gpu/fence.cpp @@ -20,6 +20,10 @@ void Fence::wait(Stream s, const array&) { cast().event.wait(s); } +bool Fence::wait_in_consumer(Stream, const array&, int) { + return false; +} + void Fence::update(Stream s, const array&, bool) { auto& f = cast(); f.count++; diff --git a/mlx/fast.h b/mlx/fast.h index aca6da3aed..76fe2da2d7 100644 --- a/mlx/fast.h +++ b/mlx/fast.h @@ -95,6 +95,23 @@ MLX_API CustomKernelFunction metal_kernel_with_mutable_inputs( bool atomic_outputs = false, const CompileOptions& compile_options = {}); +// As `metal_kernel_with_mutable_inputs`. A fenced input can come from a CPU +// stream in the same eval; with MLX_METAL_FENCED_INPUTS=1 the kernel waits for +// that CPU work itself, and MLX encodes no separate fence wait. The source +// calls MLX_FENCED_INPUT_WAIT(name) for each fenced input before it reads it, +// in control flow that all threads of the threadgroup reach. +MLX_API CustomKernelFunction metal_kernel_with_fenced_inputs( + const std::string& name, + const std::vector& input_names, + const std::vector& output_names, + const std::string& source, + const std::vector& mutable_input_names, + const std::vector& fenced_input_names, + const std::string& header = "", + bool ensure_row_contiguous = true, + bool atomic_outputs = false, + const CompileOptions& compile_options = {}); + MLX_API CustomKernelFunction cuda_kernel( const std::string& name, const std::vector& input_names, diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 28f5ef6423..42f6084d04 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -449,7 +449,8 @@ class CustomKernel : public Primitive { int shared_memory, CompileOptions::Data compile_options = {}, std::vector mutable_inputs = {}, - std::string library_name = "") + std::string library_name = "", + std::vector fenced_inputs = {}) : Primitive(stream), name_(std::move(name)), source_(std::move(source)), @@ -463,7 +464,8 @@ class CustomKernel : public Primitive { shared_memory_(shared_memory), compile_options_(compile_options), library_name_(std::move(library_name)), - mutable_inputs_(std::move(mutable_inputs)) {} + mutable_inputs_(std::move(mutable_inputs)), + fenced_inputs_(std::move(fenced_inputs)) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) override { @@ -474,6 +476,16 @@ class CustomKernel : public Primitive { override; DEFINE_NAME(CustomKernel); + + bool fenced_input(int index) const { + for (int i : fenced_inputs_) { + if (i == index) { + return true; + } + } + return false; + } + auto state() const { return std::make_tuple( name_, @@ -508,6 +520,9 @@ class CustomKernel : public Primitive { protected: std::vector mutable_inputs_; + // Inputs whose fence wait runs in the kernel. Not in `state()`: never set + // while exporting (see metal_kernel_with_fenced_inputs). + std::vector fenced_inputs_; }; class MutableInputCustomKernel : public CustomKernel { diff --git a/mlx/fence.h b/mlx/fence.h index 3fd5da333b..7bc9ce363d 100644 --- a/mlx/fence.h +++ b/mlx/fence.h @@ -32,6 +32,11 @@ class Fence { void update(Stream stream, const array& x, bool cross_device); void wait(Stream stream, const array& x); + // Give the wait on input `input` of `consumer` to the consumer's own GPU + // kernel (a fenced input of a Metal custom kernel). Returns false when it + // cannot; call `wait` then. + bool wait_in_consumer(Stream stream, const array& consumer, int input); + template auto& cast() const { return *static_cast(fence_.get()); diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 694bca53d8..b5f04f1f43 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -92,6 +92,9 @@ array eval_impl(std::vector outputs, bool async) { // Map of array id that needs fence and stream it's computed on std::unordered_map> needs_fence; + // GPU streams with an array that a CPU primitive reads + std::unordered_set gpu_to_cpu; + auto synchronizer = array( {}, bool_, std::make_shared(stream), std::move(outputs)); @@ -150,6 +153,9 @@ array eval_impl(std::vector outputs, bool async) { if (!inserted) { it->second.second |= device_switch; } + if (device_switch && in.primitive().device() == Device::gpu) { + gpu_to_cpu.insert(in.primitive().stream().index); + } } } @@ -246,12 +252,20 @@ array eval_impl(std::vector outputs, bool async) { } } - for (auto& in : arr.inputs()) { + // A kernel can wait for its CPU-stream input itself when that CPU work + // can depend on no GPU stream other than this one. + bool one_gpu_stream = gpu_to_cpu.empty() || + (gpu_to_cpu.size() == 1 && gpu_to_cpu.count(stream.index) == 1); + for (int i = 0; i < arr.inputs().size(); ++i) { + auto& in = arr.inputs()[i]; if (auto it = needs_fence.find(in.id()); it != needs_fence.end()) { // Use fence to wait within a single eval // Get the input array's stream fence and wait on the // output arrays stream - fences[it->second.first].wait(stream, in); + auto& fence = fences[it->second.first]; + if (!one_gpu_stream || !fence.wait_in_consumer(stream, arr, i)) { + fence.wait(stream, in); + } } else if (in.event().valid()) { if (in.event().is_signaled()) { in.detach_event(); diff --git a/mlx/utils.h b/mlx/utils.h index 59372483d5..d539623a75 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -217,6 +217,12 @@ inline bool metal_fused_fence_update() { return fused; } +// Custom kernels wait for their fenced inputs from a CPU stream themselves. +inline bool metal_fenced_inputs() { + static bool fenced = get_var("MLX_METAL_FENCED_INPUTS", 0); + return fenced; +} + inline bool enable_tf32() { static bool enable_tf32_ = get_var("MLX_ENABLE_TF32", 1); return enable_tf32_; From 7ebf8e155118878e8a0aa2b668a9c19ddd012bbc Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 20/44] [Metal] Small flat sets for per-dispatch encoder hazard tracking `CommandEncoder` tracked each dispatch's inputs and outputs in three hash sets; decode-sized dispatches (<= 24 buffers) now use small flat vectors with identical barrier, commit and fence decisions (replayed against the old code on 100 decode-like traces; set differential test under ASan/UBSan). About 0.2 ms of host time per GLM-5.3-Flash decode step (~1,000 dispatches). Co-Authored-By: Claude Opus 5.5 --- mlx/backend/metal/device.cpp | 14 ++-- mlx/backend/metal/device.h | 150 +++++++++++++++++++++++++++++++++-- 2 files changed, 150 insertions(+), 14 deletions(-) diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index b32bc35514..152ec3c80b 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -348,13 +348,12 @@ void CommandEncoder::set_input_array( const array& a, int idx, int64_t offset /* = 0 */) { - if (all_inputs_.insert(a.buffer().ptr()).second) { + if (all_inputs_.insert(a.buffer().ptr())) { buffer_sizes_ += a.data_size(); } auto r_buf = static_cast(const_cast(a.buffer().ptr())); next_inputs_.insert(r_buf); - needs_barrier_ = - needs_barrier_ | (prev_outputs_.find(r_buf) != prev_outputs_.end()); + needs_barrier_ = needs_barrier_ | prev_outputs_.contains(r_buf); auto a_buf = static_cast(a.buffer().ptr()); get_command_encoder()->setBuffer(a_buf, a.offset() + offset, idx); } @@ -376,8 +375,7 @@ void CommandEncoder::register_output_array(const array& a) { concurrent_outputs_.insert(buf); } else { next_outputs_.insert(buf); - needs_barrier_ = - needs_barrier_ | (prev_inputs_.find(buf) != prev_inputs_.end()); + needs_barrier_ = needs_barrier_ | prev_inputs_.contains(buf); } } @@ -396,7 +394,7 @@ void CommandEncoder::maybeInsertBarrier() { if (needs_barrier_) { get_command_encoder()->memoryBarrier(MTL::BarrierScopeBuffers); needs_barrier_ = false; - // Preserve the hash tables' buckets for reuse across barrier epochs. + // Keep the sets' memory for reuse across barrier epochs. prev_inputs_.swap(next_inputs_); prev_outputs_.swap(next_outputs_); } else { @@ -480,7 +478,8 @@ void CommandEncoder::end_encoding() { buffer_->addCompletedHandler([this, fence = std::move(fence_), temporaries = std::move(temporaries_), - all_outputs = std::move(all_outputs_), + all_outputs = std::vector( + all_outputs_.begin(), all_outputs_.end()), waiting_on = std::move(waiting_on)]( MTL::CommandBuffer*) mutable { std::lock_guard lk(outputs_mtx_); @@ -504,6 +503,7 @@ void CommandEncoder::end_encoding() { next_outputs_.clear(); concurrent_outputs_.clear(); all_inputs_.clear(); + all_outputs_.clear(); } void CommandEncoder::signal_event(Event event, uint64_t value) { diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 92920156b2..5319a873e6 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -3,11 +3,14 @@ #pragma once #include +#include +#include #include #include #include #include #include +#include #include "mlx/array.h" #include "mlx/backend/common/gemma4_expert_qmm.h" @@ -22,6 +25,139 @@ using MTLFCList = class Device; +// A set of buffer pointers for the encoder's hazard tracking. A small set is +// a vector with a linear search; a larger set also gets an open addressing +// index. clear() keeps the memory, so a warm encoder does not allocate. +class BufferSet { + public: + BufferSet() = default; + BufferSet(const BufferSet&) = delete; + BufferSet& operator=(const BufferSet&) = delete; + + // Returns true if `p` was not in the set. + bool insert(const void* p) { + if (!indexed_) { + if (std::find(items_.begin(), items_.end(), p) != items_.end()) { + return false; + } + items_.push_back(p); + if (items_.size() > kLinearMax) { + build_index(); + } + return true; + } + auto i = find_slot(key(p)); + if (slots_[i] != kEmpty) { + return false; + } + slots_[i] = key(p); + items_.push_back(p); + if (2 * items_.size() > slots_.size()) { + build_index(); + } + return true; + } + + template + void insert(It first, It last) { + for (; first != last; ++first) { + insert(*first); + } + } + + bool contains(const void* p) const { + if (!indexed_) { + return std::find(items_.begin(), items_.end(), p) != items_.end(); + } + return slots_[find_slot(key(p))] != kEmpty; + } + + void erase(const void* p) { + auto it = std::find(items_.begin(), items_.end(), p); + if (it == items_.end()) { + return; + } + *it = items_.back(); + items_.pop_back(); + if (indexed_) { + erase_slot(find_slot(key(p))); + } + } + + // build_index() resets every slot, so the index needs no clearing here. + void clear() { + items_.clear(); + indexed_ = false; + } + + void swap(BufferSet& other) noexcept { + items_.swap(other.items_); + slots_.swap(other.slots_); + std::swap(indexed_, other.indexed_); + } + + size_t size() const { + return items_.size(); + } + std::vector::const_iterator begin() const { + return items_.begin(); + } + std::vector::const_iterator end() const { + return items_.end(); + } + + private: + static constexpr size_t kLinearMax = 16; + static constexpr uintptr_t kEmpty = ~uintptr_t(0); + + static uintptr_t key(const void* p) { + return reinterpret_cast(p); + } + static size_t hash(uintptr_t k) { + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + return static_cast(k); + } + // The slot that holds `k`, or the empty slot where it would go. + size_t find_slot(uintptr_t k) const { + size_t mask = slots_.size() - 1; + size_t i = hash(k) & mask; + while (slots_[i] != kEmpty && slots_[i] != k) { + i = (i + 1) & mask; + } + return i; + } + // Remove slot i and move back later entries of its probe run. + void erase_slot(size_t i) { + size_t mask = slots_.size() - 1; + for (size_t j = (i + 1) & mask; slots_[j] != kEmpty; j = (j + 1) & mask) { + size_t home = hash(slots_[j]) & mask; + bool stays = (i <= j) ? (i < home && home <= j) : (i < home || home <= j); + if (!stays) { + slots_[i] = slots_[j]; + i = j; + } + } + slots_[i] = kEmpty; + } + void build_index() { + size_t capacity = 64; + while (capacity < 4 * items_.size()) { + capacity *= 2; + } + slots_.assign(capacity, kEmpty); + for (auto p : items_) { + slots_[find_slot(key(p))] = key(p); + } + indexed_ = true; + } + + std::vector items_; + std::vector slots_; + bool indexed_{false}; +}; + class MLX_API CommandEncoder { public: CommandEncoder(Device& d, int index, ResidencySets& residency_sets); @@ -151,13 +287,13 @@ class MLX_API CommandEncoder { bool wait_all_pending_{false}; bool concurrent_{false}; std::vector temporaries_; - std::unordered_set prev_inputs_; - std::unordered_set prev_outputs_; - std::unordered_set next_inputs_; - std::unordered_set next_outputs_; - std::unordered_set concurrent_outputs_; - std::unordered_set all_inputs_; - std::unordered_set all_outputs_; + BufferSet prev_inputs_; + BufferSet prev_outputs_; + BufferSet next_inputs_; + BufferSet next_outputs_; + BufferSet concurrent_outputs_; + BufferSet all_inputs_; + BufferSet all_outputs_; // A map of prior command encoder outputs to their corresponding fence. std::unordered_map> prev_ce_outputs_; From 9ec3dba8a9d387ea0856aee295b9978420a68e10 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 21/44] [Metal] Opt-in eager commit after a cross-device fence update `MLX_EAGER_FENCE_COMMIT=1` commits the command buffer right after a GPU-to-CPU fence update, so a CPU-stream collective can start as soon as its input is ready. Off by default (measured neutral on GLM TP2 decode); it only adds commit points and keeps the fast-synch ordering intact. Co-Authored-By: Claude Opus 5.5 --- mlx/transforms.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index b5f04f1f43..f78da7de09 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -306,6 +306,15 @@ array eval_impl(std::vector outputs, bool async) { it = fences.emplace(stream.index, Fence{stream}).first; } it->second.update(stream, a, nf->second.second); + // MLX_EAGER_FENCE_COMMIT=1: commit the GPU work now, so the + // CPU stream starts when `a` is ready, not when the buffer is + // full. + static const bool eager_commit = + env::get_var("MLX_EAGER_FENCE_COMMIT", 0); + if (eager_commit && nf->second.second && + stream.device == Device::gpu) { + gpu::finalize(stream); + } } }; From a94584b308a6a9bb4bd2d9809b2ea948c703e159 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 22/44] [scheduler] Optional separate budget for CPU-stream tasks `MLX_MAX_ACTIVE_CPU_TASKS=n` counts CPU-stream tasks apart from command buffers in the active-task throttle (`MLX_MAX_ACTIVE_TASKS` sets the other). Unset, the throttle is exactly today's. Co-Authored-By: Claude Opus 5.5 --- mlx/scheduler.h | 12 ++++++++++++ mlx/transforms.cpp | 17 ++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/mlx/scheduler.h b/mlx/scheduler.h index 7bce5a9fe6..d93f1d37c4 100644 --- a/mlx/scheduler.h +++ b/mlx/scheduler.h @@ -37,6 +37,7 @@ class MLX_API Scheduler { { std::lock_guard lk(mtx); n_active_tasks_++; + n_active_cpu_tasks_ += stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -45,6 +46,7 @@ class MLX_API Scheduler { { std::lock_guard lk(mtx); n_active_tasks_--; + n_active_cpu_tasks_ -= stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -53,6 +55,11 @@ class MLX_API Scheduler { return n_active_tasks_; } + // The active tasks of CPU streams; they are also in n_active_tasks(). + int n_active_cpu_tasks() const { + return n_active_cpu_tasks_; + } + void wait_for_one() { std::unique_lock lk(mtx); int n_tasks_old = n_active_tasks(); @@ -69,6 +76,7 @@ class MLX_API Scheduler { StreamThread& get_thread(Stream s); int n_active_tasks_{0}; + int n_active_cpu_tasks_{0}; std::unordered_map> threads_; std::shared_mutex threads_mtx_; std::condition_variable completion_cv; @@ -102,6 +110,10 @@ inline int n_active_tasks() { return scheduler().n_active_tasks(); } +inline int n_active_cpu_tasks() { + return scheduler().n_active_cpu_tasks(); +} + inline void notify_new_task(const Stream& stream) { scheduler().notify_new_task(stream); } diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index f78da7de09..7d452a3de4 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -24,6 +24,21 @@ namespace mlx::core { static constexpr int MAX_ACTIVE_TASKS = 10; +// At most MLX_MAX_ACTIVE_TASKS (default MAX_ACTIVE_TASKS) tasks in flight. +// MLX_MAX_ACTIVE_CPU_TASKS=n (n > 0) gives CPU-stream tasks their own limit +// n, and the first limit then counts GPU command buffers only. +static bool too_many_active_tasks() { + static const int max_tasks = + env::get_var("MLX_MAX_ACTIVE_TASKS", MAX_ACTIVE_TASKS); + static const int max_cpu_tasks = env::get_var("MLX_MAX_ACTIVE_CPU_TASKS", 0); + int n_tasks = scheduler::n_active_tasks(); + if (max_cpu_tasks <= 0) { + return n_tasks > max_tasks; + } + int n_cpu_tasks = scheduler::n_active_cpu_tasks(); + return n_tasks - n_cpu_tasks > max_tasks || n_cpu_tasks > max_cpu_tasks; +} + namespace { // Create a tracer copy of a primal for use in vjp/jvp. If the primal is a @@ -282,7 +297,7 @@ array eval_impl(std::vector outputs, bool async) { cpu::eval(arr); } - if (scheduler::n_active_tasks() > MAX_ACTIVE_TASKS || + if (too_many_active_tasks() || (get_active_memory() > get_memory_limit() && scheduler::n_active_tasks() > 0)) { // Commit any open streams From 7620956413fd68df96137bda1d438eb16ef95397 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:04:04 -0700 Subject: [PATCH 23/44] [Metal] Cheaper custom-kernel launches and graph bookkeeping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host time only; every generated source, kernel name, buffer and dispatch order is unchanged: - custom-kernel primitives share the cached generated source instead of copying it, and resolve the pipeline once per source; - repeat launches skip rebuilding the kernel name, template string and cache key; inputs bind directly when none needs a contiguous copy; - graph teardown dedups node inputs with a small vector; `eval_impl`'s per-node map is a flat open-addressing map (differential test vs std::unordered_map under ASan/UBSan); - one per-buffer Metal query removed from allocation. GLM-5.3-Flash one-rank decode on an M5 Ultra (with the mlx-c/mlx-swift counterparts): main-thread CPU per step 6.5–6.9 -> 4.7–4.8 ms; logits and token hashes identical. The CUDA side of the shared-source change is not compiled here. Co-Authored-By: Claude Opus 5.5 --- mlx/array.cpp | 43 ++++++++- mlx/backend/common/metal_kernel.cpp | 140 +++++++++++++++++----------- mlx/backend/cuda/custom_kernel.cpp | 5 +- mlx/backend/metal/allocator.cpp | 6 +- mlx/backend/metal/custom_kernel.cpp | 65 +++++++++---- mlx/fast_primitives.h | 63 +++++++++++-- mlx/transforms.cpp | 108 +++++++++++++++++++-- 7 files changed, 330 insertions(+), 100 deletions(-) diff --git a/mlx/array.cpp b/mlx/array.cpp index 07d3acd616..86a9e25e41 100644 --- a/mlx/array.cpp +++ b/mlx/array.cpp @@ -1,6 +1,7 @@ // Copyright © 2023-2024 Apple Inc. #include #include +#include #include "mlx/array.h" #include "mlx/ops.h" @@ -288,18 +289,50 @@ array::ArrayDesc::~ArrayDesc() { std::vector> for_deletion; + // The distinct inputs (and their siblings) of `ad`, one reference each. + // A graph node has a few inputs, so a vector with a linear search does + // the work of a hash map without allocating a node per input; large + // input lists also get a hash index. auto append_deletable_inputs = [&for_deletion](ArrayDesc& ad) { - std::unordered_map input_map; + constexpr size_t linear_max = 32; + // Ids are kept beside the arrays: a moved-out array has no id. + std::vector> distinct; + std::unordered_set index; + auto contains = [&](std::uintptr_t id) { + if (distinct.size() <= linear_max) { + for (auto& x : distinct) { + if (x.first == id) { + return true; + } + } + return false; + } + return index.count(id) > 0; + }; + auto insert = [&](const array& x) { + if (contains(x.id())) { + return; + } + distinct.emplace_back(x.id(), x); + if (distinct.size() == linear_max + 1) { + for (auto& y : distinct) { + index.insert(y.first); + } + } else if (distinct.size() > linear_max + 1) { + index.insert(x.id()); + } + }; + distinct.reserve(ad.inputs.size()); for (array& a : ad.inputs) { if (a.array_desc_) { - input_map.insert({a.id(), a}); + insert(a); for (auto& s : a.siblings()) { - input_map.insert({s.id(), s}); + insert(s); } } } ad.inputs.clear(); - for (auto& [_, a] : input_map) { + for (auto& [_, a] : distinct) { bool is_deletable = (a.array_desc_.use_count() <= a.siblings().size() + 1); // An array with siblings is deletable only if all of its siblings @@ -308,7 +341,7 @@ array::ArrayDesc::~ArrayDesc() { if (!is_deletable) { break; } - int is_input = (input_map.find(s.id()) != input_map.end()); + int is_input = contains(s.id()); is_deletable &= s.array_desc_.use_count() <= a.siblings().size() + is_input; } diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index 8bc86e600b..270fa846d6 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -435,19 +435,20 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( // The generated source is a pure function of this kernel object (header, // body, names, attributes, shape infos, atomic and mutable inputs: all // fixed here) and of the per-call key built below: the template - // definition and, per input, its dtype and how it is passed (mutable, + // arguments and, per input, its dtype and how it is passed (mutable, // scalar, constant or device; a 0-d mutable input also drops its shape - // parameters). Cache the source and its Metal library name per key, so a - // repeated call neither regenerates the (often multi-KB) source nor hashes - // it again at dispatch time. Shared by every copy of the returned function. - struct GeneratedSource { - std::string source; - std::string library_name; + // parameters), the output dtypes and whether fenced waits are compiled in. + // Cache the kernel name, source and Metal library name per key, so a + // repeated call neither formats names nor regenerates the (often multi-KB) + // source, and every launch of one entry shares it (and its pipeline, see + // CustomKernel::eval_gpu). Shared by every copy of the returned function. + struct Generated { + std::string kernel_name; + std::shared_ptr source; }; struct SourceCache { std::mutex mtx; - std::unordered_map> - entries; + std::unordered_map> entries; }; auto source_cache = std::make_shared(); @@ -478,59 +479,86 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( check_size(output_dtypes.size(), output_names.size(), "output_dtypes"); auto s = resolve_metal_kernel_stream(s_); + const bool fenced = !fenced_inputs.empty() && fenced_inputs_enabled(); - std::string kernel_name = "custom_kernel_" + name; - std::string template_def = ""; - if (!template_args.empty()) { - template_def = write_template(template_args); - auto template_hash = make_template_hash(template_def); - kernel_name += "_"; - kernel_name += template_hash; + // The per-call key as raw bytes: each template argument (name, kind, + // value), each input's dtype and passing, each output's dtype and the + // fenced form. It determines the kernel name and the source below. + thread_local std::string key; + key.clear(); + for (const auto& [arg_name, arg] : template_args) { + key += arg_name; + key += '\0'; + key += static_cast(arg.index()); + if (auto* v = std::get_if(&arg)) { + key.append(reinterpret_cast(v), sizeof(int)); + } else if (auto* b = std::get_if(&arg)) { + key += *b ? '1' : '0'; + } else { + key += static_cast(std::get(arg).val()); + } } - - // The generated source depends on the dtypes of the inputs and outputs - // and on how each input is passed (see `write_signature`). Include them - // in the kernel name so that a given name always maps to the same source. + key += '\0'; for (int i = 0; i < inputs.size(); ++i) { const auto& arr = inputs[i]; - kernel_name += "_"; - kernel_name += get_type_string(arr.dtype()); + key += static_cast(arr.dtype().val()); if (std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != mutable_inputs.end()) { - kernel_name += "m"; + key += arr.ndim() == 0 ? 'z' : 'n'; } else if (arr.ndim() == 0) { - kernel_name += "s"; + key += 's'; } else if (arr.size() < max_constant_array_size) { - kernel_name += "c"; + key += 'c'; + } else { + key += 'd'; } } + key += '\0'; for (const auto& dtype : output_dtypes) { - kernel_name += "_"; - kernel_name += get_type_string(dtype); + key += static_cast(dtype.val()); } + key += fenced ? 'f' : 'u'; - // `kernel_name` already encodes the template hash, every dtype and the - // m/s/c passing of each input; the full template definition and the - // 0-d-ness of mutable inputs complete the key (see `SourceCache`). - std::string cache_key = kernel_name; - cache_key += '|'; - cache_key += template_def; - for (int i : mutable_inputs) { - cache_key += inputs[i].ndim() == 0 ? 'z' : 'n'; - } - const bool fenced = !fenced_inputs.empty() && fenced_inputs_enabled(); - if (!fenced_inputs.empty()) { - cache_key += fenced ? 'f' : 'u'; - } - std::shared_ptr generated; + std::shared_ptr generated; { std::lock_guard lock(source_cache->mtx); - if (auto it = source_cache->entries.find(cache_key); + if (auto it = source_cache->entries.find(key); it != source_cache->entries.end()) { generated = it->second; } } if (!generated) { + std::string kernel_name = "custom_kernel_" + name; + std::string template_def = ""; + if (!template_args.empty()) { + template_def = write_template(template_args); + auto template_hash = make_template_hash(template_def); + kernel_name += "_"; + kernel_name += template_hash; + } + + // The generated source depends on the dtypes of the inputs and outputs + // and on how each input is passed (see `write_signature`). Include them + // in the kernel name so that a given name always maps to the same + // source. + for (int i = 0; i < inputs.size(); ++i) { + const auto& arr = inputs[i]; + kernel_name += "_"; + kernel_name += get_type_string(arr.dtype()); + if (std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != + mutable_inputs.end()) { + kernel_name += "m"; + } else if (arr.ndim() == 0) { + kernel_name += "s"; + } else if (arr.size() < max_constant_array_size) { + kernel_name += "c"; + } + } + for (const auto& dtype : output_dtypes) { + kernel_name += "_"; + kernel_name += get_type_string(dtype); + } + std::string kernel_source = write_signature( kernel_name, header, @@ -565,17 +593,19 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( kernel_name, std::hash{}(kernel_source), compile_options.serialize()); - generated = std::make_shared( - GeneratedSource{std::move(kernel_source), std::move(library_name)}); + auto entry = std::make_shared(); + entry->kernel_name = std::move(kernel_name); + entry->source = std::make_shared( + std::move(kernel_source), std::move(library_name)); + generated = std::move(entry); std::lock_guard lock(source_cache->mtx); - source_cache->entries.emplace(cache_key, generated); + source_cache->entries.emplace(key, generated); } - const std::string& kernel_source = generated->source; if (verbose) { std::cout << "Generated source code for `" << name << "`:" << std::endl << "```" << std::endl - << kernel_source << std::endl + << generated->source->source << std::endl << "```" << std::endl; } @@ -585,8 +615,8 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( output_dtypes, std::make_shared( s, - kernel_name, - kernel_source, + generated->kernel_name, + generated->source, grid, threadgroup, shape_infos, @@ -597,17 +627,16 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( 0, compile_options.serialize(), mutable_inputs, - generated->library_name, fenced ? fenced_inputs : std::vector{}), inputs); } return array::make_arrays( - std::move(output_shapes), - std::move(output_dtypes), + output_shapes, + output_dtypes, std::make_shared( s, - std::move(kernel_name), - kernel_source, + generated->kernel_name, + generated->source, grid, threadgroup, shape_infos, @@ -618,9 +647,8 @@ CustomKernelFunction metal_kernel_with_fenced_inputs( 0, compile_options.serialize(), std::vector{}, - generated->library_name, fenced ? fenced_inputs : std::vector{}), - std::move(inputs)); + inputs); }; } diff --git a/mlx/backend/cuda/custom_kernel.cpp b/mlx/backend/cuda/custom_kernel.cpp index c230656d80..6fede0dbbc 100644 --- a/mlx/backend/cuda/custom_kernel.cpp +++ b/mlx/backend/cuda/custom_kernel.cpp @@ -310,14 +310,15 @@ void CustomKernel::eval_gpu( // Compile the custom kernel std::string kernel_name = (is_precompiled_) ? name_ : "mlx::core::cu::" + name_; + const std::string& source = source_->source; std::string module_name = - fmt::format("{}_{:x}", name_, std::hash{}(source_)); + fmt::format("{}_{:x}", name_, std::hash{}(source)); cu::JitModule& mod = cu::get_jit_module( encoder.device(), module_name, [&]() { return std::make_tuple( - is_precompiled_, source_, std::vector{kernel_name}); + is_precompiled_, source, std::vector{kernel_name}); }, false); diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9db99ed59f..a0f3ad4b96 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -270,8 +270,10 @@ Buffer MetalAllocator::malloc(size_t size) { return Buffer{nullptr}; } - // More helpful message if maximum buffer length is exceeded - if (size > device_->maxBufferLength()) { + // More helpful message if maximum buffer length is exceeded. The limit is + // fixed for the device: read it once, not with a Metal call per buffer. + static const size_t max_buffer_length = device_->maxBufferLength(); + if (size > max_buffer_length) { std::ostringstream msg; msg << "[metal::malloc] Attempting to allocate " << size << " bytes which is greater than" diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index c45395adb5..7d3cd6612d 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -38,7 +38,8 @@ void CustomKernel::eval_gpu( auto& s = stream(); auto& d = metal::device(s.device); - const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + // The device limit is fixed: query it once rather than per launch. + static const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); if (static_cast(tx) > device_max.width || static_cast(ty) > device_max.height || static_cast(tz) > device_max.depth) { @@ -93,35 +94,63 @@ void CustomKernel::eval_gpu( return copies.back(); } }; - std::vector checked_inputs; - for (const array& in : inputs) { - checked_inputs.push_back(check_input(in)); + // Bind the inputs themselves unless one needs a contiguous copy (the same + // arrays either way, without a reference-counted copy of each). + bool needs_copy = false; + if (ensure_row_contiguous_) { + for (const array& in : inputs) { + needs_copy |= !in.flags().row_contiguous; + } + } + std::vector copied_inputs; + if (needs_copy) { + copied_inputs.reserve(inputs.size()); + for (const array& in : inputs) { + copied_inputs.push_back(check_input(in)); + } } + const std::vector& checked_inputs = + needs_copy ? copied_inputs : inputs; // Hashing the whole generated source (often tens of KB) on every dispatch // dominated the host cost of decode-sized custom kernels; the kernel // builder precomputes the identical name once per generated source. - std::string lib_name = library_name_.empty() - ? fmt::format( - "{}_{:x}_{}", - name_, - std::hash{}(source_), - compile_options_) - : library_name_; - auto lib = d.get_library( - lib_name, compile_options_, [this] { return metal::utils() + source_; }); - auto kernel = d.get_kernel(name_, lib); - auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + const std::string& source = source_->source; + std::string derived_name; + if (source_->library_name.empty()) { + derived_name = fmt::format( + "{}_{:x}_{}", + name_, + std::hash{}(source), + compile_options_); + } + const std::string& lib_name = + source_->library_name.empty() ? derived_name : source_->library_name; + // Launches that share a generated source skip the library and kernel + // lookups (a name hash and a shared lock each) after the first one. + std::call_once(source_->resolved, [&] { + auto lib = d.get_library(lib_name, compile_options_, [&source] { + return metal::utils() + source; + }); + auto pipeline = d.get_kernel(name_, lib); + source_->max_total_threads = pipeline->maxTotalThreadsPerThreadgroup(); + source_->pipeline = std::shared_ptr(pipeline->retain(), [](void* p) { + static_cast(p)->release(); + }); + }); + auto kernel = + static_cast(source_->pipeline.get()); + auto max_tg_size = source_->max_total_threads; const bool retry_geometry = (tx == 512 || tx == 1024) && ty == 1 && tz == 1 && gx >= tx && gx % tx == 0 && gy > 0 && gz > 0; if (tg_size > max_tg_size && retry_geometry) { const std::string declaration = "[[kernel]] void " + name_ + "("; - const auto position = source_.find(declaration); + const auto position = source.find(declaration); if (position != std::string::npos && - source_.find(declaration, position + declaration.size()) == + source.find(declaration, position + declaration.size()) == std::string::npos) { // Keep the dispatch geometry and give the compiler its required size. - auto constrained_source = source_; + auto constrained_source = source; constrained_source.insert( position, "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 42f6084d04..fe80634d88 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1,5 +1,7 @@ // Copyright © 2024 Apple Inc. +#include +#include #include #include @@ -433,12 +435,31 @@ class Quantize : public Custom { using ScalarArg = std::variant; +// Generated source of a custom kernel. `metal_kernel` makes one for each +// kernel and template instance, and all its launches share it. +struct CustomKernelSource { + explicit CustomKernelSource( + std::string source, + std::string library_name = "") + : source(std::move(source)), library_name(std::move(library_name)) {} + + std::string source; + // Metal library name. When empty, eval_gpu makes it from the source. + std::string library_name; + + // The compiled kernel and its threadgroup limit, resolved once by the + // first launch (Metal). + mutable std::once_flag resolved; + mutable std::shared_ptr pipeline; + mutable size_t max_total_threads = 0; +}; + class CustomKernel : public Primitive { public: CustomKernel( Stream stream, std::string name, - std::string source, + std::shared_ptr source, std::tuple grid, std::tuple threadgroup, std::vector> shape_infos, @@ -449,7 +470,6 @@ class CustomKernel : public Primitive { int shared_memory, CompileOptions::Data compile_options = {}, std::vector mutable_inputs = {}, - std::string library_name = "", std::vector fenced_inputs = {}) : Primitive(stream), name_(std::move(name)), @@ -463,10 +483,39 @@ class CustomKernel : public Primitive { is_precompiled_(is_precompiled), shared_memory_(shared_memory), compile_options_(compile_options), - library_name_(std::move(library_name)), mutable_inputs_(std::move(mutable_inputs)), fenced_inputs_(std::move(fenced_inputs)) {} + // A private source entry (graph import, cuda): resolved once per primitive. + CustomKernel( + Stream stream, + std::string name, + std::string source, + std::tuple grid, + std::tuple threadgroup, + std::vector> shape_infos, + bool ensure_row_contiguous, + std::optional init_value, + std::vector scalar_arguments, + bool is_precompiled, + int shared_memory, + CompileOptions::Data compile_options = {}, + std::vector mutable_inputs = {}) + : CustomKernel( + stream, + std::move(name), + std::make_shared(std::move(source)), + grid, + threadgroup, + std::move(shape_infos), + ensure_row_contiguous, + init_value, + std::move(scalar_arguments), + is_precompiled, + shared_memory, + compile_options, + std::move(mutable_inputs)) {} + void eval_cpu(const std::vector& inputs, std::vector& outputs) override { throw std::runtime_error("Custom kernels only run on GPU."); @@ -489,7 +538,7 @@ class CustomKernel : public Primitive { auto state() const { return std::make_tuple( name_, - source_, + source_->source, grid_, threadgroup_, shape_infos_, @@ -503,7 +552,7 @@ class CustomKernel : public Primitive { private: std::string name_; - std::string source_; + std::shared_ptr source_; std::tuple grid_; std::tuple threadgroup_; std::vector> shape_infos_; @@ -513,10 +562,6 @@ class CustomKernel : public Primitive { bool is_precompiled_; int shared_memory_; CompileOptions::Data compile_options_; - // Metal library name precomputed by `metal_kernel` (name, source hash and - // compile options); empty for kernels built elsewhere (e.g. imported - // graphs), which hash the source at dispatch as before. - std::string library_name_; protected: std::vector mutable_inputs_; diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 7d452a3de4..7fee175740 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -41,6 +41,98 @@ static bool too_many_active_tasks() { namespace { +// Degree of each array id in eval_impl's graph walk: an open-addressing map +// (linear probing, deletion by backward shift) with the operations of the +// std::unordered_map it replaces. A decode step's graph has thousands of +// nodes; this avoids a heap node per entry and the rehash chain. +class DegreeMap { + public: + int* find(std::uintptr_t key) { + if (keys_.empty()) { + return nullptr; + } + for (size_t i = home(key);; i = (i + 1) & mask_) { + if (keys_[i] == key) { + return &values_[i]; + } + if (keys_[i] == 0) { + return nullptr; + } + } + } + // Inserts `value` when `key` is absent; the entry either way. + int& emplace(std::uintptr_t key, int value) { + if (2 * (size_ + 1) > keys_.size()) { + grow(); + } + size_t i = home(key); + for (; keys_[i] != 0; i = (i + 1) & mask_) { + if (keys_[i] == key) { + return values_[i]; + } + } + keys_[i] = key; + values_[i] = value; + ++size_; + return values_[i]; + } + int& operator[](std::uintptr_t key) { + return emplace(key, 0); + } + void erase(std::uintptr_t key) { + if (keys_.empty()) { + return; + } + size_t i = home(key); + for (; keys_[i] != key; i = (i + 1) & mask_) { + if (keys_[i] == 0) { + return; + } + } + for (size_t j = (i + 1) & mask_; keys_[j] != 0; j = (j + 1) & mask_) { + size_t h = home(keys_[j]); + bool stays = i <= j ? (i < h && h <= j) : (i < h || h <= j); + if (!stays) { + keys_[i] = keys_[j]; + values_[i] = values_[j]; + i = j; + } + } + keys_[i] = 0; + values_[i] = 0; + --size_; + } + bool empty() const { + return size_ == 0; + } + + private: + size_t home(std::uintptr_t key) const { + uint64_t k = key; + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + return static_cast(k) & mask_; + } + void grow() { + std::vector keys(std::max(64, 2 * keys_.size()), 0); + std::vector values(keys.size(), 0); + std::swap(keys, keys_); + std::swap(values, values_); + mask_ = keys_.size() - 1; + size_ = 0; + for (size_t i = 0; i < keys.size(); ++i) { + if (keys[i] != 0) { + emplace(keys[i], values[i]); + } + } + } + std::vector keys_; + std::vector values_; + size_t mask_ = 0; + size_t size_ = 0; +}; + // Create a tracer copy of a primal for use in vjp/jvp. If the primal is a // stale Copy from a previous transform call (not an active tracer), peel it // off to prevent copy-chain accumulation when containers feed tracers back. @@ -127,7 +219,7 @@ array eval_impl(std::vector outputs, bool async) { { // Record the degree of each input - std::unordered_map cache; + DegreeMap cache; std::stack, int>> dfs; dfs.emplace(synchronizer, 0); @@ -176,14 +268,14 @@ array eval_impl(std::vector outputs, bool async) { // All siblings have the same degree auto cache_it = cache.find(in.id()); - if (cache_it == cache.end()) { + if (cache_it == nullptr) { dfs.emplace(in, 0); - cache.insert({in.id(), 1}); + cache.emplace(in.id(), 1); for (auto& s : in.siblings()) { - cache.insert({s.id(), 1}); + cache.emplace(s.id(), 1); } } else { - cache_it->second++; + (*cache_it)++; for (auto& s : in.siblings()) { cache[s.id()]++; } @@ -225,9 +317,9 @@ array eval_impl(std::vector outputs, bool async) { } auto it = cache.find(in.id()); - it->second -= 1; + *it -= 1; - if (it->second != 0) { + if (*it != 0) { for (auto& s : in.siblings()) { cache[s.id()] -= 1; } @@ -235,7 +327,7 @@ array eval_impl(std::vector outputs, bool async) { } // Remove input and siblings from cache - cache.erase(it); + cache.erase(in.id()); for (auto& s : in.siblings()) { cache.erase(s.id()); } From b7434f7f8bbf94fbecc2c58fe5dac615f459533f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:28:16 -0700 Subject: [PATCH 24/44] Revert the NAX gather_qmm simdgroup skip (#4352) on this tree Upstream ml-explore/mlx c7ff35d97 ("Skip unnecessary simdgroup computations for quantised MOE matmuls on NAX", #4352) reached this fork through the v0.32.2 squash (734241bb), not by ancestry, in the form that #4572 later gave it: `const bool sg_active = sgp_sm > 0;` and two `if (sg_active)` blocks around the MMA loop in each of fp_gather_qmm_rhs_nax (fp_quantized_nax.h) and affine_gather_qmm_rhs_nax (quantized_nax.h). This removes the flag and runs the MMA in every simdgroup again, as before #4352. It is the same change as the earlier revert of #4352 on 0.32.2 (e9debbeaa) and its re-application on the 0.32.3 kernels, hand-ported because the surrounding lines differ here. Why: these kernels run only on GPUs with NAX. On a two-Mac JACCL pair with one NAX GPU, mixture-of-experts serving with the skip present lost all-reduce completions, and 92 to 96 GiB stayed wired on the host until it was rebooted. The builds that served that pair afterwards carried the revert. It is therefore kept out of every build that runs distributed on mixed hardware. Output is unchanged: stores stay bounded by sgp_sm, and the rows past the tile that the MMA now reads are either inside M (rows_in_bounds) or loaded as zeros by load_safe with sgp_sm rows. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ccf517a04bb168258009be33042b4acd677dc913) --- fork.yaml | 9 ++ mlx/backend/metal/kernels/fp_quantized_nax.h | 100 +++++++++---------- mlx/backend/metal/kernels/quantized_nax.h | 88 ++++++++-------- 3 files changed, 95 insertions(+), 102 deletions(-) diff --git a/fork.yaml b/fork.yaml index 3a72e886dd..d392efc724 100644 --- a/fork.yaml +++ b/fork.yaml @@ -296,6 +296,15 @@ def: floating-point kernels have no global-scale input, and the NAX kernels keep the fork's bound for the last K tile. The section disappears once the fork rebases onto an upstream commit at or past `90089440`. + + One upstream change in these NAX kernels is reverted on purpose: the simdgroup skip + of [ml-explore/mlx#4352](https://github.com/ml-explore/mlx/pull/4352) (`c7ff35d9`, + which arrived with the v0.32.2 changes; `#4572` kept it as + `sg_active = sgp_sm > 0`). `fp_gather_qmm_rhs_nax` and `affine_gather_qmm_rhs_nax` run + the MMA in every simdgroup again. With the skip, mixture-of-experts serving on a + two-Mac JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB + wired until a reboot. Stores stay bounded by `sgp_sm`, so the output is unchanged. + Keep the revert at every rebase onto upstream. globs: - ".gitignore" - "benchmarks/python/swiglu_bench.py" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 39fbfd0d54..c7f9f8fcc7 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -882,8 +882,6 @@ template < using AccumType = float; - const bool sg_active = sgp_sm > 0; - NAXTile Dtile; Dtile.clear(); @@ -913,35 +911,31 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } - - if constexpr (transpose) { - Btile.template load( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load( - Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); } + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } xn += BK; @@ -955,32 +949,28 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - const short psk = min(int(SK), max(0, (BK - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); - - if constexpr (transpose) { - Btile.template load( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load( - Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + const short psk = min(int(SK), max(0, (BK - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } } diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 0921d007a3..bf90bb84fa 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -1561,8 +1561,6 @@ template < using AccumType = float; - const bool sg_active = sgp_sm > 0; - NAXTile Dtile; Dtile.clear(); @@ -1593,33 +1591,31 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } - - if constexpr (transpose) { - Btile.template load(Ws + tn * BK_padded + kk1); - } else { - Btile.template load(Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); } + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } xn += BK; @@ -1633,30 +1629,28 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; + NAXTile Atile; + NAXTile Btile; - volatile int compiler_barrier; + volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + const short psk = min(int(SK), max(0, (BK - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); - if constexpr (transpose) { - Btile.template load(Ws + tn * BK_padded + kk1); - } else { - Btile.template load(Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); - (void)compiler_barrier; - } + (void)compiler_barrier; } } From 0077571e8330ce6d4a06c394f25f55e146227451 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:20:08 -0700 Subject: [PATCH 25/44] fix(metal): bound sorted quantized NAX tail loads Use the remaining reduction width for the final activation tile. Check row and packed-column bounds before reading affine or floating-quantized weights and scales, then zero padding lanes. Add exact-value partial-tile and NaN-neighbor regression coverage for affine, MXFP4, MXFP8 and NVFP4. The companion Swift regression reproduced 48 failing geometries and passes all 272 cases with this repair. The original MiMo and Qwen fallback failures also pass on M5 Max. AI assistance: Codex diagnosed, implemented and tested this patch under the repository owner's explicit direction. (cherry picked from commit eb576eb2684f9d97dd2460db52edd717decc6b58) --- fork.yaml | 18 +++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 25 ++++---- mlx/backend/metal/kernels/quantized_nax.h | 52 ++++++++-------- python/tests/test_quantized.py | 62 ++++++++++++++++++++ 4 files changed, 116 insertions(+), 41 deletions(-) diff --git a/fork.yaml b/fork.yaml index d392efc724..eebcaa1509 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,15 +169,29 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" + - title: "Quantized NAX partial-tile bounds" + description: | + Sorted gathered matrix products use the remaining reduction width for a + partial activation tile. Safe affine and floating-quantized weight loaders + check row and packed-column bounds before reading weights or scales, then + zero invalid lanes. This prevents finite tails from reading the next row, + including a following NaN row. Exact Python regressions cover affine, + MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + Aligned dispatch and accumulation precision remain unchanged. + globs: + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official v0.32.2 by applying upstream's changes rather than merging them, so `git` sees them as - fork commits even though every file below is byte-identical to upstream `v0.32.2` + fork commits even though the imported content matches upstream `v0.32.2` (CUDA backend, CPU SIMD, kernels, Python bindings and tests, repository CI and templates, `AGENTS.md` / `CLAUDE.md`, docs). Listed here so the page does not credit Layr-Labs with upstream's changes; the section disappears once the fork rebases onto - an upstream commit at or past v0.32.2. + an upstream commit at or past v0.32.2. Later fork changes to these paths + are described in their own sections, including quantized NAX tile bounds. globs: - ".pre-commit-config.yaml" - "AGENTS.md" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index c7f9f8fcc7..04f8262b3a 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -149,14 +149,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -165,10 +158,18 @@ struct QuantizedBlockLoader { int k = 0; for (int i = 0; i < n_steps_per_read; i++) { - T scale = dequantize_scale(scales[i]); + const bool scale_in_bounds = (bj + k) * pack_factor < src_tile_dim.x; + T scale = + scale_in_bounds ? dequantize_scale(scales[i]) : T(0); for (int j = 0; j < n_reads_per_scale; j++) { - dequantize( - src[k * bytes_per_pack], scale, dst + k * pack_factor); + if ((bj + k) * pack_factor < src_tile_dim.x) { + dequantize( + src[k * bytes_per_pack], scale, dst + k * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[k * pack_factor + p] = T(0); + } + } k++; } } @@ -954,7 +955,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index bf90bb84fa..68f0ee2dd5 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -653,14 +653,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -670,11 +663,17 @@ struct QuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -793,14 +792,7 @@ struct QuantizedBlockLoader< return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -810,11 +802,17 @@ struct QuantizedBlockLoader< T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -1634,7 +1632,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 461175f013..f0edfa7455 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1600,6 +1600,68 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y4, atol=tol)) @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") + @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") + def test_gather_qmm_sorted_partial_tiles(self): + # Exact sums expose reading a following row as reduction-tile padding. + counts = [17, 3, 31, 14] + indices = [expert for expert, count in enumerate(counts) for _ in range(count)] + rhs = mx.array(indices, dtype=mx.uint32) + experts = [0.25, 0.5, 1.0, 2.0] + for mode, dtype, k, n in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.float16, mx.bfloat16], + [32, 64, 96, 128], + [32, 96], + ): + with self.subTest(mode=mode, dtype=dtype, k=k, n=n): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 scales are 1/4, 1/2, 1, 2. + wq = mx.full((4, n, k // 8), 0x22222222, dtype=mx.uint32) + scales = mx.broadcast_to( + mx.array([40, 48, 56, 64], dtype=mx.uint8)[:, None, None], + (4, n, k // 16), + ) + packed = (wq, scales) + else: + weights = mx.broadcast_to( + mx.array(experts, dtype=dtype)[:, None, None], (4, n, k) + ) + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + for poison in [False, True]: + rows = [ + float("nan") if poison and i % 2 else float(i % 3 + 1) + for i in range(len(indices)) + ] + x = mx.broadcast_to( + mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) + ) + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=rhs, + transpose=True, + group_size=group_size, + bits=bits, + mode=mode, + sorted_indices=True, + ) + expected = mx.array( + [ + rows[row] * k * experts[expert] + for row, expert in enumerate(indices) + ], + dtype=dtype, + )[:, None, None] + self.assertEqual(actual.shape, (len(indices), 1, n)) + equal = (actual == expected) | ( + mx.isnan(actual) & mx.isnan(expected) + ) + self.assertTrue(mx.all(equal).item(), f"poison={poison}") + def test_gather_qmm_sorted_sliced_weight(self): E, R, D, N = 8, 64, 256, 64 dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 From 6beeabd8373ccdbda8e8edc3e11cb4ab593cca68 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:42:26 -0700 Subject: [PATCH 26/44] test(metal): exercise contiguous sorted quantized activation tiles (cherry picked from commit 65eb14fa3f64a56c9a807004b5af1b5f93f0c13d) --- python/tests/test_quantized.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index f0edfa7455..e5c81c3995 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1640,7 +1640,7 @@ def test_gather_qmm_sorted_partial_tiles(self): mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) ) actual = mx.gather_qmm( - x, + mx.contiguous(x), *packed, rhs_indices=rhs, transpose=True, From e3799f2325ee8d16772ae1657a47613a59890dca Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:58:51 -0700 Subject: [PATCH 27/44] Give floating-point NAX loaders a distinct Metal symbol (cherry picked from commit f7bbf7d73b1c8779ca0c58cf338027a48d877454) --- fork.yaml | 5 ++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/fork.yaml b/fork.yaml index eebcaa1509..d9bbd94138 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,7 +169,7 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" - - title: "Quantized NAX partial-tile bounds" + - title: "Quantized NAX tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders @@ -177,6 +177,9 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + The floating-point NAX loader has a distinct type name: its layout + differs from the non-NAX loader, and sharing a name corrupts MXFP4 + results when the offline Metal linker combines both translation units. Aligned dispatch and accumulation precision remain unchanged. globs: - "mlx/backend/metal/kernels/quantized_nax.h" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 04f8262b3a..f4db25db46 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -79,7 +79,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct FPQuantizedNAXBlockLoader { MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; @@ -107,7 +107,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedNAXBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -222,7 +222,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); // Instantiate Loader - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, BN, BK, @@ -366,7 +366,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< T, BK, BN, @@ -815,7 +815,7 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, transpose ? BN : BK, transpose ? BK : BN, From d02ac7778c9d8137b30989eeba0e018de46c894c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:06:28 -0700 Subject: [PATCH 28/44] Separate incompatible quantized Metal loader implementations (cherry picked from commit 1fb86d3fab639d9ba0e1d08a5ceb91423b416b78) --- fork.yaml | 10 ++++-- mlx/backend/metal/kernels/fp_quantized.h | 32 ++++++++--------- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++--- mlx/backend/metal/kernels/quantized.h | 38 ++++++++++---------- mlx/backend/metal/kernels/quantized_nax.h | 30 ++++++++-------- 5 files changed, 62 insertions(+), 58 deletions(-) diff --git a/fork.yaml b/fork.yaml index d9bbd94138..ebc7bb8a81 100644 --- a/fork.yaml +++ b/fork.yaml @@ -177,12 +177,16 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. - The floating-point NAX loader has a distinct type name: its layout - differs from the non-NAX loader, and sharing a name corrupts MXFP4 - results when the offline Metal linker combines both translation units. + Each affine/floating-point, legacy/NAX loader has a distinct type name. + Their layouts or bodies differ; sharing a name corrupts MXFP4 results + when the offline Metal linker combines the translation units. The + incompatible affine/FP pack-factor helpers and legacy/NAX vector loaders + also use distinct names. Aligned dispatch and accumulation precision remain unchanged. globs: + - "mlx/backend/metal/kernels/quantized.h" - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index e6c6a1de65..579ddf95ac 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -155,8 +155,8 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); +struct FPQuantizedBlockLoader { + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -181,7 +181,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -272,7 +272,7 @@ METAL_FUNC void fp_qmv_quad_impl( uint quad_gid [[quadgroup_index_in_threadgroup]], uint quad_lid [[thread_index_in_quadgroup]]) { constexpr int quads_per_simd = SIMD_SIZE / QUAD_SIZE; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int values_per_thread = D / QUAD_SIZE; constexpr int steps_per_thread = values_per_thread < group_size ? 1 : values_per_thread / group_size; @@ -342,7 +342,7 @@ METAL_FUNC void fp_qmv_fast_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int packs_per_thread = 2; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -430,7 +430,7 @@ METAL_FUNC void fp_qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -590,7 +590,7 @@ METAL_FUNC void fp_qmv_wide_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = SIMD_SIZE / k_lanes; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int nf4 = group_size / 4; // float4 lanes per quant group @@ -705,7 +705,7 @@ METAL_FUNC void fp_qvm_impl( uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = group_size / pack_factor; @@ -831,7 +831,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -841,7 +841,7 @@ METAL_FUNC void fp_qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BN, BK, @@ -955,7 +955,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -966,7 +966,7 @@ METAL_FUNC void fp_qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BK, BN, @@ -1894,7 +1894,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BN * BK_padded]; @@ -2011,7 +2011,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2030,7 +2030,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index f4db25db46..45e1bfebd3 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -80,7 +80,7 @@ template < short group_size, short bits> struct FPQuantizedNAXBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -216,7 +216,7 @@ METAL_FUNC void fp_qmm_t_impl( (void)lid; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); @@ -361,7 +361,7 @@ METAL_FUNC void fp_qmm_n_impl( (void)lid; (void)M; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -810,7 +810,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index 7b6f36eee1..d5a2953b32 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -15,7 +15,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -577,7 +577,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -589,7 +589,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -610,7 +610,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -769,7 +769,7 @@ METAL_FUNC void qmv_fast_impl( constexpr int packs_per_thread = bits == 2 ? 1 : 2; constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -836,7 +836,7 @@ METAL_FUNC void qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -1094,7 +1094,7 @@ METAL_FUNC void qvm_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = 32 / pack_factor; @@ -1220,7 +1220,7 @@ METAL_FUNC void qmm_t_expert_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1230,7 +1230,7 @@ METAL_FUNC void qmm_t_expert_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1348,7 +1348,7 @@ METAL_FUNC void qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1358,7 +1358,7 @@ METAL_FUNC void qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1474,7 +1474,7 @@ METAL_FUNC void qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1485,7 +1485,7 @@ METAL_FUNC void qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BK, BN, @@ -2118,7 +2118,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; @@ -2713,7 +2713,7 @@ template < return; } - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = BK + 16 / sizeof(T); threadgroup T Xs[BM * BK_padded]; @@ -2798,7 +2798,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2817,7 +2817,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, @@ -2935,7 +2935,7 @@ template constexpr float eps = 1e-7; constexpr int simd_size = 32; constexpr float n_bins = (1 << bits) - 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_reduce = group_size / simd_size; constexpr int writes_per_reduce = pack_factor / values_per_reduce; @@ -3037,7 +3037,7 @@ template device T* out [[buffer(3)]], uint2 index [[thread_position_in_grid]], uint2 grid_dim [[threads_per_grid]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); size_t offset = index.x + grid_dim.x * size_t(index.y); diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 68f0ee2dd5..60893f0f0e 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -29,7 +29,7 @@ inline constexpr short get_bytes_per_pack() { } template -inline U load_vector(const device T* x, thread U* x_thread) { +inline U nax_load_vector(const device T* x, thread U* x_thread) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -108,7 +108,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { } template -inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { +inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -579,7 +579,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedNAXBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -591,7 +591,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -612,7 +612,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -706,7 +706,7 @@ template < short reduction_dim, short tgp_size, short bits> -struct QuantizedBlockLoader< +struct AffineQuantizedNAXBlockLoader< T, BROWS, BCOLS, @@ -725,7 +725,7 @@ struct QuantizedBlockLoader< bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -751,7 +751,7 @@ struct QuantizedBlockLoader< const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -959,12 +959,12 @@ METAL_FUNC void qmm_t_nax_tgp_impl( (void)lid; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BN, BK, @@ -1103,12 +1103,12 @@ METAL_FUNC void qmm_n_nax_tgp_impl( static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BK, BN, @@ -1484,12 +1484,12 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, From 9266fda0b38aae916f06e394ae5b551b141bfb2b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:49:37 -0700 Subject: [PATCH 29/44] Fix legacy quantized partial-tile bounds (cherry picked from commit adbc349ba623be417993ec083afbb11d07ec42a9) --- fork.yaml | 5 +++-- mlx/backend/metal/kernels/fp_quantized.h | 19 +++++++++--------- mlx/backend/metal/kernels/quantized.h | 25 ++++++++++++------------ 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/fork.yaml b/fork.yaml index ebc7bb8a81..48e89c6b01 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,11 +169,12 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" - - title: "Quantized NAX tile bounds and distinct loader symbols" + - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders - check row and packed-column bounds before reading weights or scales, then + check row and packed-column bounds on both legacy and NAX paths before + reading weights or scales, then zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index 579ddf95ac..35dc88961f 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -221,14 +221,7 @@ struct FPQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -237,8 +230,14 @@ struct FPQuantizedBlockLoader { T scale = dequantize_scale(*scales); for (int i = 0; i < n_reads; i++) { - dequantize( - src[i * bytes_per_pack], scale, dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + src[i * bytes_per_pack], scale, dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index d5a2953b32..ad347e113f 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -651,14 +651,7 @@ struct AffineQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -668,11 +661,17 @@ struct AffineQuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } From 2a0c9bbb72bc801773fa4b512b55ca2962361f42 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:22:02 -0700 Subject: [PATCH 30/44] Enforce optional Metal backing caps and preserve CPU quantized sums (cherry picked from commit 9e22e1998a3b6f7f6f4ad58dc2038ecf9f4d0cb9) --- fork.yaml | 21 + mlx/backend/common/process_allocation_cap.h | 192 +++++++ mlx/backend/cpu/quantized.cpp | 18 +- mlx/backend/cuda/allocator.cpp | 9 + mlx/backend/metal/allocator.cpp | 237 ++++++++- mlx/backend/metal/allocator.h | 10 + mlx/backend/metal/resident.cpp | 16 +- mlx/backend/no_gpu/allocator.cpp | 9 + mlx/memory.h | 6 + python/tests/test_quantized.py | 74 +++ tests/allocator_tests.cpp | 2 +- tests/standalone/process_allocation_cap.cpp | 204 ++++++++ .../process_allocation_cap_metal.cpp | 494 ++++++++++++++++++ 13 files changed, 1274 insertions(+), 18 deletions(-) create mode 100644 mlx/backend/common/process_allocation_cap.h create mode 100644 tests/standalone/process_allocation_cap.cpp create mode 100644 tests/standalone/process_allocation_cap_metal.cpp diff --git a/fork.yaml b/fork.yaml index 48e89c6b01..6c2053ae3c 100644 --- a/fork.yaml +++ b/fork.yaml @@ -98,12 +98,22 @@ def: overflow-checked) cache-reuse limit shared with `BufferCache`. Metal, CPU and CUDA allocators implement the same interface; the allocator's own behaviour stays the authority. These describe allocator accounting, not process RSS. (PR #15) + The public process-allocation cap API adds install-once Metal backing enforcement. + Reservations include pending allocations and the fixed heap. Owned page-aligned VM + regions use Metal no-copy buffers; credit returns after the deallocator unmaps them. + Foreign wrappers retain caller ownership. CPU/CUDA reject this optional API; soft + memory limits are unchanged. Residency insertion rolls back failed registration before + callers release buffers, including ordinary uncapped allocations. Standalone CPU and + real-Metal tests cover delayed release, churn, and injected construction failures. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" + - "mlx/backend/common/process_allocation_cap.h" + - "tests/standalone/process_allocation_cap*.cpp" - "mlx/backend/common/buffer_cache.h" - "mlx/backend/metal/allocator.h" - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/metal/resident.cpp" - "mlx/backend/cuda/allocator.h" - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" @@ -190,6 +200,17 @@ def: - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" + - title: "CPU quantized accumulation precision" + description: | + Scalar affine, MXFP4, MXFP8 and NVFP4 matrix products accumulate in FP32 + and convert once when writing each output. Both matrix orientations and + the FP group sum preserve partial sums instead of rounding every addition + to BF16 or FP16. Exact CPU regressions compare constant products with + dequantized matmul, including sorted and unsorted gathered affine paths. + Quantization, packing, indexing and Metal kernels remain unchanged. + globs: + - "mlx/backend/cpu/quantized.cpp" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official diff --git a/mlx/backend/common/process_allocation_cap.h b/mlx/backend/common/process_allocation_cap.h new file mode 100644 index 0000000000..d92723b73e --- /dev/null +++ b/mlx/backend/common/process_allocation_cap.h @@ -0,0 +1,192 @@ +// Copyright © 2026 Eigen Labs. +#pragma once + +#include +#include +#include +#include +#include + +namespace mlx::core::allocator { + +struct ProcessAllocationCapSnapshot { + bool installed{false}; + size_t limit_bytes{0}; + size_t heap_bytes{0}; + size_t live_bytes{0}; + size_t cached_bytes{0}; + size_t pending_bytes{0}; + size_t unreclaimed_bytes{0}; + size_t charged_bytes{0}; + size_t peak_bytes{0}; +}; + +// Reference release alone cannot refund backing credit. +class ProcessAllocationCap { + public: + void install(size_t limit, size_t heap) { + std::lock_guard lock(mutex_); + if (state_.installed || !limit || heap > limit) { + throw std::invalid_argument("allocation cap install refused"); + } + state_.installed = true; + state_.limit_bytes = limit; + state_.heap_bytes = heap; + state_.charged_bytes = state_.peak_bytes = heap; + } + + void reserve(size_t bytes) { + std::lock_guard lock(mutex_); + if (!state_.installed || + bytes > state_.limit_bytes - state_.charged_bytes) { + throw std::runtime_error("native allocation cap exceeded"); + } + state_.pending_bytes += bytes; + state_.charged_bytes += bytes; + if (state_.charged_bytes > state_.peak_bytes) { + state_.peak_bytes = state_.charged_bytes; + } + } + + // Only a reservation for which no backing was acquired can be rolled back. + void failed_before_acquisition(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.pending_bytes, bytes); + state_.pending_bytes -= bytes; + state_.charged_bytes -= bytes; + } + void acquired(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.pending_bytes, state_.live_bytes, bytes); + } + void cache(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.live_bytes, state_.cached_bytes, bytes); + } + void reuse(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.cached_bytes, state_.live_bytes, bytes); + } + void relinquish(size_t bytes, bool cached = false) { + std::lock_guard lock(mutex_); + transfer( + cached ? state_.cached_bytes : state_.live_bytes, + state_.unreclaimed_bytes, + bytes); + } + void destroyed(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.unreclaimed_bytes, bytes); + state_.unreclaimed_bytes -= bytes; + state_.charged_bytes -= bytes; + } + ProcessAllocationCapSnapshot snapshot() const { + std::lock_guard lock(mutex_); + return state_; + } + + private: + static void require(size_t available, size_t bytes) { + if (bytes > available) { + throw std::logic_error("allocation cap ledger mismatch"); + } + } + static void transfer(size_t& from, size_t& to, size_t bytes) { + require(from, bytes); + if (bytes > std::numeric_limits::max() - to) { + throw std::overflow_error("allocation cap ledger overflow"); + } + from -= bytes; + to += bytes; + } + mutable std::mutex mutex_; + ProcessAllocationCapSnapshot state_; +}; + +// Shared by allocator bookkeeping and the Metal deallocator block. The callback +// never takes the allocator mutex. Release must finish before credit is +// returned. +class ProcessBackingLease { + public: + using Release = bool (*)(void*, size_t); + ProcessBackingLease(std::shared_ptr cap, size_t bytes) + : cap_(std::move(cap)), bytes_(bytes) { + cap_->reserve(bytes_); + } + ~ProcessBackingLease() { + finish(); + } + void attach(void* pointer, Release release) noexcept { + std::lock_guard lock(mutex_); + pointer_ = pointer; + release_ = release; + } + void acquired() { + std::lock_guard lock(mutex_); + if (state_ != State::pending) { + throw std::logic_error("backing already retired"); + } + cap_->acquired(bytes_); + state_ = State::live; + } + void cache() { + std::lock_guard lock(mutex_); + if (state_ != State::live) { + throw std::logic_error("backing cache mismatch"); + } + cap_->cache(bytes_); + state_ = State::cached; + } + void reuse() { + std::lock_guard lock(mutex_); + if (state_ != State::cached) { + throw std::logic_error("backing reuse mismatch"); + } + cap_->reuse(bytes_); + state_ = State::live; + } + void retire() { + std::lock_guard lock(mutex_); + if (state_ != State::live && state_ != State::cached) { + throw std::logic_error("backing retirement mismatch"); + } + cap_->relinquish(bytes_, state_ == State::cached); + state_ = State::retired; + } + void finish() noexcept { + std::lock_guard lock(mutex_); + if (state_ == State::finished) { + return; + } + // Foreign wrappers have no release function: their caller retains + // ownership. + const bool released = !release_ || release_(pointer_, bytes_); + if (state_ == State::pending && released) { + cap_->failed_before_acquisition(bytes_); + } else { + if (state_ == State::pending) { + cap_->acquired(bytes_); + } + if (state_ != State::retired) { + cap_->relinquish(bytes_, state_ == State::cached); + } + if (released) { + cap_->destroyed(bytes_); + } + } + // A failed backing release is permanently charged; it cannot be retried + // after ownership has been relinquished to a deallocator callback. + state_ = State::finished; + } + + private: + enum class State { pending, live, cached, retired, finished }; + std::shared_ptr cap_; + size_t bytes_; + void* pointer_{nullptr}; + Release release_{nullptr}; + State state_{State::pending}; + std::mutex mutex_; +}; + +} // namespace mlx::core::allocator diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 15e00cd913..30b11c87d6 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -108,15 +108,16 @@ void _qmm( constexpr int bytes_per_pack = get_bytes_per_pack(bits); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const T* scales_local = scales; const T* biases_local = biases; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -147,6 +148,7 @@ void _qmm( } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -174,7 +176,7 @@ void _qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = *scales_local++; T bias = *biases_local++; @@ -458,14 +460,15 @@ void fp_qmm( constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const uint8_t* scales_local = scales; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -484,6 +487,7 @@ void fp_qmm( } } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -506,11 +510,11 @@ void fp_qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = dequantize_scale(*scales_local++); - T gsum = 0; + float gsum = 0; for (int kw = 0; kw < packs_in_group; kw++) { if constexpr (bits == 4) { gsum += (*x_local++) * static_cast(FP4_LUT[w_local[0] & 0xf]); diff --git a/mlx/backend/cuda/allocator.cpp b/mlx/backend/cuda/allocator.cpp index e483317845..b29cc3a2b3 100644 --- a/mlx/backend/cuda/allocator.cpp +++ b/mlx/backend/cuda/allocator.cpp @@ -440,6 +440,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return cu::allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return cu::allocator().set_memory_limit(limit); } diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9b80840a18..97fc684aca 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -6,6 +6,7 @@ #include "mlx/memory.h" #include +#include #include #include #include @@ -52,6 +53,7 @@ MetalAllocator::MetalAllocator(Device& d) vm_page_size, [](MTL::Buffer* buf) { return buf->length(); }, [this](MTL::Buffer* buf) { + relinquish_capped(buf, true); if (!buf->heap()) { residency_sets_.erase(buf); } @@ -136,6 +138,125 @@ size_t MetalAllocator::set_wired_limit(size_t limit) { return limit; }; +void MetalAllocator::install_process_allocation_cap(size_t bytes) { + std::unique_lock lock(mutex_); + if (buffer_allocation_attempted_) { + throw std::invalid_argument( + "allocation cap requires a pristine buffer allocator"); + } + cap_->install(bytes, heap_ ? heap_->size() : 0); + cap_installed_ = true; +} + +ProcessAllocationCapSnapshot +MetalAllocator::get_process_allocation_cap_snapshot() { + return cap_->snapshot(); +} + +void MetalAllocator::relinquish_capped(MTL::Buffer* buffer, bool cached) { + if (!cap_installed_) { + return; + } + auto entry = capped_buffers_.find(buffer); + if (entry == capped_buffers_.end()) { + throw std::logic_error("untracked capped buffer"); + } + if (entry->second) { + entry->second->retire(); + } + capped_buffers_.erase(entry); +} + +Buffer MetalAllocator::malloc_capped( + size_t size, + std::unique_lock& lock) { + if (auto* cached = buffer_cache_.reuse_from_cache(size)) { + if (auto lease = capped_buffers_.at(cached)) { + lease->reuse(); + } + active_memory_ += cached->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{cached}; + } + // Trim idle backing before refusing a new shape. Actual callbacks, not cache + // eviction, return credit; externally retained buffers remain charged. + auto snapshot = cap_->snapshot(); + const auto charge = allocator::round_allocation_size(size, vm_page_size); + if (charge > device_->maxBufferLength()) { + throw std::invalid_argument( + "page-aligned backing exceeds Metal buffer limit"); + } + if (charge > snapshot.limit_bytes - snapshot.charged_bytes || + num_resources_ >= resource_limit_ || + buffer_cache_.cache_size() > max_pool_size_) { + num_resources_ -= buffer_cache_.clear(); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + MTL::Buffer* buffer = nullptr; + std::shared_ptr lease; + if (size < small_size_ && heap_) { + buffer = heap_->newBuffer(size, resource_options); + } + if (!buffer) { + // Reserve before releasing allocator lock, including in-flight allocations. + lease = std::make_shared(cap_, charge); + ++num_resources_; + lock.unlock(); + try { + void* pages = mmap( + nullptr, + charge, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + if (pages == MAP_FAILED) { + throw std::bad_alloc(); + } + lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + buffer = device_->newBuffer( + pages, charge, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + if (!buffer) { + throw std::runtime_error("Metal no-copy allocation failed"); + } + lease->acquired(); + } catch (...) { + if (buffer) { + buffer->release(); + } else { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); + } else { + ++num_resources_; + } + try { + capped_buffers_.emplace(buffer, lease); + if (!buffer->heap()) { + residency_sets_.insert(buffer); + } + } catch (...) { + capped_buffers_.erase(buffer); + if (lease) { + lease->retire(); + } + --num_resources_; + buffer->release(); + throw; + } + active_memory_ += buffer->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{buffer}; +} + Buffer MetalAllocator::malloc(size_t size) { // Metal doesn't like empty buffers if (size == 0) { @@ -159,6 +280,10 @@ Buffer MetalAllocator::malloc(size_t size) { // Try the cache std::unique_lock lk(mutex_); + buffer_allocation_attempted_ = true; + if (cap_installed_) { + return malloc_capped(size, lk); + } MTL::Buffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { size_t mem_required = get_active_memory() + get_cache_memory() + size; @@ -211,10 +336,16 @@ Buffer MetalAllocator::malloc(size_t size) { throw std::runtime_error(msg.str()); } lk.lock(); - num_resources_++; - if (!buf->heap()) { - residency_sets_.insert(buf); + try { + if (!buf->heap()) { + residency_sets_.insert(buf); + } + } catch (...) { + lk.unlock(); + buf->release(); + throw; } + num_resources_++; } active_memory_ += buf->length(); @@ -243,7 +374,13 @@ void MetalAllocator::free(Buffer buffer) { active_memory_ -= buf->length(); if (get_cache_memory() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); + if (cap_installed_) { + if (auto lease = capped_buffers_.at(buf)) { + lease->cache(); + } + } } else { + relinquish_capped(buf, false); num_resources_--; if (!buf->heap()) { residency_sets_.erase(buf); @@ -259,15 +396,91 @@ size_t MetalAllocator::size(Buffer buffer) const { } Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { - auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + std::unique_lock lock(mutex_); + buffer_allocation_attempted_ = true; + if (!cap_installed_) { + lock.unlock(); + auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + if (!buf) { + return Buffer{nullptr}; + } + lock.lock(); + try { + residency_sets_.insert(buf); + } catch (...) { + lock.unlock(); + buf->release(); + throw; + } + active_memory_ += buf->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + num_resources_++; + return Buffer{static_cast(buf)}; + } + std::shared_ptr lease; + if (cap_installed_) { + if (!size || size % vm_page_size || + reinterpret_cast(ptr) % vm_page_size || !ptr || + size > device_->maxBufferLength()) { + throw std::invalid_argument( + "capped foreign backing must be page aligned"); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + lease = std::make_shared(cap_, size); + } + ++num_resources_; + lock.unlock(); + MTL::Buffer* buf = nullptr; + try { + if (lease) { + // Charge wrapper lifetime; never free or assume ownership of caller + // pages. + buf = device_->newBuffer( + ptr, size, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + } else { + buf = device_->newBuffer(ptr, size, resource_options, nullptr); + } + if (buf && lease) { + lease->acquired(); + } + } catch (...) { + if (buf) { + buf->release(); + } else if (lease) { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); if (!buf) { - return Buffer{nullptr}; + if (lease) { + lease->finish(); + } + --num_resources_; + throw std::runtime_error("capped Metal no-copy wrapper allocation failed"); + } + try { + if (lease) { + capped_buffers_.emplace(buf, lease); + } + residency_sets_.insert(buf); + } catch (...) { + if (lease) { + capped_buffers_.erase(buf); + lease->retire(); + } + --num_resources_; + buf->release(); + throw; } - std::unique_lock lk(mutex_); - residency_sets_.insert(buf); active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); - num_resources_++; return Buffer{static_cast(buf)}; } @@ -278,6 +491,7 @@ void MetalAllocator::release(Buffer buffer) { } std::unique_lock lk(mutex_); active_memory_ -= buf->length(); + relinquish_capped(buf, false); num_resources_--; residency_sets_.erase(buf); lk.unlock(); @@ -308,6 +522,13 @@ size_t get_allocation_size_upper_bound(size_t size) { return result; } +void install_process_allocation_cap(size_t bytes) { + metal::allocator().install_process_allocation_cap(bytes); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + return metal::allocator().get_process_allocation_cap_snapshot(); +} + size_t set_cache_limit(size_t limit) { return metal::allocator().set_cache_limit(limit); } diff --git a/mlx/backend/metal/allocator.h b/mlx/backend/metal/allocator.h index 623055e92c..b184944224 100644 --- a/mlx/backend/metal/allocator.h +++ b/mlx/backend/metal/allocator.h @@ -24,6 +24,8 @@ class MetalAllocator : public allocator::Allocator { virtual Buffer make_buffer(void* ptr, size_t size) override; virtual void release(Buffer buffer) override; + void install_process_allocation_cap(size_t bytes); + ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); MemorySnapshot get_memory_snapshot(); size_t get_active_memory() { return active_memory_; @@ -93,6 +95,14 @@ class MetalAllocator : public allocator::Allocator { static constexpr size_t resource_high_water_num_ = 9; static constexpr size_t resource_high_water_den_ = 10; + Buffer malloc_capped(size_t size, std::unique_lock& lock); + void relinquish_capped(MTL::Buffer* buffer, bool cached); + std::shared_ptr cap_{ + std::make_shared()}; + bool cap_installed_{false}; + bool buffer_allocation_attempted_{false}; + std::map> + capped_buffers_; std::mutex mutex_; }; diff --git a/mlx/backend/metal/resident.cpp b/mlx/backend/metal/resident.cpp index 2436993637..fede178a5a 100644 --- a/mlx/backend/metal/resident.cpp +++ b/mlx/backend/metal/resident.cpp @@ -150,8 +150,20 @@ void ResidencySets::insert(MTL::Allocation* buf) { if (total_wired_ + bytes > capacity_) { return; } - uint32_t idx = add_to_set_locked(buf, it->second); - sets_[idx].set->commit(); + try { + uint32_t idx = add_to_set_locked(buf, it->second); + sets_[idx].set->commit(); + } catch (...) { + // Registration must not leave a pointer to a buffer the caller will + // release. + if (it->second.set_id != kNoSet) { + const uint32_t idx = it->second.set_id; + remove_from_set_locked(buf, it->second); + sets_[idx].set->commit(); + } + buf_to_set_.erase(it); + throw; + } } void ResidencySets::erase(MTL::Allocation* buf) { diff --git a/mlx/backend/no_gpu/allocator.cpp b/mlx/backend/no_gpu/allocator.cpp index f766707bce..06f9bcd79d 100644 --- a/mlx/backend/no_gpu/allocator.cpp +++ b/mlx/backend/no_gpu/allocator.cpp @@ -213,6 +213,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return allocator::common_allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return allocator::common_allocator().set_memory_limit(limit); } diff --git a/mlx/memory.h b/mlx/memory.h index f2e7bf225f..d36201b51a 100644 --- a/mlx/memory.h +++ b/mlx/memory.h @@ -7,9 +7,15 @@ #include #include "mlx/api.h" +#include "mlx/backend/common/process_allocation_cap.h" namespace mlx::core { +using ProcessAllocationCapSnapshot = allocator::ProcessAllocationCapSnapshot; +// One-way, pristine-allocator installation. Not a whole-process/host limit. +MLX_API void install_process_allocation_cap(size_t bytes); +MLX_API ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); + struct MemorySnapshot { size_t active_memory; size_t cache_memory; diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index e5c81c3995..d860196acf 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1599,6 +1599,80 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y3, atol=tol)) self.assertTrue(mx.allclose(y1, y4, atol=tol)) + def test_cpu_quantized_accumulation_modes_and_orientations(self): + with mx.stream(mx.cpu): + for mode, dtype, transpose, k in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.bfloat16, mx.float16, mx.float32], + [False, True], + [96, 3072], + ): + with self.subTest(mode=mode, dtype=dtype, transpose=transpose, k=k): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + x = mx.full((1, k), 3, dtype=dtype) + weights = mx.full((32, k) if transpose else (k, 32), 2, dtype=dtype) + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 code 64 is exactly 2. + packed = ( + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 8), + 0x22222222, + dtype=mx.uint32, + ), + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 16), + 64, + dtype=mx.uint8, + ), + ) + else: + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + dequantized = mx.dequantize( + *packed, group_size=group_size, bits=bits, mode=mode + ) + reference = x @ (dequantized.T if transpose else dequantized) + expected = mx.full((1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + actual = mx.quantized_matmul( + x, + *packed, + transpose=transpose, + group_size=group_size, + bits=bits, + mode=mode, + ) + self.assertTrue(mx.array_equal(actual, expected)) + + def test_affine_qmm_cpu_low_precision_accumulation(self): + with mx.stream(mx.cpu): + for dtype, bits, k in product( + [mx.bfloat16, mx.float16, mx.float32], [3, 4, 6], [96, 128] + ): + with self.subTest(dtype=dtype, bits=bits, k=k): + x = mx.full((1, 1, k), 3, dtype=dtype) + weights = mx.full((1, 32, k), 2, dtype=dtype) + packed = mx.quantize(weights, group_size=32, bits=bits) + reference = x @ mx.swapaxes( + mx.dequantize(*packed, group_size=32, bits=bits), -1, -2 + ) + expected = mx.full((1, 1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + for sorted_indices in [False, True]: + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=mx.array([0], dtype=mx.uint32), + group_size=32, + bits=bits, + sorted_indices=sorted_indices, + ) + self.assertTrue(mx.array_equal(actual, expected)) + actual = mx.quantized_matmul(x, *packed, group_size=32, bits=bits) + self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") def test_gather_qmm_sorted_partial_tiles(self): diff --git a/tests/allocator_tests.cpp b/tests/allocator_tests.cpp index d5ff60525b..bab64689bc 100644 --- a/tests/allocator_tests.cpp +++ b/tests/allocator_tests.cpp @@ -182,7 +182,7 @@ TEST_CASE("test memory snapshot does not wait for stream work") { auto status = snapshot.wait_for(std::chrono::seconds(1)); release.set_value(); synchronize(stream); - snapshot.get(); + (void)snapshot.get(); CHECK_EQ(status, std::future_status::ready); } diff --git a/tests/standalone/process_allocation_cap.cpp b/tests/standalone/process_allocation_cap.cpp new file mode 100644 index 0000000000..1500baac9d --- /dev/null +++ b/tests/standalone/process_allocation_cap.cpp @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. +#include "mlx/backend/common/process_allocation_cap.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/backend/common/allocation_footprint.h" + +using namespace mlx::core::allocator; +using Cap = ProcessAllocationCap; +using Lease = ProcessBackingLease; + +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + assert(refused); +} +void invariant(const Cap& cap) { + auto s = cap.snapshot(); + assert( + s.charged_bytes == + s.heap_bytes + s.live_bytes + s.cached_bytes + s.pending_bytes + + s.unreclaimed_bytes); + assert(s.charged_bytes <= s.peak_bytes && s.peak_bytes <= s.limit_bytes); +} +std::atomic releases{0}; +bool unmap(void* p, size_t n) { + ++releases; + return munmap(p, n) == 0; +} + +using Callback = void (^)(); +Callback retainedCallback(std::shared_ptr lease) { + return Block_copy(^{ + lease->finish(); + }); +} + +int main() { + const size_t page = static_cast(getpagesize()); + { + Cap c; + refuses([&] { c.install(0, 0); }); + refuses([&] { c.install(3, 4); }); + assert(!c.snapshot().installed); + c.install(16, 4); + refuses([&] { c.install(32, 4); }); + c.reserve(12); + refuses([&] { c.reserve(1); }); + c.failed_before_acquisition(12); + assert(c.snapshot().charged_bytes == 4); + invariant(c); + Cap huge; + huge.install(SIZE_MAX, SIZE_MAX - 1); + huge.reserve(1); + refuses([&] { huge.reserve(SIZE_MAX); }); + huge.failed_before_acquisition(1); + invariant(huge); + refuses([&] { round_allocation_size(SIZE_MAX, page); }); + } + { + auto c = std::make_shared(); + c->install(4 * page, page); + // Real VM backing, real copied Blocks ABI; no Metal/device initialization. + for (int i = 0; i < 1000; ++i) { + auto lease = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + lease->attach(p, unmap); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->cache(); + lease->reuse(); + lease->retire(); + lease.reset(); + assert(c->snapshot().unreclaimed_bytes == page); + assert(c->snapshot().charged_bytes == 2 * page); + callback(); + callback(); // defensive idempotence; unmap exactly once + Block_release(callback); + assert(c->snapshot().charged_bytes == page); + invariant(*c); + } + assert( + releases == 1000); // Churn does not accumulate a fake high-water cap. + } + { + auto c = std::make_shared(); + c->install(page, 0); + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + refuses( + [&] { Lease next(c, 1); }); // retained Metal equivalent blocks refund + std::thread completion([&] { callback(); }); + completion.join(); + Block_release(callback); + Lease next(c, page); // delayed completion makes capacity reusable + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + { + Lease failed(c, page); + } // no VM acquired + assert(c->snapshot().charged_bytes == 0); + auto failed = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + failed->attach(p, unmap); + failed->finish(); // Metal constructor returned nil after VM acquisition + failed.reset(); + assert(c->snapshot().charged_bytes == 0 && releases == 1001); + Lease quarantine(c, page); + quarantine.attach(nullptr, [](void*, size_t) { return false; }); + quarantine.acquired(); + quarantine.retire(); + quarantine.finish(); + assert(c->snapshot().unreclaimed_bytes == page); + refuses([&] { Lease next(c, 1); }); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + // Foreign pages stay caller-owned even after callback and ledger refund. + auto* p = static_cast(mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + assert(p != MAP_FAILED); + p[0] = 42; + { + Lease wrapper(c, page); + wrapper.acquired(); + wrapper.retire(); + wrapper.finish(); + } + assert(p[0] == 42 && c->snapshot().charged_bytes == 0); + assert(munmap(p, page) == 0); + } + { + auto c = std::make_shared(); + c->install(1, 0); + std::atomic arrived{0}, successes{0}; + std::atomic release{false}; + std::vector threads; + for (int i = 0; i < 2; ++i) { + threads.emplace_back([&] { + std::shared_ptr lease; + try { + lease = std::make_shared(c, 1); + ++successes; + } catch (...) { + } + ++arrived; + while (!release) { + std::this_thread::yield(); + } + }); + } + while (arrived != 2) { + std::this_thread::yield(); + } + assert(successes == 1 && c->snapshot().pending_bytes == 1); + release = true; + for (auto& t : threads) { + t.join(); + } + assert(c->snapshot().charged_bytes == 0); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + std::weak_ptr weak = c; + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + c.reset(); + assert(!weak.expired()); + callback(); + Block_release(callback); + assert(weak.expired()); // callback owns ledger, not an allocator stack + // reference + } + std::cout + << "PASS: install/overflow, 1000 VM churn cycles, delayed copied block, " + "failure rollback/quarantine, foreign ownership, concurrent reserve, ledger lifetime\n"; +} diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp new file mode 100644 index 0000000000..9ebd9340b5 --- /dev/null +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -0,0 +1,494 @@ +// Copyright © 2026 Eigen Labs. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/allocator.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" + +using namespace mlx::core; +namespace a = mlx::core::allocator; +void require(bool value, const char* what) { + if (!value) { + throw std::runtime_error(what); + } +} +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + require(refused, "required refusal did not occur"); +} +auto snapshot() { + return get_process_allocation_cap_snapshot(); +} +void settled(size_t expected) { + for (int i = 0; i < 200 && snapshot().charged_bytes != expected; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require( + snapshot().charged_bytes == expected, "callback credit did not settle"); +} + +// Process-local Metal API interception; no production failure switches. +IMP original_no_copy = nullptr; +IMP original_allocate = nullptr; +IMP original_residency = nullptr; +MTL::Buffer* retained_failure_buffer = nullptr; +bool reject_no_copy = false; +MTL::Buffer* intercept_no_copy( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + if (reject_no_copy) { + reject_no_copy = false; + return nullptr; + } + auto fn = reinterpret_cast( + original_no_copy); + auto* b = fn(self, selector, p, n, opts, cleanup); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::Buffer* intercept_allocate( + id self, + SEL selector, + NS::UInteger n, + MTL::ResourceOptions opts) { + auto fn = reinterpret_cast< + MTL::Buffer* (*)(id, SEL, NS::UInteger, MTL::ResourceOptions)>( + original_allocate); + auto* b = fn(self, selector, n, opts); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::ResidencySet* +fail_residency(id, SEL, MTL::ResidencySetDescriptor*, NS::Error**) { + throw std::bad_alloc(); // insert has already added its map entry +} +struct Intercept { + Method method; + IMP previous; + Intercept(MTL::Device* device, const char* selector, IMP replacement) + : method(class_getInstanceMethod( + object_getClass(reinterpret_cast(device)), + sel_registerName(selector))), + previous(nullptr) { + require(method != nullptr, "Metal interception selector missing"); + previous = method_setImplementation(method, replacement); + } + ~Intercept() { + method_setImplementation(method, previous); + } +}; + +struct PendingMetalConstruction { + std::mutex mutex; + std::condition_variable changed; + size_t entered{0}; + bool complete{false}; + std::array retained{nullptr, nullptr}; + IMP original{nullptr}; +}; +PendingMetalConstruction* pending_construction = nullptr; +MTL::Buffer* intercept_pending( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + auto& state = *pending_construction; + auto fn = reinterpret_cast( + state.original); + // Construct real Metal buffers before holding their return to the allocator. + auto* buffer = fn(self, selector, p, n, opts, cleanup); + std::unique_lock lock(state.mutex); + const auto index = state.entered++; + if (index < state.retained.size() && buffer) { + buffer->retain(); + state.retained[index] = buffer; + } + state.changed.notify_all(); + if (index < state.retained.size()) { + state.changed.wait(lock, [&] { return state.complete; }); + } + return buffer; +} +void concurrent_case(size_t page) { + auto& device = metal::device(Device::gpu); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + const auto chunk = (cap - heap) / 2; + require( + chunk % page == 0 && chunk * 2 + heap == cap, + "nonintegral test envelope"); + PendingMetalConstruction state; + pending_construction = &state; + std::array buffers{a::Buffer(nullptr), a::Buffer(nullptr)}; + std::array errors; + bool both_pending = false, contender_refused = false; + ProcessAllocationCapSnapshot pending_snapshot; + size_t actual_bytes = 0; + a::Buffer contender(nullptr); + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_pending)); + state.original = hook.previous; + std::array workers; + for (size_t i = 0; i < workers.size(); ++i) { + workers[i] = std::thread([&, i] { + try { + buffers[i] = a::malloc(chunk); + } catch (...) { + errors[i] = std::current_exception(); + } + }); + } + { + std::unique_lock lock(state.mutex); + both_pending = state.changed.wait_for( + lock, std::chrono::seconds(5), [&] { return state.entered == 2; }); + if (both_pending && state.retained[0] && state.retained[1]) { + actual_bytes = + state.retained[0]->length() + state.retained[1]->length(); + } + } + pending_snapshot = snapshot(); + if (both_pending) { + try { + contender = a::malloc(page); + } catch (const std::exception&) { + contender_refused = true; + } + } + { + std::lock_guard lock(state.mutex); + state.complete = true; + } + state.changed.notify_all(); + for (auto& worker : workers) { + worker.join(); + } + } + pending_construction = nullptr; + require( + both_pending, + "allocator did not allow two real in-flight Metal allocations"); + require(!errors[0] && !errors[1], "real Metal construction failed"); + require(actual_bytes + heap == cap, "unexpected actual Metal backing total"); + require( + pending_snapshot.pending_bytes == 2 * chunk && + pending_snapshot.charged_bytes == cap && + pending_snapshot.live_bytes == 0, + "in-flight Metal backing was not reserved before completion"); + require( + contender_refused && !contender.ptr() && state.entered == 2, + "contender reached Metal despite exhausted pending budget"); + require( + snapshot().peak_bytes == cap && snapshot().pending_bytes == 0 && + snapshot().live_bytes == 2 * chunk, + "pending-to-live transfer changed cap charge"); + for (auto buffer : buffers) { + a::free(buffer); + } + clear_cache(); + require( + snapshot().unreclaimed_bytes == 2 * chunk && + snapshot().charged_bytes == cap, + "allocator release refunded externally retained Metal backing"); + refuses([&] { a::malloc(page); }); + state.retained[0]->release(); + settled(heap + chunk); + auto recovered = a::malloc(chunk); + require( + snapshot().charged_bytes == cap && snapshot().peak_bytes == cap, + "callback recovery failed exact-cap replacement"); + a::free(recovered); + clear_cache(); + settled(heap + chunk); + state.retained[1]->release(); + settled(heap); + require( + snapshot().pending_bytes == 0 && snapshot().unreclaimed_bytes == 0, + "concurrent allocation left stranded charges"); +} +void failure_case(const std::string& mode, size_t page) { + const bool capped = mode.find("ordinary") == std::string::npos; + const bool foreign = mode.find("foreign") != std::string::npos; + auto& device = metal::device(Device::gpu); + auto& sets = device.residency_sets(); + (void)snapshot(); // initialize allocator and its fixed heap + if (capped) { + install_process_allocation_cap(8 << 20); + } + const auto baseline = capped ? snapshot().charged_bytes : 0; + set_cache_limit(0); + if (mode == "nil-foreign") { + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(p != MAP_FAILED, "foreign map failed"); + int deleter_calls = 0; + bool threw = false; + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = hook.previous; + reject_no_copy = true; + try { + array foreign_array( + p, {static_cast(page / sizeof(float))}, float32, [&](void*) { + ++deleter_calls; + }); + } catch (const std::exception&) { + threw = true; + } + } + require(munmap(p, page) == 0, "caller unmap failed"); + require(threw, "nil wrapper silently copied instead of throwing"); + require(deleter_calls == 0, "failed wrapper invoked caller deleter"); + settled(baseline); + return; + } + set_wired_limit(8 << 20); + sets.set_max_bytes_per_set(page); + const auto wired = sets.wired_size(); + const auto resources = get_num_resources(); + const auto active = get_active_memory(); + void* foreign_pages = nullptr; + if (foreign) { + foreign_pages = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(foreign_pages != MAP_FAILED, "foreign map failed"); + } + { + Intercept no_copy( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = no_copy.previous; + Intercept allocated( + device.mtl_device(), + "newBufferWithLength:options:", + reinterpret_cast(intercept_allocate)); + original_allocate = allocated.previous; + Intercept registration( + device.mtl_device(), + "newResidencySetWithDescriptor:error:", + reinterpret_cast(fail_residency)); + original_residency = registration.previous; + refuses([&] { + if (foreign) { + (void)a::make_buffer(foreign_pages, page); + } else { + (void)a::malloc(page); + } + }); + } + require( + retained_failure_buffer != nullptr, + "failure did not reach allocated buffer"); + // Keep the object alive to diagnose stale registration without dereferencing + // freed memory. On the broken path resize wires this failed allocation. + set_wired_limit((8 << 20) + page); + require( + sets.wired_size() == wired, + "failed insert left a tracked Metal allocation"); + require( + get_num_resources() == resources && get_active_memory() == active, + "failed registration changed allocator counters"); + if (capped) { + require( + snapshot().charged_bytes == baseline + page, + "retained failure refunded early"); + } + require( + retained_failure_buffer->retainCount() == 1, + "allocator leaked failed buffer reference"); + retained_failure_buffer->release(); + retained_failure_buffer = nullptr; + if (capped) { + settled(baseline); + } + if (foreign) { + require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); + } +} +int main(int argc, char** argv) { + try { + require(argc == 2, "one fresh-process case required"); + const std::string mode = argv[1]; + const size_t page = static_cast(getpagesize()); + if (mode == "concurrent") { + concurrent_case(page); + } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { + failure_case(mode, page); + } else if (mode == "late") { + auto b = a::malloc(page); + a::free(b); + clear_cache(); + refuses([] { install_process_allocation_cap(8 << 20); }); + require(!snapshot().installed, "late install mutated state"); + } else { + // The allocator's fixed heap is created when queried, before + // installation. + require(!snapshot().installed, "process already capped"); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + const auto baseline = snapshot(); + const auto heap = baseline.heap_bytes; + require( + heap > 0 && baseline.charged_bytes == heap, + "existing heap not charged"); + require(baseline.limit_bytes == cap, "wrong cap"); + if (mode == "install") { + refuses([&] { install_process_allocation_cap(cap); }); + refuses([&] { install_process_allocation_cap(cap + page); }); + require(snapshot().limit_bytes == cap, "limit changed"); + refuses([] { a::malloc(SIZE_MAX); }); + require( + snapshot().charged_bytes == heap, "overflow leaked reservation"); + auto exact = a::malloc(cap - heap); + require(snapshot().charged_bytes == cap, "exact fill mismatch"); + refuses([&] { a::malloc(page); }); + a::free(exact); + clear_cache(); + settled(heap); + } else if (mode == "retained") { + auto b = a::malloc(cap - heap); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::free(b); + clear_cache(); + require( + snapshot().unreclaimed_bytes == cap - heap, + "release refunded early"); + require(snapshot().charged_bytes == cap, "extra reference lost charge"); + refuses([&] { a::malloc(page); }); + metal->release(); + settled(heap); + auto replacement = a::malloc(cap - heap); + a::free(replacement); + clear_cache(); + settled(heap); + } else if (mode == "churn") { + auto tiny = a::malloc(8); + require( + static_cast(tiny.ptr())->heap() != nullptr, + "fixed heap unused"); + require(snapshot().charged_bytes == heap, "heap double charged"); + a::free(tiny); + clear_cache(); + for (size_t i = 0; i < 1000; ++i) { + const auto size = page * (1 + i % 31); + auto b = a::malloc(size); + const auto bytes = snapshot().charged_bytes; + auto pointer = b.ptr(); + a::free(b); + require( + snapshot().cached_bytes > 0 && snapshot().charged_bytes == bytes, + "cache transfer refunded credit"); + auto reused = a::malloc(size); + require( + reused.ptr() == pointer && snapshot().charged_bytes == bytes, + "cache reuse allocated new backing"); + a::free(reused); + clear_cache(); + settled(heap); + } + require(snapshot().peak_bytes < cap, "churn accumulated backing"); + } else if (mode == "foreign") { + void* p = mmap( + nullptr, + page, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + require(p != MAP_FAILED, "foreign map failed"); + static_cast(p)[0] = 42; + auto b = a::make_buffer(p, page); + require(b.ptr() != nullptr, "foreign wrapper failed"); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::release(b); + require( + snapshot().charged_bytes == heap + page, + "foreign wrapper refunded early"); + metal->release(); + settled(heap); + require( + static_cast(p)[0] == 42, + "caller pages invalidated"); + refuses([&] { a::make_buffer(static_cast(p) + 1, page); }); + require(munmap(p, page) == 0, "caller unmap failed"); + } else if (mode == "gpu") { + { + // Real native graph roots stay owned through GPU evaluation and + // readback. + auto input = arange(1024, float32, Device::gpu); + auto output = + add(multiply(input, array(2.0f), Device::gpu), + array(3.0f), + Device::gpu); + async_eval(output); + synchronize(default_stream(Device::gpu)); + for (int i = 0; i < 1024; ++i) { + require( + output.data()[i] == i * 2.0f + 3.0f, + "GPU value mismatch"); + } + require(snapshot().live_bytes > 0, "evaluated roots uncharged"); + } + synchronize(default_stream(Device::gpu)); + clear_cache(); + settled(heap); + } else { + throw std::runtime_error("unknown case"); + } + require(snapshot().pending_bytes == 0, "pending reservation leaked"); + require(snapshot().charged_bytes <= cap, "cap exceeded"); + } + std::cout << "PASS " << mode << '\n'; + return 0; + } catch (const std::exception& e) { + std::cerr << "FAIL " << e.what() << '\n'; + return 1; + } +} From 99dc5f4235413e466be89f8ed8ff8a6d6b71de3f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:40:16 -0700 Subject: [PATCH 31/44] Cover page-backed small buffers in detached Metal footprints Keep the allocation bound stable before and after process cap installation. Add real ordinary/capped boundary coverage without changing allocation, ownership, process-cap enforcement or the policy ABI. Document the bound. Implemented and validated with OpenAI Codex. (cherry picked from commit 4d913204912559099eff856cd56efdcc9d305d5f) --- docs/src/usage/unified_memory.rst | 18 +++++++++ fork.yaml | 7 ++++ mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 37 ++++++++++++++++++- 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 57f54bc23b..8541fec358 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -76,3 +76,21 @@ If we time the computation fully on the GPU, we get 2.8 milliseconds. But if we run the computation with ``d1=mx.gpu`` and ``d2=mx.cpu``, then the time is only about 1.4 milliseconds, about twice as fast. These times were measured on an M1 Max. + +Native allocation footprint bounds +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The C++ ``get_allocation_footprint_policy()`` returns a detached value that +bounds one allocator buffer, including alignment and permitted cache reuse. +On Metal, every positive request has a minimum footprint of one VM page +before the cache-reuse allowance is added. This covers the page-backed +fallback used by the optional process-allocation cap, including requests +smaller than one page. A policy captured before cap installation remains +valid afterward. Zero bytes still has a zero bound; arithmetic overflow is +refused. + +For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes +have an upper bound of 32,767 bytes. The bound is conservative; it is not a +measurement of the buffer's actual backing. The cap accounts for its fixed +heap separately. Per-buffer footprint bounds and the optional cap do not +replace whole-process memory budgets or OS headroom checks. diff --git a/fork.yaml b/fork.yaml index 6c2053ae3c..b1f122d03b 100644 --- a/fork.yaml +++ b/fork.yaml @@ -105,6 +105,12 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. + Metal footprint quotations apply a one-VM-page minimum to every positive request + before adding the cache-reuse allowance, covering capped page-backed fallback even + when the policy was captured before cap installation. Standalone fresh-process + ordinary and capped cases compare actual backing with detached and direct bounds + at subpage and page boundaries; zero and overflow remain explicit controls. + The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" @@ -118,6 +124,7 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 97fc684aca..037bedbd3d 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -511,7 +511,8 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; + // Capped fallback buffers use whole VM pages, including subpage requests. + return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index 9ebd9340b5..d50feb8b1b 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -350,12 +350,47 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } +void footprint_case(size_t page, bool capped) { + const auto quoted = get_allocation_footprint_policy(); + if (capped) { + install_process_allocation_cap(8 << 20); + } + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + for (auto requested : std::array{ + 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { + auto buffer = a::malloc(requested); + const auto actual = a::allocator().size(buffer); + size_t bound = 0; + const bool valid = quoted.upper_bound(requested, bound); + const auto direct = get_allocation_size_upper_bound(requested); + a::free(buffer); + clear_cache(); + settled(heap); + std::cout << "footprint requested=" << requested << " actual=" << actual + << " bound=" << bound << '\n'; + require( + valid && direct == bound, "pre-cap policy changed after installation"); + require( + actual >= requested && actual <= bound, + "actual backing exceeds quotation"); + require( + snapshot().pending_bytes == 0, "footprint check leaked reservation"); + } + require( + get_allocation_size_upper_bound(0) == 0, + "empty allocation bound changed"); + refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "concurrent") { + if (mode == "footprint" || mode == "footprint-ordinary") { + footprint_case(page, mode == "footprint"); + } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { failure_case(mode, page); From 23164b8bcf944cb92e221ee6a145e4c822d2b5d3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:05:56 -0700 Subject: [PATCH 32/44] Preserve capped Metal backing ownership and validate custom launch dimensions Prefault capped no-copy backing before handing it to Metal. Add a one-shot JACCL startup wait budget with C-facing group operations and failure cleanup tests. Validate custom Metal launch dimensions and bound the 1024-thread pipeline retry to the declared geometry. CPU policy, bridge, allocation-ledger and evaluator regressions pass. Native GPU and end-to-end qualification are tracked separately. Single-Mac release split: this pick keeps only the Metal half (CPU prefault of capped no-copy backing, validated custom-kernel launch dimensions and the bounded pipeline retry). The JACCL startup wait budget and its group API stay on darkbloom/sealed-all-sum with the rest of the two-Mac code. (cherry picked from commit 54975cd06be07a51128e48754729a5620e04a325) --- docs/src/dev/custom_metal_kernels.rst | 14 ++++ docs/src/usage/unified_memory.rst | 6 ++ fork.yaml | 14 ++++ mlx/backend/metal/allocator.cpp | 7 ++ mlx/backend/metal/custom_kernel.cpp | 73 +++++++++++++---- python/tests/test_metal_threadgroup_bounds.py | 80 +++++++++++++++++++ .../process_allocation_cap_metal.cpp | 55 ++++++++++++- 7 files changed, 234 insertions(+), 15 deletions(-) create mode 100644 python/tests/test_metal_threadgroup_bounds.py diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index 6a9471fd51..f3ad478438 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -466,3 +466,17 @@ We can then implement the backwards pass as follows: There's an even larger speed up for the vjp: ``676.4ms -> 16.7ms => 40x speed up`` + +Threadgroup compiler capacity +----------------------------- + +Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, +a thread count within UINT32_MAX, and axes within the device limits. Invalid +geometry is refused before output allocation. A capable original pipeline is +kept. For a nonempty grid containing complete 1024-wide groups, exactly +``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +uses a distinct source/library identity and must itself support the full +threadgroup. Compile errors and remaining capacity failures propagate. This +does not change shader math, precision, group/grid axes, or guarantee that a +particular shader can compile at 1024. Other geometries receive no retry. diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 8541fec358..10d925c349 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -94,3 +94,9 @@ have an upper bound of 32,767 bytes. The bound is conservative; it is not a measurement of the buffer's actual backing. The cap accounts for its fixed heap separately. Per-buffer footprint bounds and the optional cap do not replace whole-process memory budgets or OS headroom checks. + +Capped no-copy backing is touched once per VM page from the CPU before it is +wrapped as a Metal buffer. This makes the process physical footprint include +pages first written by GPU work. It preserves the allocator cap and does not +replace load admission or operating-system memory headroom. The fresh-process +``gpu-footprint`` regression checks GPU-written backing; it requires Metal. diff --git a/fork.yaml b/fork.yaml index b1f122d03b..5df09b43b7 100644 --- a/fork.yaml +++ b/fork.yaml @@ -110,6 +110,8 @@ def: when the policy was captured before cap installation. Standalone fresh-process ordinary and capped cases compare actual backing with detached and direct bounds at subpage and page boundaries; zero and overflow remain explicit controls. + Capped no-copy pages are first touched on the CPU so process physical + footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" @@ -186,6 +188,18 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" + - title: "Validated custom Metal threadgroups and bounded compiler retry" + description: | + Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond + the device limits before allocating outputs. A nonempty grid with complete + x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + declaration. The original capable pipeline is retained; retry compilation + and the selected pipeline's actual capacity remain authoritative. Other + geometries refuse without clamping. Shader math and dispatch axes do not change. + globs: + - "python/tests/test_metal_threadgroup_bounds.py" + - "docs/src/dev/custom_metal_kernels.rst" - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 037bedbd3d..9db99ed59f 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -216,6 +216,13 @@ Buffer MetalAllocator::malloc_capped( throw std::bad_alloc(); } lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + // Fault every page from the CPU before wrapping it. Pages a no-copy + // buffer first receives through the GPU are not charged to this + // process's physical footprint, which hides the model from the OS + // memory-pressure accounting and from Activity Monitor. + for (size_t offset = 0; offset < charge; offset += vm_page_size) { + static_cast(pages)[offset] = 0; + } buffer = device_->newBuffer( pages, charge, resource_options, ^(void*, NS::UInteger) { lease->finish(); diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 65c33d2448..33f502a718 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -8,6 +8,8 @@ #include #include +#include +#include namespace mlx::core::fast { @@ -18,7 +20,30 @@ void CustomKernel::eval_gpu( (void)is_precompiled_; (void)shared_memory_; + const auto [tx, ty, tz] = threadgroup_; + const auto [gx, gy, gz] = grid_; + if (tx <= 0 || ty <= 0 || tz <= 0 || gx < 0 || gy < 0 || gz < 0) { + throw std::invalid_argument("Invalid custom kernel launch dimensions."); + } + size_t tg_size = 1; + for (auto dimension : {tx, ty, tz}) { + if (static_cast(dimension) > + std::numeric_limits::max() / tg_size) { + throw std::invalid_argument( + "Custom kernel threadgroup size exceeds 32 bits."); + } + tg_size *= static_cast(dimension); + } + auto& s = stream(); + auto& d = metal::device(s.device); + const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + if (static_cast(tx) > device_max.width || + static_cast(ty) > device_max.height || + static_cast(tz) > device_max.depth) { + throw std::invalid_argument( + "Custom kernel threadgroup exceeds device dimensions."); + } for (auto i : mutable_inputs_) { if (i < 0 || i >= inputs.size()) { @@ -56,13 +81,45 @@ void CustomKernel::eval_gpu( checked_inputs.push_back(check_input(in)); } - auto& d = metal::device(s.device); - std::string lib_name = fmt::format( "{}_{:x}_{}", name_, std::hash{}(source_), compile_options_); auto lib = d.get_library( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); + auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && + gx % tx == 0 && gy > 0 && gz > 0; + if (tg_size > max_tg_size && retry_geometry) { + const std::string declaration = "[[kernel]] void " + name_ + "("; + const auto position = source_.find(declaration); + if (position != std::string::npos && + source_.find(declaration, position + declaration.size()) == + std::string::npos) { + // Keep the dispatch geometry and give the compiler its required size. + auto constrained_source = source_; + constrained_source.insert( + position, + "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + + ")]] "); + auto constrained_name = + lib_name + "_required_tg_" + std::to_string(tg_size); + auto constrained_lib = d.get_library( + constrained_name, compile_options_, [&constrained_source] { + return metal::utils() + constrained_source; + }); + kernel = d.get_kernel(name_, constrained_lib); + max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + } + } + if (tg_size > max_tg_size) { + std::ostringstream msg; + msg << "Thread group size (" << tg_size << ") is greater than " + << " the maximum allowed threads per threadgroup (" << max_tg_size + << "). Kernel: " << name_ << "; threadgroup=(" << tx << "," << ty << "," + << tz << "); grid=(" << gx << "," << gy << "," << gz << ")."; + throw std::invalid_argument(msg.str()); + } + auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); int index = 0; @@ -96,18 +153,6 @@ void CustomKernel::eval_gpu( index++; } - const auto [tx, ty, tz] = threadgroup_; - auto tg_size = tx * ty * tz; - auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - if (tg_size > max_tg_size) { - std::ostringstream msg; - msg << "Thread group size (" << tg_size << ") is greater than " - << " the maximum allowed threads per threadgroup (" << max_tg_size - << ")."; - throw std::invalid_argument(msg.str()); - } - - const auto [gx, gy, gz] = grid_; MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); MTL::Size grid_dims = MTL::Size(gx, gy, gz); diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py new file mode 100644 index 0000000000..f074676be6 --- /dev/null +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -0,0 +1,80 @@ +# Custom Metal launch validation. + +import unittest + +import mlx.core as mx + + +@unittest.skipIf(not mx.metal.is_available(), "Metal is unavailable; not a pass") +class ThreadgroupBoundsTests(unittest.TestCase): + def test_invalid_dimensions_precede_compilation(self): + # A compiler attempt would raise RuntimeError instead of ValueError. + cases = [ + ((0, 1, 1), (1024, 1, 1), "dimensions"), + ((1, 0, 1), (1024, 1, 1), "dimensions"), + ((1, 1, 0), (1024, 1, 1), "dimensions"), + ((-1, 1, 1), (1024, 1, 1), "dimensions"), + ((1, -1, 1), (1024, 1, 1), "dimensions"), + ((1, 1, -1), (1024, 1, 1), "dimensions"), + ((1024, 1, 1), (-1, 1, 1), "dimensions"), + ((1024, 1, 1), (1, -1, 1), "dimensions"), + ((1024, 1, 1), (1, 1, -1), "dimensions"), + ((65536, 65536, 1), (1024, 1, 1), "32 bits"), + ( + (2147483647, 2147483647, 2147483647), + (1024, 1, 1), + "32 bits", + ), + ((2147483647, 1, 1), (1024, 1, 1), "device dimensions"), + ((1, 2147483647, 1), (1024, 1, 1), "device dimensions"), + ((1, 1, 2147483647), (1024, 1, 1), "device dimensions"), + ] + for index, (group, grid, message) in enumerate(cases): + with self.subTest(group=group, grid=grid): + kernel = mx.fast.metal_kernel( + name=f"invalid_geometry_{index}", + input_names=[], + output_names=["out"], + source="INTENTIONAL_INVALID_METAL;", + ensure_row_contiguous=True, + ) + with self.assertRaisesRegex(ValueError, message): + outputs = kernel( + inputs=[], + grid=grid, + threadgroup=group, + output_shapes=[(1,)], + output_dtypes=[mx.uint32], + init_value=0, + stream=mx.gpu, + ) + mx.eval(outputs) + + def test_legal_launch_keeps_threads_and_values(self): + for group in [32, 256, 1024]: + kernel = mx.fast.metal_kernel( + name="thread_count_and_math", + input_names=["a"], + output_names=["out", "count"], + source=""" + uint i = thread_position_in_grid.x; + out[i] = a[i] * 2.0f + 1.0f; + count[i] = threads_per_threadgroup.x; + """, + ) + a = mx.arange(2048, dtype=mx.float32) + out, count = kernel( + inputs=[a], + grid=(2048, 1, 1), + threadgroup=(group, 1, 1), + output_shapes=[(2048,), (2048,)], + output_dtypes=[mx.float32, mx.uint32], + stream=mx.gpu, + ) + mx.eval(out, count) + self.assertTrue(mx.array_equal(out, a * 2 + 1).item()) + self.assertTrue(mx.all(count == group).item()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index d50feb8b1b..ed5c4959f7 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Eigen Labs. +#include #include #include #include @@ -383,12 +384,64 @@ void footprint_case(size_t page, bool capped) { refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); } +// Capped backing is owned no-copy VM. Pages first written by the GPU must +// still be charged to this process, or the OS cannot see the model's memory. +size_t physical_footprint() { + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + require( + task_info( + mach_task_self(), + TASK_VM_INFO, + reinterpret_cast(&info), + &count) == KERN_SUCCESS, + "task footprint unavailable"); + return static_cast(info.phys_footprint); +} + +bool footprint_growth_at_least(size_t before, size_t after, size_t expected) { + return after >= before && after - before >= expected; +} + +void footprint_delta_case() { + require( + !footprint_growth_at_least(1024, 1023, 512), + "decrease wrapped into growth"); + require( + !footprint_growth_at_least(1024, 1024, 1), "unchanged footprint grew"); + require(!footprint_growth_at_least(1024, 1535, 512), "short growth passed"); + require(footprint_growth_at_least(1024, 1536, 512), "exact growth failed"); + require( + !footprint_growth_at_least(SIZE_MAX, 0, 1), "maximum baseline wrapped"); +} + +void gpu_footprint_case() { + const size_t bytes = size_t(512) << 20; + install_process_allocation_cap(size_t(2) << 30); + const auto before = physical_footprint(); + { + auto filled = + full({int(bytes / sizeof(float))}, 1.0f, float32, Device::gpu); + eval(filled); + synchronize(default_stream(Device::gpu)); + const auto after = physical_footprint(); + require( + footprint_growth_at_least(before, after, bytes - (bytes >> 4)), + "GPU-written capped backing missing from process footprint"); + } + clear_cache(); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "footprint" || mode == "footprint-ordinary") { + if (mode == "footprint-delta") { + footprint_delta_case(); + } else if (mode == "gpu-footprint") { + gpu_footprint_case(); + } else if (mode == "footprint" || mode == "footprint-ordinary") { footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); From 2bba342de9759c6e8d1048e13fcc30868c86374c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:32:34 -0700 Subject: [PATCH 33/44] fix(metal): retry 512-thread kernels with explicit compiler capacity (cherry picked from commit 3a1791192aaf6b834d8e2a12fde623026045a4ec) --- docs/src/dev/custom_metal_kernels.rst | 8 ++++---- fork.yaml | 4 ++-- mlx/backend/metal/custom_kernel.cpp | 4 ++-- python/tests/test_metal_threadgroup_bounds.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index f3ad478438..8c160167ef 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -473,10 +473,10 @@ Threadgroup compiler capacity Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, a thread count within UINT32_MAX, and axes within the device limits. Invalid geometry is refused before output allocation. A capable original pipeline is -kept. For a nonempty grid containing complete 1024-wide groups, exactly -``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL -``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +kept. For a nonempty grid containing complete 512- or 1024-wide groups, exactly +``(512, 1, 1)`` or ``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(requestedWidth)`` declaration attribute. The retry uses a distinct source/library identity and must itself support the full threadgroup. Compile errors and remaining capacity failures propagate. This does not change shader math, precision, group/grid axes, or guarantee that a -particular shader can compile at 1024. Other geometries receive no retry. +particular shader can compile at the requested width. Other geometries receive no retry. diff --git a/fork.yaml b/fork.yaml index 5df09b43b7..1c6588ee55 100644 --- a/fork.yaml +++ b/fork.yaml @@ -192,8 +192,8 @@ def: description: | Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond the device limits before allocating outputs. A nonempty grid with complete - x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient - pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + x-axis multiples of the group width and groups (512,1,1) or (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(requestedWidth) on its unique generated declaration. The original capable pipeline is retained; retry compilation and the selected pipeline's actual capacity remain authoritative. Other geometries refuse without clamping. Shader math and dispatch axes do not change. diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 33f502a718..3ee8f3d029 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -87,8 +87,8 @@ void CustomKernel::eval_gpu( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && - gx % tx == 0 && gy > 0 && gz > 0; + const bool retry_geometry = (tx == 512 || tx == 1024) && ty == 1 && tz == 1 && + gx >= tx && gx % tx == 0 && gy > 0 && gz > 0; if (tg_size > max_tg_size && retry_geometry) { const std::string declaration = "[[kernel]] void " + name_ + "("; const auto position = source_.find(declaration); diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py index f074676be6..49466d0440 100644 --- a/python/tests/test_metal_threadgroup_bounds.py +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -51,7 +51,7 @@ def test_invalid_dimensions_precede_compilation(self): mx.eval(outputs) def test_legal_launch_keeps_threads_and_values(self): - for group in [32, 256, 1024]: + for group in [32, 256, 512, 1024]: kernel = mx.fast.metal_kernel( name="thread_count_and_math", input_names=["a"], From 4a3557460a1ba308fcc2b8b0b62bbeec20569355 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:06:36 -0700 Subject: [PATCH 34/44] Revert "Cover page-backed small buffers in detached Metal footprints" This reverts commit 99dc5f4235413e466be89f8ed8ff8a6d6b71de3f. --- docs/src/usage/unified_memory.rst | 14 ++------ fork.yaml | 6 ---- mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 35 ------------------- 4 files changed, 3 insertions(+), 55 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 10d925c349..2430806e2c 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -82,18 +82,8 @@ Native allocation footprint bounds The C++ ``get_allocation_footprint_policy()`` returns a detached value that bounds one allocator buffer, including alignment and permitted cache reuse. -On Metal, every positive request has a minimum footprint of one VM page -before the cache-reuse allowance is added. This covers the page-backed -fallback used by the optional process-allocation cap, including requests -smaller than one page. A policy captured before cap installation remains -valid afterward. Zero bytes still has a zero bound; arithmetic overflow is -refused. - -For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes -have an upper bound of 32,767 bytes. The bound is conservative; it is not a -measurement of the buffer's actual backing. The cap accounts for its fixed -heap separately. Per-buffer footprint bounds and the optional cap do not -replace whole-process memory budgets or OS headroom checks. +Zero bytes has a zero bound; arithmetic overflow is refused. The bound does +not apply a one-page minimum to requests smaller than one page. Capped no-copy backing is touched once per VM page from the CPU before it is wrapped as a Metal buffer. This makes the process physical footprint include diff --git a/fork.yaml b/fork.yaml index 1c6588ee55..3c9334dcaa 100644 --- a/fork.yaml +++ b/fork.yaml @@ -105,11 +105,6 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. - Metal footprint quotations apply a one-VM-page minimum to every positive request - before adding the cache-reuse allowance, covering capped page-backed fallback even - when the policy was captured before cap installation. Standalone fresh-process - ordinary and capped cases compare actual backing with detached and direct bounds - at subpage and page boundaries; zero and overflow remain explicit controls. Capped no-copy pages are first touched on the CPU so process physical footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. @@ -126,7 +121,6 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" - - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9db99ed59f..6ae5030267 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -518,8 +518,7 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - // Capped fallback buffers use whole VM pages, including subpage requests. - return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; + return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index ed5c4959f7..23c9ded0da 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -351,39 +351,6 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } -void footprint_case(size_t page, bool capped) { - const auto quoted = get_allocation_footprint_policy(); - if (capped) { - install_process_allocation_cap(8 << 20); - } - set_cache_limit(0); - const auto heap = snapshot().heap_bytes; - for (auto requested : std::array{ - 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { - auto buffer = a::malloc(requested); - const auto actual = a::allocator().size(buffer); - size_t bound = 0; - const bool valid = quoted.upper_bound(requested, bound); - const auto direct = get_allocation_size_upper_bound(requested); - a::free(buffer); - clear_cache(); - settled(heap); - std::cout << "footprint requested=" << requested << " actual=" << actual - << " bound=" << bound << '\n'; - require( - valid && direct == bound, "pre-cap policy changed after installation"); - require( - actual >= requested && actual <= bound, - "actual backing exceeds quotation"); - require( - snapshot().pending_bytes == 0, "footprint check leaked reservation"); - } - require( - get_allocation_size_upper_bound(0) == 0, - "empty allocation bound changed"); - refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); -} - // Capped backing is owned no-copy VM. Pages first written by the GPU must // still be charged to this process, or the OS cannot see the model's memory. size_t physical_footprint() { @@ -441,8 +408,6 @@ int main(int argc, char** argv) { footprint_delta_case(); } else if (mode == "gpu-footprint") { gpu_footprint_case(); - } else if (mode == "footprint" || mode == "footprint-ordinary") { - footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { From 6ee3062c7fcba32f36eb50cbb9df3d1d755735ba Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:23:01 -0700 Subject: [PATCH 35/44] fork.yaml: keep describing docs/src/usage/unified_memory.rst The file still differs from upstream (capped no-copy backing paragraph), so its glob stays in the allocator accounting section. --- fork.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/fork.yaml b/fork.yaml index 3c9334dcaa..40e9ba2465 100644 --- a/fork.yaml +++ b/fork.yaml @@ -121,6 +121,7 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before From 39296f3fd6e48ef952aa91003bb16fe5b3552bd7 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:36:58 -0700 Subject: [PATCH 36/44] Revert "Cover page-backed small buffers in detached Metal footprints" This reverts commit 4d913204, as the single-Mac core did (mlx#37 4a355746, 6ee3062c). The one-page minimum charged MTP drafters without declared layouts 37-671 MB per token and made each GLM MTP request reserve about 11.3 GB fixed instead of 4.1 GB. The single-Mac revert cannot reach this branch through the merge (its net change there is zero), so it is applied here explicitly. unified_memory.rst and process_allocation_cap_metal.cpp now match the single-Mac core; allocator.cpp keeps this branch's cached maxBufferLength. Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/unified_memory.rst | 14 ++------ fork.yaml | 5 --- mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 35 ------------------- 4 files changed, 3 insertions(+), 54 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 10d925c349..2430806e2c 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -82,18 +82,8 @@ Native allocation footprint bounds The C++ ``get_allocation_footprint_policy()`` returns a detached value that bounds one allocator buffer, including alignment and permitted cache reuse. -On Metal, every positive request has a minimum footprint of one VM page -before the cache-reuse allowance is added. This covers the page-backed -fallback used by the optional process-allocation cap, including requests -smaller than one page. A policy captured before cap installation remains -valid afterward. Zero bytes still has a zero bound; arithmetic overflow is -refused. - -For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes -have an upper bound of 32,767 bytes. The bound is conservative; it is not a -measurement of the buffer's actual backing. The cap accounts for its fixed -heap separately. Per-buffer footprint bounds and the optional cap do not -replace whole-process memory budgets or OS headroom checks. +Zero bytes has a zero bound; arithmetic overflow is refused. The bound does +not apply a one-page minimum to requests smaller than one page. Capped no-copy backing is touched once per VM page from the CPU before it is wrapped as a Metal buffer. This makes the process physical footprint include diff --git a/fork.yaml b/fork.yaml index a496f4206e..2264f7d698 100644 --- a/fork.yaml +++ b/fork.yaml @@ -128,11 +128,6 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. - Metal footprint quotations apply a one-VM-page minimum to every positive request - before adding the cache-reuse allowance, covering capped page-backed fallback even - when the policy was captured before cap installation. Standalone fresh-process - ordinary and capped cases compare actual backing with detached and direct bounds - at subpage and page boundaries; zero and overflow remain explicit controls. Capped no-copy pages are first touched on the CPU so process physical footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index a0f3ad4b96..962ce2951c 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -520,8 +520,7 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - // Capped fallback buffers use whole VM pages, including subpage requests. - return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; + return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index ed5c4959f7..23c9ded0da 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -351,39 +351,6 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } -void footprint_case(size_t page, bool capped) { - const auto quoted = get_allocation_footprint_policy(); - if (capped) { - install_process_allocation_cap(8 << 20); - } - set_cache_limit(0); - const auto heap = snapshot().heap_bytes; - for (auto requested : std::array{ - 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { - auto buffer = a::malloc(requested); - const auto actual = a::allocator().size(buffer); - size_t bound = 0; - const bool valid = quoted.upper_bound(requested, bound); - const auto direct = get_allocation_size_upper_bound(requested); - a::free(buffer); - clear_cache(); - settled(heap); - std::cout << "footprint requested=" << requested << " actual=" << actual - << " bound=" << bound << '\n'; - require( - valid && direct == bound, "pre-cap policy changed after installation"); - require( - actual >= requested && actual <= bound, - "actual backing exceeds quotation"); - require( - snapshot().pending_bytes == 0, "footprint check leaked reservation"); - } - require( - get_allocation_size_upper_bound(0) == 0, - "empty allocation bound changed"); - refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); -} - // Capped backing is owned no-copy VM. Pages first written by the GPU must // still be charged to this process, or the OS cannot see the model's memory. size_t physical_footprint() { @@ -441,8 +408,6 @@ int main(int argc, char** argv) { footprint_delta_case(); } else if (mode == "gpu-footprint") { gpu_footprint_case(); - } else if (mode == "footprint" || mode == "footprint-ordinary") { - footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { From a1d7567988a7789fa0a8be7e0b64fdacf48469f1 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:37:21 -0700 Subject: [PATCH 37/44] fork.yaml: describe the host cuts and the streamed sealed sum The fork-diff gate failed on this branch since 76209564 and 8c6f9e77: mlx/array.cpp and mlx/distributed/sealed_stream.h were changed but not described. Add a section for the custom-kernel launch and graph bookkeeping cuts, and the streamed pieces to the sealed all-sum section. Co-Authored-By: Claude Opus 5.5 --- fork.yaml | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/fork.yaml b/fork.yaml index 2264f7d698..ab502aac94 100644 --- a/fork.yaml +++ b/fork.yaml @@ -294,12 +294,16 @@ def: gathers the frames, opens the peer frame and adds in rank order. Missing codecs and authentication failures refuse evaluation without a plaintext fallback. The distributed primitive retains its temporary arrays until - the queued work completes. + the queued work completes. On a two-rank JACCL mesh the sum streams in 256 KiB + pieces, each with its own AES-256-GCM tag, over `MeshImpl::exchange`: a piece is + sent as soon as it is sealed and opened and added as soon as it lands. Other + groups keep the seal-gather-open path. globs: - "mlx/distributed/CMakeLists.txt" - "mlx/distributed/primitives.h" - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" + - "mlx/distributed/sealed_stream.h" - title: "Fused cross-device fence update" description: | Opt-in (`MLX_METAL_FUSED_FENCE_UPDATE=1`, fast synch only). A GPU array that the CPU @@ -339,6 +343,22 @@ def: - "mlx/backend/cuda/fence.cpp" - "mlx/utils.h" - "docs/src/usage/environment_variables.rst" + - title: "Cheaper custom-kernel launches and graph bookkeeping" + description: | + Host time only: generated sources, kernel names, buffers and dispatch order do not + change. Custom-kernel primitives share the cached generated source and resolve the + pipeline once per source; repeat launches skip rebuilding the name, template string + and cache key, and bind inputs directly when none needs a contiguous copy. Graph + teardown dedups node inputs with a small vector, `eval_impl`'s per-node map is a flat + open-addressing map, and allocation reads the device's maximum buffer length once. + globs: + - "mlx/array.cpp" + - "mlx/transforms.cpp" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/cuda/custom_kernel.cpp" - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a From 360d11b90dcf26fe1b0c9be1789d5cb9d2c49f80 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:03:32 -0700 Subject: [PATCH 38/44] distributed: sealed reduce-scatter and all-gather for two ranks `reduce_scatter_sealed` and `all_gather_sealed` (SealedReduceScatter, SealedAllGather) seal and authenticate every piece through the same codec as `all_sum_sealed`. The streamed path generalises the streamed all-sum (source and addend sealed apart; the gather adds nothing), with a gathered path for groups without exchange. The reduce-scatter adds each element's two partials in float32 in rank order and rounds once, as the all-sum does; the gather is a byte copy. Every sealed collective now draws its counter from one process-wide sequence (`next_sealed_counter`, which was the all-sum's own counter): the same values for a graph of all-sums only, and no counter is reused across collective kinds. A peer piece that does not authenticate is refused, and the codec stays refused. Co-Authored-By: Claude Opus 5.5 --- mlx/distributed/primitives.h | 41 ++++- mlx/distributed/sealed.cpp | 289 +++++++++++++++++++++++++++++++- mlx/distributed/sealed.h | 16 ++ mlx/distributed/sealed_stream.h | 18 +- 4 files changed, 356 insertions(+), 8 deletions(-) diff --git a/mlx/distributed/primitives.h b/mlx/distributed/primitives.h index f5a9b0d631..ea72abce4d 100644 --- a/mlx/distributed/primitives.h +++ b/mlx/distributed/primitives.h @@ -92,7 +92,46 @@ class SealedAllSum : public DistPrimitive { void eval_streamed(const array& in, array& out); SealCodec codec_; - static inline std::atomic counter_{0}; +}; + +/// The sealed reduce-scatter and all-gather (`reduce_scatter_sealed`, +/// `all_gather_sealed`, sealed.h): the all-sum's frames and counters, half +/// the bytes each. Every sealed collective draws its counter from one +/// sequence (`detail::next_sealed_counter`), in evaluation order. +class SealedReduceScatter : public DistPrimitive { + public: + SealedReduceScatter(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + const char* name() const override { + return "SealedReduceScatter"; + } + + private: + SealCodec codec_; +}; + +class SealedAllGather : public DistPrimitive { + public: + SealedAllGather(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + const char* name() const override { + return "SealedAllGather"; + } + + private: + SealCodec codec_; }; class AllGather : public DistPrimitive { diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index 9a3d60eba6..26714fd470 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "mlx/allocator.h" #include "mlx/backend/cpu/copy.h" @@ -19,6 +20,12 @@ namespace mlx::core::distributed { namespace { std::mutex codec_mutex; std::optional installed_codec; +// One counter for every sealed collective, advanced per evaluation; both +// ranks evaluate the same graph in the same order. +std::atomic sealed_counter{0}; +uint64_t next_sealed_counter() { + return sealed_counter++; +} } // namespace void set_seal_codec(SealCodec codec) { @@ -70,6 +77,67 @@ array all_sum_sealed( {x}); } +namespace { +// [1, T, ...] split on its second axis between two ranks. +void require_rows(const array& x, Group& group, const char* name, bool even) { + if (group.size() != 2) { + throw std::invalid_argument(std::string(name) + " needs exactly two ranks"); + } + if (x.dtype() != float32 && x.dtype() != bfloat16 && x.dtype() != float16) { + throw std::invalid_argument( + std::string(name) + " moves float32, bfloat16 or float16 only"); + } + if (x.ndim() < 2 || x.shape(0) != 1 || x.shape(1) < 1 || + (even && x.shape(1) % 2 != 0)) { + throw std::invalid_argument( + std::string(name) + " needs [1, T, ...]" + (even ? " with T even" : "")); + } +} +SealCodec require_codec(const char* name) { + auto codec = seal_codec(); + if (!codec.has_value()) { + throw std::runtime_error( + std::string(name) + + " no seal codec is installed: a partial never crosses the link in the clear"); + } + return *codec; +} +} // namespace + +array reduce_scatter_sealed( + const array& x, + std::optional group_, + StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + require_rows(x, group, "[reduce_scatter_sealed]", true); + auto codec = require_codec("[reduce_scatter_sealed]"); + auto shape = x.shape(); + shape[1] /= 2; + auto stream = detail::communication_stream(group, s); + return array( + std::move(shape), + x.dtype(), + std::make_shared(stream, group, codec), + {x}); +} + +array all_gather_sealed( + const array& x, + std::optional group_, + StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + require_rows(x, group, "[all_gather_sealed]", false); + auto codec = require_codec("[all_gather_sealed]"); + auto shape = x.shape(); + shape[1] *= 2; + auto stream = detail::communication_stream(group, s); + return array( + std::move(shape), + x.dtype(), + std::make_shared(stream, group, codec), + {x}); +} + namespace { template void add_span(const T* rank0, const T* rank1, T* out, size_t n) { @@ -131,7 +199,7 @@ void SealedAllSum::eval_cpu( peer.set_data(allocator::malloc(n)); int rank = group().rank(); - uint64_t counter = counter_++; + uint64_t counter = next_sealed_counter(); auto codec = codec_; auto& encoder = cpu::get_command_encoder(stream()); encoder.set_input_array(in); @@ -231,7 +299,7 @@ void SealedAllSum::eval_streamed(const array& in, array& out) { received.set_data(allocator::malloc(layout.frame())); int rank = group().rank(); - uint64_t counter = counter_++; + uint64_t counter = next_sealed_counter(); auto& encoder = cpu::get_command_encoder(stream()); encoder.set_input_array(in); encoder.set_output_array(out); @@ -246,7 +314,7 @@ void SealedAllSum::eval_streamed(const array& in, array& out) { mine = sealed.data(), theirs = received.data()]() { detail::StreamedSum sum( - codec, layout, counter, rank, src, dst, mine, theirs, add); + codec, layout, counter, rank, src, src, dst, mine, theirs, add); bool ok = sum.run([&group]( const char* send, char* recv, @@ -270,4 +338,219 @@ void SealedAllSum::eval_gpu(const std::vector&, std::vector&) { "[SealedAllSum::eval_gpu] has no GPU implementation."); } +namespace { + +detail::AddPieceFn add_piece_for(Dtype dtype, const char* name) { + switch (dtype) { + case float32: + return detail::add_piece; + case bfloat16: + return detail::add_piece; + case float16: + return detail::add_piece; + default: + throw std::runtime_error(std::string(name) + " unsupported dtype"); + } +} + +// The streamed half-size exchange both new collectives run: `send` (n bytes) +// sealed and sent, the peer's n bytes opened into `out` and, with `add`, +// `addend` added in rank order. +void run_streamed( + const SealCodec& codec, + Group& group, + Stream stream, + const array& in, + array& out, + size_t n, + const char* send, + const char* addend, + char* dst, + detail::AddPieceFn add, + const char* name) { + detail::PieceLayout layout(n, codec.piece_bytes); + if (layout.count > 0xFFFF) { + throw std::invalid_argument( + std::string(name) + " a frame needs more than 65,535 sealed pieces"); + } + array sealed({static_cast(layout.frame())}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(layout.frame())); + array received({static_cast(layout.frame())}, uint8, nullptr, {}); + received.set_data(allocator::malloc(layout.frame())); + int rank = group.rank(); + uint64_t counter = next_sealed_counter(); + auto& encoder = cpu::get_command_encoder(stream); + encoder.set_input_array(in); + encoder.set_output_array(out); + std::string label = name; + encoder.dispatch([codec, + layout, + counter, + rank, + add, + label, + raw = group.raw_group(), + send, + addend, + dst, + mine = sealed.data(), + theirs = received.data()]() { + detail::StreamedSum exchange( + codec, layout, counter, rank, send, addend, dst, mine, theirs, add); + bool ok = exchange.run([&raw]( + const char* sent, + char* recv, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + raw->exchange(sent, recv, bytes, ready, arrived); + }); + if (!ok) { + throw std::runtime_error( + label + + " a piece did not seal or a peer piece did not authenticate: refused"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(received); +} + +// The same without an exchange: seal `send`, gather both frames, open the +// peer's into `dst` and, with `add`, add `addend` in rank order. +void run_gathered( + const SealCodec& codec, + Group& group, + Stream stream, + const array& in, + array& out, + size_t n, + const char* send, + const char* addend, + char* dst, + detail::AddPieceFn add, + const char* name) { + size_t frame = n + codec.overhead; + array sealed({static_cast(frame)}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(frame)); + array gathered({static_cast(2 * frame)}, uint8, nullptr, {}); + gathered.set_data(allocator::malloc(2 * frame)); + int rank = group.rank(); + uint64_t counter = next_sealed_counter(); + std::string label = name; + auto& encoder = cpu::get_command_encoder(stream); + encoder.set_input_array(in); + encoder.set_output_array(sealed); + encoder.dispatch( + [codec, send, dst = sealed.data(), n, frame, counter, label]() { + if (codec.seal(codec.ctx, send, n, dst, counter) != 0) { + std::memset(dst, 0, frame); + throw std::runtime_error(label + " the codec refused to seal"); + } + }); + distributed::detail::all_gather(group, sealed, gathered, stream); + encoder.set_input_array(gathered); + encoder.set_output_array(out); + encoder.dispatch([codec, + frames = gathered.data(), + addend, + dst, + n, + frame, + counter, + rank, + add, + label]() { + const char* peer_frame = frames + (rank == 0 ? frame : 0); + if (codec.open(codec.ctx, peer_frame, n, dst, counter, 1 - rank) != 0) { + throw std::runtime_error( + label + " a peer frame did not authenticate: refused"); + } + if (add != nullptr) { + add(rank, addend, dst, n); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(gathered); +} + +} // namespace + +// Rank r keeps rows [r * T / 2, (r + 1) * T / 2): it sends the peer's half +// of its partial and adds the peer's partial of its own half to its own, in +// rank order (rank 0 + rank 1), as the all-sum does for every element. +void SealedReduceScatter::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + size_t half = out.nbytes(); + int rank = group().rank(); + const char* src = in.data(); + const char* send = src + (rank == 0 ? half : 0); + const char* mine = src + (rank == 0 ? 0 : half); + auto add = add_piece_for(in.dtype(), "[reduce_scatter_sealed]"); + auto group = this->group(); + if (codec_.streamed() && group.raw_group()->supports_exchange()) { + run_streamed( + codec_, group, stream(), in, out, half, send, mine, out.data(), + add, "[reduce_scatter_sealed]"); + } else { + run_gathered( + codec_, group, stream(), in, out, half, send, mine, out.data(), + add, "[reduce_scatter_sealed]"); + } + if (!inputs[0].flags().row_contiguous) { + cpu::get_command_encoder(stream()).add_temporary(in); + } +} + +void SealedReduceScatter::eval_gpu( + const std::vector&, + std::vector&) { + throw std::runtime_error( + "[SealedReduceScatter::eval_gpu] has no GPU implementation."); +} + +// Rank 0's rows then rank 1's: this rank's rows are copied in place and the +// peer's arrive sealed. +void SealedAllGather::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + size_t n = in.nbytes(); + int rank = group().rank(); + char* own = out.data() + (rank == 0 ? 0 : n); + char* theirs = out.data() + (rank == 0 ? n : 0); + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(out); + encoder.dispatch( + [src = in.data(), own, n]() { std::memcpy(own, src, n); }); + auto group = this->group(); + if (codec_.streamed() && group.raw_group()->supports_exchange()) { + run_streamed( + codec_, group, stream(), in, out, n, in.data(), nullptr, theirs, + nullptr, "[all_gather_sealed]"); + } else { + run_gathered( + codec_, group, stream(), in, out, n, in.data(), nullptr, theirs, + nullptr, "[all_gather_sealed]"); + } + if (!inputs[0].flags().row_contiguous) { + encoder.add_temporary(in); + } +} + +void SealedAllGather::eval_gpu(const std::vector&, std::vector&) { + throw std::runtime_error( + "[SealedAllGather::eval_gpu] has no GPU implementation."); +} + } // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h index cc5deb424e..291e6cefff 100644 --- a/mlx/distributed/sealed.h +++ b/mlx/distributed/sealed.h @@ -95,4 +95,20 @@ MLX_API array all_sum_sealed( std::optional group = std::nullopt, StreamOrDevice s = {}); +// Two ranks, `x` shaped [1, T, ...]. Rank r receives rows +// [r * T / 2, (r + 1) * T / 2) of the sum, added in rank order exactly as +// all_sum_sealed adds them (T even): each rank sends only the peer's half. +MLX_API array reduce_scatter_sealed( + const array& x, + std::optional group = std::nullopt, + StreamOrDevice s = {}); + +// Two ranks, `x` shaped [1, T, ...] (this rank's rows): [1, 2T, ...], rank +// 0's rows then rank 1's, each rank sending only its own. A copy: every +// element keeps its bits. +MLX_API array all_gather_sealed( + const array& x, + std::optional group = std::nullopt, + StreamOrDevice s = {}); + } // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h index 8d4e3aa16b..e4fceca5d8 100644 --- a/mlx/distributed/sealed_stream.h +++ b/mlx/distributed/sealed_stream.h @@ -106,7 +106,12 @@ inline size_t seal_lanes() { return lanes; } -// One streamed sealed sum, run on the calling thread (a CPU-stream task). +// One streamed sealed exchange, run on the calling thread (a CPU-stream +// task): `send` is sealed and sent piece by piece; each peer piece is opened +// into `out` and, with `add`, `addend` (this rank's own values for the same +// elements) is added to it in rank order. The all-sum sends and adds its +// whole partial; the reduce-scatter sends the peer's half and adds its own; +// the all-gather sends its own half and only opens. class StreamedSum { public: StreamedSum( @@ -114,7 +119,8 @@ class StreamedSum { const PieceLayout& layout, uint64_t counter, int rank, - const char* mine, + const char* send, + const char* addend, char* out, char* sealed, char* received, @@ -123,7 +129,8 @@ class StreamedSum { layout_(layout), counter_(counter), rank_(rank), - mine_(mine), + mine_(send), + addend_(addend), out_(out), sealed_(sealed), received_(received), @@ -273,7 +280,9 @@ class StreamedSum { failed_.store(true); return; } - add_(rank_, mine_ + layout_.plain(k), dst, len); + if (add_ != nullptr) { + add_(rank_, addend_ + layout_.plain(k), dst, len); + } } const SealCodec codec_; @@ -281,6 +290,7 @@ class StreamedSum { const uint64_t counter_; const int rank_; const char* const mine_; + const char* const addend_; char* const out_; char* const sealed_; char* const received_; From 95938c4bb756fc8b40bfac6ebec28a690efb7cfd Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:08:59 -0700 Subject: [PATCH 39/44] Format inherited native cluster sources for pinned CI The same change as 66edc771 on fix/cluster-metal-fence-wait (applied here with cherry-pick, so that merge stays clean): clang-format and cmake-format on the six paths that failed this pull request's Check Lint job (mesh_impl.h, sealed.cpp, sealed_stream.h, fast_primitives.h, tests/jaccl/CMakeLists.txt, tests/jaccl/exchange_tests.cpp). Layout only; no source body changes. Tests: clang-format 21 (the 21.x line that .pre-commit-config.yaml pins): no changes left in any .h or .cpp file of the tree. Co-Authored-By: Claude Opus 5.5 --- mlx/distributed/jaccl/lib/jaccl/mesh_impl.h | 4 +- mlx/distributed/sealed.cpp | 60 ++++++++++++++++----- mlx/distributed/sealed_stream.h | 4 +- mlx/fast_primitives.h | 4 +- tests/jaccl/CMakeLists.txt | 3 +- tests/jaccl/exchange_tests.cpp | 10 ++-- 6 files changed, 62 insertions(+), 23 deletions(-) diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index 35e8b8594d..47ecc24c1b 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -58,7 +58,9 @@ class MeshImpl { int64_t N = buffer_size / sizeof(T); // Frames in flight per peer (staging holds this many; NUM_BUFFERS >= it). constexpr int PIPELINE = MESH_PIPELINE; - static_assert(MESH_PIPELINE <= NUM_BUFFERS, "mesh pipeline exceeds registered buffers"); + static_assert( + MESH_PIPELINE <= NUM_BUFFERS, + "mesh pipeline exceeds registered buffers"); constexpr int WC_NUM = PIPELINE * MESH_MAX_PEERS * 2; int64_t total = static_cast(size); int num_peers = size_ - 1; diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index 26714fd470..dd2ae0bca7 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -1,8 +1,8 @@ // Copyright © 2026 Darkbloom. +#include #include #include -#include #include #include #include @@ -32,8 +32,7 @@ void set_seal_codec(SealCodec codec) { if (codec.seal != nullptr && codec.open != nullptr && (codec.seal_piece != nullptr || codec.open_piece != nullptr)) { if (!codec.streamed() || codec.piece_bytes < 4096 || - codec.piece_bytes > (size_t(16) << 20) || - codec.piece_bytes % 16 != 0) { + codec.piece_bytes > (size_t(16) << 20) || codec.piece_bytes % 16 != 0) { throw std::invalid_argument( "[set_seal_codec] a streamed codec needs both piece callbacks and " "piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]"); @@ -90,7 +89,8 @@ void require_rows(const array& x, Group& group, const char* name, bool even) { if (x.ndim() < 2 || x.shape(0) != 1 || x.shape(1) < 1 || (even && x.shape(1) % 2 != 0)) { throw std::invalid_argument( - std::string(name) + " needs [1, T, ...]" + (even ? " with T even" : "")); + std::string(name) + " needs [1, T, ...]" + + (even ? " with T even" : "")); } } SealCodec require_codec(const char* name) { @@ -495,12 +495,30 @@ void SealedReduceScatter::eval_cpu( auto group = this->group(); if (codec_.streamed() && group.raw_group()->supports_exchange()) { run_streamed( - codec_, group, stream(), in, out, half, send, mine, out.data(), - add, "[reduce_scatter_sealed]"); + codec_, + group, + stream(), + in, + out, + half, + send, + mine, + out.data(), + add, + "[reduce_scatter_sealed]"); } else { run_gathered( - codec_, group, stream(), in, out, half, send, mine, out.data(), - add, "[reduce_scatter_sealed]"); + codec_, + group, + stream(), + in, + out, + half, + send, + mine, + out.data(), + add, + "[reduce_scatter_sealed]"); } if (!inputs[0].flags().row_contiguous) { cpu::get_command_encoder(stream()).add_temporary(in); @@ -536,12 +554,30 @@ void SealedAllGather::eval_cpu( auto group = this->group(); if (codec_.streamed() && group.raw_group()->supports_exchange()) { run_streamed( - codec_, group, stream(), in, out, n, in.data(), nullptr, theirs, - nullptr, "[all_gather_sealed]"); + codec_, + group, + stream(), + in, + out, + n, + in.data(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); } else { run_gathered( - codec_, group, stream(), in, out, n, in.data(), nullptr, theirs, - nullptr, "[all_gather_sealed]"); + codec_, + group, + stream(), + in, + out, + n, + in.data(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); } if (!inputs[0].flags().row_contiguous) { encoder.add_temporary(in); diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h index e4fceca5d8..fc0fbfdb91 100644 --- a/mlx/distributed/sealed_stream.h +++ b/mlx/distributed/sealed_stream.h @@ -225,7 +225,9 @@ class StreamedSum { QosOverride() : token_( raise_qos() ? pthread_override_qos_class_start_np( - pthread_self(), QOS_CLASS_USER_INTERACTIVE, 0) + pthread_self(), + QOS_CLASS_USER_INTERACTIVE, + 0) : nullptr) {} QosOverride(const QosOverride&) = delete; QosOverride& operator=(const QosOverride&) = delete; diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 3b8d4b71ce..6d5effd791 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -510,9 +510,7 @@ using ScalarArg = std::variant; // Generated source of a custom kernel. `metal_kernel` makes one for each // kernel and template instance, and all its launches share it. struct CustomKernelSource { - explicit CustomKernelSource( - std::string source, - std::string library_name = "") + explicit CustomKernelSource(std::string source, std::string library_name = "") : source(std::move(source)), library_name(std::move(library_name)) {} std::string source; diff --git a/tests/jaccl/CMakeLists.txt b/tests/jaccl/CMakeLists.txt index 75324951e9..9768aeea88 100644 --- a/tests/jaccl/CMakeLists.txt +++ b/tests/jaccl/CMakeLists.txt @@ -33,7 +33,8 @@ target_include_directories(startup_wait_budget_api_tests PRIVATE ../..) jaccl_test(exchange_tests) target_include_directories(exchange_tests PRIVATE ../..) add_test(NAME exchange COMMAND exchange_tests) -set_tests_properties(exchange PROPERTIES ENVIRONMENT "JACCL_TIMEOUT_ACTION=throw") +set_tests_properties(exchange PROPERTIES ENVIRONMENT + "JACCL_TIMEOUT_ACTION=throw") add_test(NAME startup_wait_budget_api COMMAND startup_wait_budget_api_tests) add_test(NAME startup_wait_budget_groups COMMAND startup_wait_budget_group_tests) diff --git a/tests/jaccl/exchange_tests.cpp b/tests/jaccl/exchange_tests.cpp index d579062d04..134adb5bd3 100644 --- a/tests/jaccl/exchange_tests.cpp +++ b/tests/jaccl/exchange_tests.cpp @@ -202,8 +202,7 @@ struct Codec { static uint64_t key(uint64_t counter, int sender, uint32_t piece) { return mix(counter * 0x10001 ^ uint64_t(sender) << 60 ^ uint64_t(piece)); } - static void - crypt(const char* in, char* out, size_t len, uint64_t key) { + static void crypt(const char* in, char* out, size_t len, uint64_t key) { for (size_t i = 0; i < len; ++i) { out[i] = char(in[i] ^ char(mix(key ^ (i / 8)) >> (8 * (i % 8)))); } @@ -340,7 +339,8 @@ std::vector reference(const SumResult& r) { auto b = reinterpret_cast(r.partial[1].data()); auto out = reinterpret_cast(sum.data()); for (size_t i = 0; i < sum.size() / sizeof(T); ++i) { - out[i] = static_cast(static_cast(a[i]) + static_cast(b[i])); + out[i] = + static_cast(static_cast(a[i]) + static_cast(b[i])); } return sum; } @@ -444,8 +444,8 @@ int main() { passed &= group( streamed_sum_identical, "streamed sum bit-identical to gathered sum"); passed &= group(streamed_sum_tamper, "streamed sum refuses a changed byte"); - passed &= group( - streamed_sum_seal_failure, "streamed sum seal failure sends zeros"); + passed &= + group(streamed_sum_seal_failure, "streamed sum seal failure sends zeros"); passed &= group(exchange_failure, "exchange failure closes the group"); const auto& ledger = fixture::ledger(); if (ledger.queue_pairs != 0 || ledger.completion_queues != 0 || From 2b5253ad0f8a56518f115a9bcec64d4e03aba781 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:10:33 -0700 Subject: [PATCH 40/44] test(jaccl): pass the all-sum addend in the streamed-sum exchange test 360d11b9 (sealed reduce-scatter and all-gather) added the `addend` argument to detail::StreamedSum, but tests/jaccl/exchange_tests.cpp still called the old constructor, so the tests/jaccl project did not compile (CI does not build it). The all-sum sends and adds its whole partial, as all_sum_sealed does (send = addend = partial). Tests: tests/jaccl with ASan and UBSan: 14 of 14 passed (exchange, startup_wait_budget, startup_wait_budget_api, startup_wait_budget_groups, send_frame and the nine progress_guard modes); with TSan: 14 of 14 passed. Co-Authored-By: Claude Opus 5.5 --- tests/jaccl/exchange_tests.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/jaccl/exchange_tests.cpp b/tests/jaccl/exchange_tests.cpp index 134adb5bd3..341c12fa89 100644 --- a/tests/jaccl/exchange_tests.cpp +++ b/tests/jaccl/exchange_tests.cpp @@ -313,6 +313,7 @@ SumResult streamed_sum( counter, rank, r.partial[rank].data(), + r.partial[rank].data(), r.out[rank].data(), mine.data(), theirs.data(), From a135f491df4b50cbb2b0cf4321fa702cb80f9321 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 23 Oct 2026 12:32:23 -0700 Subject: [PATCH 41/44] Keep sealed collective callbacks portable outside Apple platforms Guard Apple dispatch, QoS and Blocks code. Preserve the Apple path and use synchronous authenticated frame callbacks elsewhere. Add CPU coverage for framing, failures and callback ownership. Validated both selected branches on macOS with C++20 and warnings as errors; actual hosted Linux execution remains pending. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9ec023f929d67e96c55b46ae3e8510e806d03f0b) --- fork.yaml | 6 +- mlx/distributed/sealed.cpp | 10 + mlx/distributed/sealed_stream.h | 18 ++ tests/CMakeLists.txt | 1 + tests/distributed_sealed_stream_tests.cpp | 248 ++++++++++++++++++++++ 5 files changed, 282 insertions(+), 1 deletion(-) create mode 100644 tests/distributed_sealed_stream_tests.cpp diff --git a/fork.yaml b/fork.yaml index 42d0f6d54c..bd78e1ba12 100644 --- a/fork.yaml +++ b/fork.yaml @@ -337,13 +337,17 @@ def: the queued work completes. On a two-rank JACCL mesh the sum streams in 256 KiB pieces, each with its own AES-256-GCM tag, over `MeshImpl::exchange`: a piece is sent as soon as it is sealed and opened and added as soon as it lands. Other - groups keep the seal-gather-open path. + groups keep the seal-gather-open path. Non-Apple builds use synchronous + piece sealing and opening without Apple dispatch or QoS APIs, preserving + the authenticated wire format and rank-ordered arithmetic. Apple keeps + its existing parallel path. globs: - "mlx/distributed/CMakeLists.txt" - "mlx/distributed/primitives.h" - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" - "mlx/distributed/sealed_stream.h" + - "tests/distributed_sealed_stream_tests.cpp" - title: "Fused cross-device fence update" description: | Opt-in (`MLX_METAL_FUSED_FENCE_UPDATE=1`, fast synch only). A GPU array that the CPU diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index dd2ae0bca7..d0009d5bec 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -1,6 +1,8 @@ // Copyright © 2026 Darkbloom. +#ifdef __APPLE__ #include +#endif #include #include #include @@ -166,11 +168,19 @@ void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { return; } size_t spans = (n + kSpan - 1) / kSpan; +#ifdef __APPLE__ dispatch_apply(spans, DISPATCH_APPLY_AUTO, ^(size_t i) { size_t begin = i * kSpan; size_t count = std::min(kSpan, n - begin); add_span(rank0 + begin, rank1 + begin, out + begin, count); }); +#else + for (size_t i = 0; i < spans; ++i) { + size_t begin = i * kSpan; + size_t count = std::min(kSpan, n - begin); + add_span(rank0 + begin, rank1 + begin, out + begin, count); + } +#endif } } // namespace diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h index fc0fbfdb91..9171431209 100644 --- a/mlx/distributed/sealed_stream.h +++ b/mlx/distributed/sealed_stream.h @@ -7,9 +7,11 @@ #pragma once +#ifdef __APPLE__ #include #include #include +#endif #include #include @@ -155,6 +157,7 @@ class StreamedSum { }); return !failed_.load(); } +#ifdef __APPLE__ QosOverride boost; Workers workers; StreamedSum* self = this; @@ -164,6 +167,12 @@ class StreamedSum { self->seal_in_order(); }); } +#else + // The portable path uses no background workers or platform QoS APIs. + for (size_t k = 0; k < layout_.count; ++k) { + seal(k); + } +#endif size_t sealed_prefix = 0; size_t dispatched = 0; exchange( @@ -183,16 +192,23 @@ class StreamedSum { layout_.sealed_end(dispatched) <= end; ++dispatched) { size_t k = dispatched; +#ifdef __APPLE__ workers.async(^{ self->open_and_add(k); }); +#else + open_and_add(k); +#endif } }); +#ifdef __APPLE__ workers.wait(); +#endif return !failed_.load(); } private: +#ifdef __APPLE__ // Waits for every block before the frames and `out` can be released. class Workers { public: @@ -241,6 +257,8 @@ class StreamedSum { pthread_override_t token_; }; +#endif + void seal_in_order() { for (size_t k; (k = next_seal_.fetch_add(1)) < layout_.count;) { seal(k); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8a00f114d8..83876c2f4c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,6 +32,7 @@ target_sources( custom_vjp_tests.cpp creations_tests.cpp device_tests.cpp + distributed_sealed_stream_tests.cpp einsum_tests.cpp export_import_tests.cpp eval_tests.cpp diff --git a/tests/distributed_sealed_stream_tests.cpp b/tests/distributed_sealed_stream_tests.cpp new file mode 100644 index 0000000000..01db881750 --- /dev/null +++ b/tests/distributed_sealed_stream_tests.cpp @@ -0,0 +1,248 @@ +// Copyright © 2026 Darkbloom. + +#include +#include +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" +#include "mlx/distributed/sealed_stream.h" + +namespace { +namespace sealed = mlx::core::distributed; +namespace detail = mlx::core::distributed::detail; + +// A deterministic test codec, not encryption. Tags bind all callback fields. +struct Codec { + int rank; + size_t total; + int fail_seal = -1; + std::atomic active{0}; + std::atomic seals{0}; + std::atomic opens{0}; + std::atomic bad_identity{false}; + std::atomic changed_thread{false}; + const std::thread::id caller = std::this_thread::get_id(); + static constexpr uint64_t counter = 19; + + bool identity( + size_t bytes, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t whole) { + const size_t expected_pieces = std::max(size_t(1), (total + 4095) / 4096); + bool valid = count == counter && whole == total && + pieces == expected_pieces && piece < expected_pieces && + size_t(piece) * 4096 <= total; + valid = + valid && bytes == std::min(size_t(4096), total - size_t(piece) * 4096); + if (!valid) + bad_identity = true; + if (caller != std::this_thread::get_id()) + changed_thread = true; + return valid; + } + + static unsigned char tag( + uint64_t counter, + int rank, + uint32_t piece, + uint32_t pieces, + size_t total, + size_t index) { + return static_cast( + counter + rank + piece + pieces + total + index); + } + + static int seal( + void* context, + const void* input, + size_t bytes, + void* output, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t total) { + auto& self = *static_cast(context); + ++self.active; + ++self.seals; + if (!self.identity(bytes, count, piece, pieces, total) || + int(piece) == self.fail_seal) { + --self.active; + return 1; + } + auto in = static_cast(input); + auto out = static_cast(output); + for (size_t i = 0; i < bytes; ++i) + out[i] = in[i] ^ (self.rank + 41); + for (size_t i = 0; i < sealed::kSealTagBytes; ++i) + out[bytes + i] = tag(count, self.rank, piece, pieces, total, i); + --self.active; + return 0; + } + + static int open( + void* context, + const void* input, + size_t bytes, + void* output, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer) { + auto& self = *static_cast(context); + ++self.active; + ++self.opens; + auto in = static_cast(input); + auto out = static_cast(output); + bool valid = self.identity(bytes, count, piece, pieces, total) && + peer == 1 - self.rank; + for (size_t i = 0; i < sealed::kSealTagBytes; ++i) + valid &= in[bytes + i] == tag(count, peer, piece, pieces, total, i); + if (valid) + for (size_t i = 0; i < bytes; ++i) + out[i] = in[i] ^ (peer + 41); + --self.active; + return valid ? 0 : 1; + } + + sealed::SealCodec value() { + sealed::SealCodec result; + result.ctx = this; + result.seal_piece = seal; + result.open_piece = open; + result.piece_bytes = 4096; + return result; + } +}; + +struct Fixture { + Codec local; + Codec peer; + detail::PieceLayout layout; + std::vector send, addend, remote, output; + std::vector sent_frame, received_frame, peer_frame; + + Fixture(int rank, size_t count) + : local{rank, count * sizeof(float)}, + peer{1 - rank, count * sizeof(float)}, + layout(count * sizeof(float), 4096), + send(std::max(size_t(1), count)), + addend(std::max(size_t(1), count)), + remote(std::max(size_t(1), count)), + output(std::max(size_t(1), count), -100), + sent_frame(layout.frame(), char(0x5a)), + received_frame(layout.frame()), + peer_frame(layout.frame()) { + for (size_t i = 0; i < count; ++i) { + send[i] = float(i % 31) / 8; + addend[i] = float(i % 17) / 4; + remote[i] = float(i % 13) / 2; + } + for (size_t k = 0; k < layout.count; ++k) + Codec::seal( + &peer, + reinterpret_cast(remote.data()) + layout.plain(k), + layout.length(k), + peer_frame.data() + layout.sealed(k), + Codec::counter, + uint32_t(k), + uint32_t(layout.count), + layout.bytes); + } + + bool run(bool add, bool throw_exchange = false) { + detail::StreamedSum sum( + local.value(), + layout, + Codec::counter, + local.rank, + reinterpret_cast(send.data()), + reinterpret_cast(addend.data()), + reinterpret_cast(output.data()), + sent_frame.data(), + received_frame.data(), + add ? detail::add_piece : nullptr); + return sum.run([&](const char*, + char* received, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!ready(bytes)) { + if (std::chrono::steady_clock::now() >= deadline) + throw std::runtime_error("test readiness timeout"); + std::this_thread::yield(); + } + std::memcpy(received, peer_frame.data(), bytes); + for (size_t k = 0; k < layout.count; ++k) { + arrived(layout.sealed_end(k) - 1); + CHECK(local.opens <= int(k)); + arrived(layout.sealed_end(k)); + if (throw_exchange) + throw std::runtime_error("test exchange failure"); + } + }); + } +}; +} // namespace + +TEST_CASE("sealed pieces preserve exact rank sum and gathered bytes") { + for (int rank : {0, 1}) { + for (size_t count : {size_t(0), size_t(17), size_t(4097)}) { + for (bool add : {false, true}) { + Fixture fixture(rank, count); + CHECK(fixture.run(add)); + std::vector expected(count); + for (size_t i = 0; i < count; ++i) + expected[i] = !add ? fixture.remote[i] + : rank == 0 ? fixture.addend[i] + fixture.remote[i] + : fixture.remote[i] + fixture.addend[i]; + if (count != 0) + CHECK( + std::memcmp( + expected.data(), + fixture.output.data(), + count * sizeof(float)) == 0); + CHECK(fixture.local.active == 0); + CHECK(fixture.local.seals == fixture.layout.count); + CHECK(fixture.local.opens == fixture.layout.count); + CHECK_FALSE(fixture.local.bad_identity); +#ifndef __APPLE__ + CHECK_FALSE(fixture.local.changed_thread); +#endif + } + } + } +} + +TEST_CASE("sealed pieces refuse changed peer tags and zero failed seals") { + Fixture tampered(0, 4097); + tampered.peer_frame[tampered.layout.sealed_end(1) - 1] ^= 1; + CHECK_FALSE(tampered.run(true)); + CHECK(tampered.local.active == 0); + for (size_t i = tampered.layout.plain(1) / sizeof(float); i < + (tampered.layout.plain(1) + tampered.layout.length(1)) / sizeof(float); + ++i) + CHECK(tampered.output[i] == -100); + Fixture failed(1, 4097); + failed.local.fail_seal = 1; + CHECK_FALSE(failed.run(true)); + CHECK(failed.local.active == 0); + for (size_t i = failed.layout.sealed(1); i < failed.layout.sealed_end(1); ++i) + CHECK(failed.sent_frame[i] == 0); +} + +TEST_CASE("sealed exchange errors leave no callback owner running") { + Fixture fixture(0, 4097); + CHECK_THROWS_WITH(fixture.run(true, true), "test exchange failure"); + CHECK(fixture.local.active == 0); + CHECK(fixture.local.seals == fixture.layout.count); + CHECK(fixture.local.opens == 1); +} From be4b55b17342cffae592ee7b879d8e98737b0927 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 27 Oct 2026 17:55:25 -0500 Subject: [PATCH 42/44] Keep fenced inputs in device memory; take fenced waits first; refuse sealed frames over INT_MAX - metal_kernel.cpp: a fenced custom-kernel input is always declared in the device address space. A 0-d or small input was `constant`, and the GPU may load a fixed-size constant buffer before the kernel runs, so before MLX_FENCED_INPUT_WAIT, which could read the CPU-stream value too early. - custom_kernel.cpp: take the fenced waits at the start of eval_gpu, before the launch checks that can throw. A throw left the wait in the thread-local list, where a later kernel at the same address took it. - sealed.cpp: frame lengths go through detail::frame_extent, which refuses a frame of more than INT_MAX bytes instead of wrapping the int array shape (a float32 partial of 1 GiB gathers more than 2 GiB). Test added. - sealed.h: state the codec contract: the counter restarts at 0 in each process (keys must not be reused across processes), and the codec's ctx must outlive the graphs built with it. Co-Authored-By: Claude Opus 5.5 --- fork.yaml | 5 ++++- mlx/backend/common/metal_kernel.cpp | 12 +++++++--- mlx/backend/metal/custom_kernel.cpp | 27 +++++++++++++---------- mlx/distributed/sealed.cpp | 22 +++++++++++------- mlx/distributed/sealed.h | 6 +++++ mlx/distributed/sealed_stream.h | 13 +++++++++++ tests/distributed_sealed_stream_tests.cpp | 17 ++++++++++++++ 7 files changed, 78 insertions(+), 24 deletions(-) diff --git a/fork.yaml b/fork.yaml index e3a45871a6..a2c736d66b 100644 --- a/fork.yaml +++ b/fork.yaml @@ -372,7 +372,10 @@ def: kernel starts after every pass and kernel encoded before it (`wait_for_all_pending` and a barrier), as the `fence_wait` pass does, so the CPU work it waits for never waits for it. MLX keeps the separate wait when the input is copied first, when another - GPU stream feeds the CPU in the same eval, and while exporting. The declaration is not + GPU stream feeds the CPU in the same eval, and while exporting. A fenced input is + always in the device address space, never `constant`, because the GPU may load a + small constant buffer before the kernel's wait. The kernel takes its waits before any + argument check can throw, so no wait is left for a later kernel. The declaration is not part of the exported schema. Synchronization only: results do not change. The `fence_wait` dispatch itself makes its pass wait for every pass in flight diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index cb0c6061b7..6801355203 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -156,10 +156,16 @@ std::string write_signature( bool is_mutable = std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != mutable_inputs.end(); + // A fenced input is read after the kernel waits for its CPU producer, + // so it stays in the device address space: the GPU may load a small + // constant buffer before the kernel runs, which is before the wait. + bool is_fenced = + std::find(fenced_inputs.begin(), fenced_inputs.end(), i) != + fenced_inputs.end(); auto dtype = get_type_string(arr.dtype()); - std::string location = !is_mutable && arr.size() < max_constant_array_size - ? "constant" - : "device"; + bool in_constant = + !is_mutable && !is_fenced && arr.size() < max_constant_array_size; + std::string location = in_constant ? "constant" : "device"; std::string ref = !is_mutable && arr.ndim() == 0 ? "&" : "*"; kernel_source += is_mutable ? " " : " const "; kernel_source += location; diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 7d3cd6612d..8b96fee838 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -21,6 +21,14 @@ void CustomKernel::eval_gpu( (void)is_precompiled_; (void)shared_memory_; + // Take the waits on fenced inputs that Fence::wait_in_consumer gave to this + // kernel before any check below can throw, so that no wait is left for a + // later kernel at the same address. + std::vector fenced; + if (!fenced_inputs_.empty()) { + fenced = metal::take_fenced_inputs(this); + } + const auto [tx, ty, tz] = threadgroup_; const auto [gx, gy, gz] = grid_; if (tx <= 0 || ty <= 0 || tz <= 0 || gx < 0 || gy < 0 || gz < 0) { @@ -57,19 +65,14 @@ void CustomKernel::eval_gpu( } } - // Waits on fenced inputs that Fence::wait_in_consumer gave to this kernel. // An input that is copied first is read before the kernel: wait for it now. - std::vector fenced; - if (!fenced_inputs_.empty()) { - fenced = metal::take_fenced_inputs(this); - for (auto it = fenced.begin(); it != fenced.end();) { - auto& in = inputs[it->input]; - if (ensure_row_contiguous_ && !in.flags().row_contiguous) { - metal::encode_fence_wait(s, in, *it); - it = fenced.erase(it); - } else { - ++it; - } + for (auto it = fenced.begin(); it != fenced.end();) { + auto& in = inputs[it->input]; + if (ensure_row_contiguous_ && !in.flags().row_contiguous) { + metal::encode_fence_wait(s, in, *it); + it = fenced.erase(it); + } else { + ++it; } } diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp index d0009d5bec..5b09c3d53f 100644 --- a/mlx/distributed/sealed.cpp +++ b/mlx/distributed/sealed.cpp @@ -201,9 +201,11 @@ void SealedAllSum::eval_cpu( } size_t n = in.nbytes(); size_t frame = n + codec_.overhead; - array sealed({static_cast(frame)}, uint8, nullptr, {}); + int sealed_len = detail::frame_extent(frame, "[all_sum_sealed]"); + int gathered_len = detail::frame_extent(2 * frame, "[all_sum_sealed]"); + array sealed({sealed_len}, uint8, nullptr, {}); sealed.set_data(allocator::malloc(frame)); - array gathered({static_cast(2 * frame)}, uint8, nullptr, {}); + array gathered({gathered_len}, uint8, nullptr, {}); gathered.set_data(allocator::malloc(2 * frame)); array peer(in.shape(), in.dtype(), nullptr, {}); peer.set_data(allocator::malloc(n)); @@ -303,9 +305,10 @@ void SealedAllSum::eval_streamed(const array& in, array& out) { default: throw std::runtime_error("[all_sum_sealed] unsupported dtype"); } - array sealed({static_cast(layout.frame())}, uint8, nullptr, {}); + int frame_len = detail::frame_extent(layout.frame(), "[all_sum_sealed]"); + array sealed({frame_len}, uint8, nullptr, {}); sealed.set_data(allocator::malloc(layout.frame())); - array received({static_cast(layout.frame())}, uint8, nullptr, {}); + array received({frame_len}, uint8, nullptr, {}); received.set_data(allocator::malloc(layout.frame())); int rank = group().rank(); @@ -383,9 +386,10 @@ void run_streamed( throw std::invalid_argument( std::string(name) + " a frame needs more than 65,535 sealed pieces"); } - array sealed({static_cast(layout.frame())}, uint8, nullptr, {}); + int frame_len = detail::frame_extent(layout.frame(), name); + array sealed({frame_len}, uint8, nullptr, {}); sealed.set_data(allocator::malloc(layout.frame())); - array received({static_cast(layout.frame())}, uint8, nullptr, {}); + array received({frame_len}, uint8, nullptr, {}); received.set_data(allocator::malloc(layout.frame())); int rank = group.rank(); uint64_t counter = next_sealed_counter(); @@ -440,9 +444,11 @@ void run_gathered( detail::AddPieceFn add, const char* name) { size_t frame = n + codec.overhead; - array sealed({static_cast(frame)}, uint8, nullptr, {}); + int sealed_len = detail::frame_extent(frame, name); + int gathered_len = detail::frame_extent(2 * frame, name); + array sealed({sealed_len}, uint8, nullptr, {}); sealed.set_data(allocator::malloc(frame)); - array gathered({static_cast(2 * frame)}, uint8, nullptr, {}); + array gathered({gathered_len}, uint8, nullptr, {}); gathered.set_data(allocator::malloc(2 * frame)); int rank = group.rank(); uint64_t counter = next_sealed_counter(); diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h index 291e6cefff..655d8d308b 100644 --- a/mlx/distributed/sealed.h +++ b/mlx/distributed/sealed.h @@ -84,6 +84,12 @@ struct SealCodec { // Installs (or, with a null seal, removes) the process's codec. A sealed // all-sum without a codec is refused when the graph is built. A streamed // codec needs piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]. +// +// The counter starts at 0 in each process, is shared by every group and is +// not reset by this call, so a codec must not reuse its keys across +// processes (the counters would repeat). Each sealed primitive keeps a copy +// of the codec it was built with: `ctx` must stay valid until every graph +// built with it has been evaluated or released. MLX_API void set_seal_codec(SealCodec codec); MLX_API std::optional seal_codec(); diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h index 9171431209..445613a81c 100644 --- a/mlx/distributed/sealed_stream.h +++ b/mlx/distributed/sealed_stream.h @@ -18,7 +18,10 @@ #include #include #include +#include #include +#include +#include #include "mlx/distributed/sealed.h" @@ -30,6 +33,16 @@ using ArrivedFn = std::function; using ExchangeFn = std::function< void(const char*, char*, size_t, const ReadyFn&, const ArrivedFn&)>; +// The length of a uint8 frame array of `bytes` bytes. Array shapes are int, +// so a longer frame is refused instead of wrapping to a wrong length. +inline int frame_extent(size_t bytes, const char* name) { + if (bytes > static_cast(std::numeric_limits::max())) { + throw std::invalid_argument( + std::string(name) + " a sealed frame is longer than 2^31 - 1 bytes"); + } + return static_cast(bytes); +} + // The streamed frame of an n-byte partial. struct PieceLayout { size_t bytes; diff --git a/tests/distributed_sealed_stream_tests.cpp b/tests/distributed_sealed_stream_tests.cpp index 01db881750..6f1121f9d8 100644 --- a/tests/distributed_sealed_stream_tests.cpp +++ b/tests/distributed_sealed_stream_tests.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -246,3 +247,19 @@ TEST_CASE("sealed exchange errors leave no callback owner running") { CHECK(fixture.local.seals == fixture.layout.count); CHECK(fixture.local.opens == 1); } + +TEST_CASE("sealed frames longer than an int array shape are refused") { + const size_t longest = std::numeric_limits::max(); + CHECK(detail::frame_extent(0, "[test]") == 0); + CHECK( + detail::frame_extent(longest, "[test]") == + std::numeric_limits::max()); + CHECK_THROWS_WITH_AS( + detail::frame_extent(longest + 1, "[test]"), + "[test] a sealed frame is longer than 2^31 - 1 bytes", + std::invalid_argument); + // A float32 partial of 1 GiB gathers two frames of more than 1 GiB. + CHECK_THROWS_AS( + detail::frame_extent(2 * ((size_t(1) << 30) + 16), "[test]"), + std::invalid_argument); +} From 169802f4b779ac9920dda97dca53b3fcf573a578 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 27 Oct 2026 18:01:39 -0500 Subject: [PATCH 43/44] Apply clang-format to the fenced-input check in write_signature Co-Authored-By: Claude Opus 5.5 --- mlx/backend/common/metal_kernel.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index 6801355203..b656d33dc5 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -159,8 +159,7 @@ std::string write_signature( // A fenced input is read after the kernel waits for its CPU producer, // so it stays in the device address space: the GPU may load a small // constant buffer before the kernel runs, which is before the wait. - bool is_fenced = - std::find(fenced_inputs.begin(), fenced_inputs.end(), i) != + bool is_fenced = std::find(fenced_inputs.begin(), fenced_inputs.end(), i) != fenced_inputs.end(); auto dtype = get_type_string(arr.dtype()); bool in_constant = From 94baa02561b4ead3f9bb8434102887cd03ccaec3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 27 Oct 2026 18:24:42 -0500 Subject: [PATCH 44/44] Make the JACCL timing tests independent of the runner's scheduling delay progress_guard_checks: the limit of the checks mode goes from 250 ms to 2000 ms. Every case is written in terms of the limit, so the ratio stays the same: below-limit gaps are limit / 2 (ratio 1:2) and must not trip, and over-limit stalls must still trip inside [limit, limit + slack]. At 250 ms a hosted runner that oversleeps a 125 ms gap by more than 125 ms let the waiting rank time out and close its endpoint, so the sender then failed with "mesh send: no completion". At 2000 ms the gap can absorb 1 s of delay. startup_wait_budget_groups: the expiry cases set the fake fabric's idle wait to 0. The guard samples the startup deadline once in 1024 empty polls, and each empty poll slept up to 1 ms. Hosted runners stretch that sleep to 4-8 ms, so 1024 polls passed the fake poll's 8 s deadline, refuses() saw "The fake poll reached its deadline" instead of "absolute startup", and the uncaught assertion aborted the process at about 8.1 s. Spinning polls are what the hardware does. No library code changes. Co-Authored-By: Claude Opus 5.5 --- tests/jaccl/progress_guard_tests.cpp | 9 ++++++--- tests/jaccl/startup_wait_budget_group_tests.cpp | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/tests/jaccl/progress_guard_tests.cpp b/tests/jaccl/progress_guard_tests.cpp index 4cf652c187..34890cf953 100644 --- a/tests/jaccl/progress_guard_tests.cpp +++ b/tests/jaccl/progress_guard_tests.cpp @@ -1241,7 +1241,7 @@ void default_exit_check(const char* program) { } // namespace // One mode in each process: -// checks all cases with a limit of 250 ms +// checks all cases with a limit of 2000 ms // disabled a limit of 0: a stalled call continues to wait // alias the limit comes from MLX_JACCL_PROGRESS_TIMEOUT_MS // precedence JACCL_PROGRESS_TIMEOUT_MS is used before the alias @@ -1267,8 +1267,11 @@ int main(int count, char** arguments) { setenv("JACCL_TIMEOUT_ACTION", "throw", 1); } if (mode == "checks") { - setenv(name, "250", 1); - value(250); + // Every case scales with the limit: below-limit gaps are limit / 2 and + // over-limit stalls must trip in [limit, limit + slack]. 2000 ms leaves a + // hosted runner 1 s of scheduling delay inside a below-limit gap. + setenv(name, "2000", 1); + value(2000); silent_peer(); lost_completion(); failed_completion(); diff --git a/tests/jaccl/startup_wait_budget_group_tests.cpp b/tests/jaccl/startup_wait_budget_group_tests.cpp index 9940085da4..3aab8d04e1 100644 --- a/tests/jaccl/startup_wait_budget_group_tests.cpp +++ b/tests/jaccl/startup_wait_budget_group_tests.cpp @@ -56,8 +56,16 @@ void ring_success_end(int wires) { [&] { pair.nodes[1]->recv(output.data(), 99, 0, wires); }); pair.fabric.require_drained(); } +// The guard samples the startup deadline once in PROGRESS_SAMPLE_POLLS empty +// polls. With the default 1 ms idle wait per empty poll, that is 1024 sleeps, +// which a hosted runner stretches past the fake poll's 8 s deadline. The +// expiry cases poll without a sleep, as the hardware does. +void spin(fixture::Fabric& fabric) { + fabric.idle_wait = std::chrono::milliseconds(0); +} void mesh_expiry_cleanup() { fixture::MeshPair pair; + spin(pair.fabric); auto& node = *pair.nodes[0]; node.begin_startup_wait_budget(1); std::this_thread::sleep_for(std::chrono::milliseconds(3)); @@ -75,6 +83,7 @@ void mesh_expiry_cleanup() { } void ring_expiry_cleanup(int wires) { fixture::RingPair pair(wires); + spin(pair.fabric); auto& node = *pair.nodes[0]; node.begin_startup_wait_budget(1); std::this_thread::sleep_for(std::chrono::milliseconds(3));