From 4e2455b0093cb63454fdc9d74914ed03e3777acc Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 23 Oct 2026 11:36:20 -0700 Subject: [PATCH 1/9] Order fast Metal fence waits after current-pass producers Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fork-tests.yml | 5 ++ docs/src/usage/using_streams.rst | 14 ++++++ fork.yaml | 18 ++++++++ mlx/backend/metal/fence.cpp | 2 + tests/CMakeLists.txt | 9 ++++ tests/metal_fence_chain.cpp | 79 ++++++++++++++++++++++++++++++++ 6 files changed, 127 insertions(+) create mode 100644 tests/metal_fence_chain.cpp diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index ab963d2cec..6415db82f1 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -44,6 +44,11 @@ jobs: # builds all Metal kernels. macos-target: '26.2' + - name: Run bounded Metal fence chains + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/fence-%p-%m.profraw + run: ctest --test-dir build -R '^metal_fence_chain_' --output-on-failure --no-tests=error + - uses: ./.github/actions/test-macos id: tests env: diff --git a/docs/src/usage/using_streams.rst b/docs/src/usage/using_streams.rst index 058bc59dea..5f640f070e 100644 --- a/docs/src/usage/using_streams.rst +++ b/docs/src/usage/using_streams.rst @@ -16,3 +16,17 @@ the operation is run on the default stream of the default device: be a :obj:`Device` (e.g. ``stream=my_device``) in which case the operation is run on the default stream of the provided device ``mx.default_stream(my_device)``. + +Cross-device fence ordering +--------------------------- + +With fast Metal synchronization, a GPU consumer can wait for work on a CPU +stream. Its wait must follow both earlier command passes and earlier kernels +in the current concurrent pass. The CPU work can depend on those GPU kernels. +``Fence::wait`` therefore inserts both dependencies before the GPU wait. + +The standalone ``metal_fence_chain`` test checks exact GPU-to-CPU-to-GPU chains +with shared side roots and request-array retirement. CTest runs separate +processes with fast synchronization and several command-buffer sizes, with a +60-second timeout per process. This component test does not qualify distributed +collective order, a transport, or an installed model service. diff --git a/fork.yaml b/fork.yaml index ab502aac94..e3ad89655a 100644 --- a/fork.yaml +++ b/fork.yaml @@ -304,6 +304,24 @@ def: - "mlx/distributed/sealed.cpp" - "mlx/distributed/sealed.h" - "mlx/distributed/sealed_stream.h" + - title: "Fast fence waits order earlier kernels in the same Metal pass" + description: | + An ordinary fast-synchronization GPU fence wait follows both pending + command passes and earlier kernels in the current concurrent encoder. + The in-pass buffer barrier matches the existing fenced-input consumer + path. Without it, a spinning wait can run before a GPU producer needed + by the CPU work it awaits. Arithmetic and command-buffer limits do not + change. A standalone bounded test checks exact GPU-to-CPU-to-GPU chains, + shared side roots and request-array retirement at several buffer sizes. + Fork Tests executes the three CTest processes on its Metal runner and + rejects a missing test registration. This component coverage does not + establish an installed RDMA model fix. + globs: + - "mlx/backend/metal/fence.cpp" + - "tests/metal_fence_chain.cpp" + - "tests/CMakeLists.txt" + - "docs/src/usage/using_streams.rst" + - ".github/workflows/fork-tests.yml" - 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/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index a144ca5605..3f908c1c59 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -73,6 +73,8 @@ void encode_wait( // 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(); + // Order the spin after earlier GPU producers in this concurrent pass too. + compute_encoder.barrier(); auto kernel = d.get_kernel("fence_wait"); MTL::Size kernel_dims = MTL::Size(1, 1, 1); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c80d20c1e3..6cf9425911 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -11,6 +11,15 @@ if(MLX_BUILD_METAL OR MLX_BUILD_CUDA) endif() if(MLX_BUILD_METAL) + add_executable(metal_fence_chain metal_fence_chain.cpp) + target_link_libraries(metal_fence_chain PRIVATE mlx) + foreach(ops IN ITEMS 8 50 1024) + add_test(NAME metal_fence_chain_${ops} COMMAND metal_fence_chain) + set_tests_properties( + metal_fence_chain_${ops} + PROPERTIES TIMEOUT 60 ENVIRONMENT + "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") + endforeach() list(APPEND METAL_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp) endif() diff --git a/tests/metal_fence_chain.cpp b/tests/metal_fence_chain.cpp new file mode 100644 index 0000000000..47b5339595 --- /dev/null +++ b/tests/metal_fence_chain.cpp @@ -0,0 +1,79 @@ +// Copyright © 2026 Eigen Labs Inc. +#include +#include +#include +#include + +#include "mlx/memory.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +// Standalone so the caller can enforce a timeout if a fence stops progress. +int main(int argc, char** argv) { + try { + const bool cpu_only = argc == 2 && std::string(argv[1]) == "--cpu"; + if (argc > 1 && !cpu_only) { + throw std::invalid_argument("only --cpu is supported"); + } + if (!cpu_only && !gpu::is_available()) { + throw std::runtime_error("Metal is required"); + } + auto producer = new_stream(cpu_only ? Device::cpu : Device::gpu); + auto host = new_stream(Device::cpu); + constexpr int layers = 96; + constexpr int repeats = 3; + size_t comparisons = 0; + for (int width : {1, 2, 3, 4, 8}) { + for (int repeat = 0; repeat < repeats; ++repeat) { + { + auto x = zeros({width, 5120}, float32, producer); + std::vector roots; + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + auto reduced = add(partial, array(2.0f), host); + x = add(reduced, array(3.0f), producer); + // Independent roots share GPU producers with the CPU chain. + if (layer % 3 == 0) { + roots.push_back(add(partial, array(17.0f), producer)); + } + } + roots.insert(roots.begin(), x); + eval(roots); + synchronize(producer); + synchronize(host); + for (size_t root = 0; root < roots.size(); ++root) { + float expected = + root == 0 ? layers * 6.0f : (root - 1) * 3 * 6.0f + 18.0f; + const float* values = roots[root].data(); + for (size_t i = 0; i < roots[root].size(); ++i) { + if (values[i] != expected) { + throw std::runtime_error("exact chain/side-root mismatch"); + } + ++comparisons; + } + } + } + synchronize(producer); + synchronize(host); + clear_cache(); + if (get_active_memory() != 0) { + throw std::runtime_error("request arrays remain after checked drain"); + } + std::cout << "{\"event\":\"case\",\"width\":" << width + << ",\"repeat\":" << repeat << ",\"layers\":" << layers + << ",\"logical_active_bytes\":0}" << std::endl; + } + } + synchronize(producer); + synchronize(host); + clear_streams(); + std::cout << "{\"event\":\"passed\",\"cases\":15,\"comparisons\":" + << comparisons << ",\"device\":\"" << (cpu_only ? "cpu" : "gpu") + << "\"}" << std::endl; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << std::endl; + return 1; + } +} From 66edc7716533bef9a6fc591284e56c6ed86bc14b Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 23 Oct 2026 12:06:18 -0700 Subject: [PATCH 2/9] Format inherited native cluster sources for pinned CI Apply the existing clang-format and cmake-format policies to six inherited paths. Preserve all test coverage and source bodies. 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 8d4e5b0f20..e835a1aa0e 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -57,7 +57,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 fe80634d88..882f594a4d 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -438,9 +438,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 9ec023f929d67e96c55b46ae3e8510e806d03f0b Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 23 Oct 2026 12:32:23 -0700 Subject: [PATCH 3/9] 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 --- 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 e3ad89655a..cfea9819a9 100644 --- a/fork.yaml +++ b/fork.yaml @@ -297,13 +297,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: "Fast fence waits order earlier kernels in the same Metal pass" description: | An ordinary fast-synchronization GPU fence wait follows both pending 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 6cf9425911..66136c1b9b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -36,6 +36,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 a5d6547ba8a249e1f13e3274ff61aa1452bf8140 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sun, 25 Oct 2026 09:23:25 -0700 Subject: [PATCH 4/9] Keep GPU streams from spinning on each other's fast fences With fast synchronization (MLX_METAL_FAST_SYNCH=1) a GPU fence wait is a kernel that spins until its producer's timestamp arrives. That is safe for a CPU producer, but Metal does not promise that a second command queue runs while a pass of the first one spins. A widened Qwen tensor-parallel decode on mlx-swift put one graph on two GPU streams: quantized_matmul cast the batched projections' bfloat16 scales and biases on the thread's default stream rather than the caller's, while mlx-swift runs everything else on its own process-wide stream. The two ranks then stopped meeting in the next collective (the cluster's c14, c17 and c39 stalls). - Helper ops keep the caller's stream: quantized_matmul's casts, gather and scatter index broadcasts, the gather matmuls' index casts and affine_quantize's scale select (ops.cpp). - A GPU stream never spins on another GPU stream: evaluation waits for it on a shared event, and so does a GPU stream waiting for CPU work that can itself wait for another GPU stream; an array read both by the CPU and by another GPU stream updates both fences. Other CPU <-> GPU waits keep the fast spin (transforms.cpp, Fence(Stream, fast) in fence.h, and the Metal, CUDA and no-GPU fences). - metal_fence_chain adds an exact two-GPU-stream chain at widths 1, 2 and 4; ops_tests checks that quantized_matmul's casts run on the caller's stream. using_streams.rst and fork.yaml describe both rules. Synchronization only: results do not change. On one Mac (two ranks over a local ring) the stall reproduced without the fix and not with either part (seeds 7, 11 and 13, two and four lanes, a 600-step soak), with tokens byte-identical to the event path. On the two-Mac pair (M3 Ultra + M5 Max, Thunderbolt RDMA) every widened Qwen tensor-parallel owner runs on fast fences since the provider build that pins this core: the fast-fence diagnostic qwen27-c40-fast1-02 (two lanes) passed, and the installed acceptance qwen27-c44-auto-mtp-01 widened to four lanes with rows retiring mid-cohort, every concurrent row byte-equal to its solo run, and no stall. Tests: the new C++ cases (metal_fence_chain's two-GPU chain, ops_tests' caller-stream check) were not built or run here; the fork's Fork Tests workflow builds and runs them. The Swift cluster runtime suites that run the fixed paths passed on the M5 Max (GPU batch 14, GPU MTP 30). Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/using_streams.rst | 8 +++ fork.yaml | 30 ++++++++ mlx/backend/cuda/fence.cpp | 2 + mlx/backend/metal/fence.cpp | 9 ++- mlx/backend/no_gpu/fence.cpp | 2 + mlx/fence.h | 3 + mlx/ops.cpp | 16 +++-- mlx/transforms.cpp | 119 ++++++++++++++++++++++++------- tests/metal_fence_chain.cpp | 44 +++++++++++- tests/ops_tests.cpp | 18 +++++ 10 files changed, 215 insertions(+), 36 deletions(-) diff --git a/docs/src/usage/using_streams.rst b/docs/src/usage/using_streams.rst index 5f640f070e..345ab09e05 100644 --- a/docs/src/usage/using_streams.rst +++ b/docs/src/usage/using_streams.rst @@ -25,6 +25,14 @@ stream. Its wait must follow both earlier command passes and earlier kernels in the current concurrent pass. The CPU work can depend on those GPU kernels. ``Fence::wait`` therefore inserts both dependencies before the GPU wait. +A GPU stream never spins on another GPU stream. The fast wait is a kernel that +spins until its producer's timestamp arrives, and Metal does not guarantee that +a second command queue runs while a pass of the first one spins: the producing +queue can starve and both stop. When an evaluation's graph spans two GPU +streams, a consumer on one waits for the other on a shared event, and so does a +GPU stream waiting for CPU work that can itself wait for another GPU stream. +The other CPU-to-GPU and GPU-to-CPU waits keep the fast path. + The standalone ``metal_fence_chain`` test checks exact GPU-to-CPU-to-GPU chains with shared side roots and request-array retirement. CTest runs separate processes with fast synchronization and several command-buffer sizes, with a diff --git a/fork.yaml b/fork.yaml index cfea9819a9..8957ea7321 100644 --- a/fork.yaml +++ b/fork.yaml @@ -326,6 +326,36 @@ def: - "tests/CMakeLists.txt" - "docs/src/usage/using_streams.rst" - ".github/workflows/fork-tests.yml" + - title: "GPU streams wait for each other on events" + description: | + With fast synch (`MLX_METAL_FAST_SYNCH=1`) a fence wait on the GPU is a one-thread + kernel that spins until the producer's timestamp arrives. That is safe when the + producer is a CPU stream (a thread always progresses), but not when it is another + GPU stream: Metal does not promise that a second command queue runs while a pass of + the first one spins, so the producing queue can starve and both stop. An eval whose + graph spans two GPU streams therefore waits for the other GPU stream on a shared + event (the non-fast path), while CPU <-> GPU waits keep the fast path. An array read + both by the CPU and by another GPU stream updates both fences. Synchronization only: + results do not change. + globs: + - "mlx/fence.h" + - "mlx/transforms.cpp" + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/no_gpu/fence.cpp" + - "mlx/backend/cuda/fence.cpp" + - "docs/src/usage/using_streams.rst" + - title: "Helper ops keep the caller's stream" + description: | + `quantized_matmul` cast `x`, `scales` and `biases`, `gather` and `scatter` broadcast + their indices, the gather matmuls cast their indices, and `affine_quantize` selected + its scales on the thread's default stream instead of the stream the caller passed. + mlx-swift passes its own process-wide stream to every op, so each of these helpers + put a second GPU stream into the graph: a 4-bit projection with float32 input and + bfloat16 scales crossed streams twice, and every crossing is a fence wait. They now + use the caller's stream. Where an op runs does not change what it computes. + globs: + - "mlx/ops.cpp" + - "tests/ops_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/backend/cuda/fence.cpp b/mlx/backend/cuda/fence.cpp index 64c605a0b0..7363c049f5 100644 --- a/mlx/backend/cuda/fence.cpp +++ b/mlx/backend/cuda/fence.cpp @@ -20,6 +20,8 @@ Fence::Fence(Stream s) { cast().event.cast().ensure_created(s, 2); } +Fence::Fence(Stream s, bool) : Fence(s) {} + void Fence::wait(Stream s, const array&) { cast().event.wait(); } diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 3f908c1c59..5ecc365770 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -9,12 +9,13 @@ namespace mlx::core { struct FenceImpl { - FenceImpl(Stream stream) : cpu_stream(stream.device == Device::cpu) { + FenceImpl(Stream stream, bool allow_fast = true) + : cpu_stream(stream.device == Device::cpu) { auto d = metal::device(stream.device).mtl_device(); if (!d->supportsFamily(MTL::GPUFamilyMetal3)) { use_fast = false; } else if (__builtin_available(macOS 15, iOS 18, *)) { - use_fast = env::metal_fast_synch(); + use_fast = allow_fast && env::metal_fast_synch(); } if (!use_fast) { @@ -95,6 +96,10 @@ Fence::Fence(Stream stream) { fence_ = std::make_shared(stream); } +Fence::Fence(Stream stream, bool fast) { + fence_ = std::make_shared(stream, fast); +} + void Fence::wait(Stream stream, const array& x) { auto& f = *static_cast(fence_.get()); diff --git a/mlx/backend/no_gpu/fence.cpp b/mlx/backend/no_gpu/fence.cpp index 86fbe09783..84fd7267d9 100644 --- a/mlx/backend/no_gpu/fence.cpp +++ b/mlx/backend/no_gpu/fence.cpp @@ -16,6 +16,8 @@ Fence::Fence(Stream s) { fence_ = std::make_shared(0, s); } +Fence::Fence(Stream s, bool) : Fence(s) {} + void Fence::wait(Stream s, const array&) { cast().event.wait(s); } diff --git a/mlx/fence.h b/mlx/fence.h index 7bc9ce363d..bfd4875137 100644 --- a/mlx/fence.h +++ b/mlx/fence.h @@ -28,6 +28,9 @@ class Fence { public: Fence() {}; explicit Fence(Stream stream); + // `fast` false synchronizes with events even when fast synchronization is + // enabled. Backends without fast synchronization ignore it. + Fence(Stream stream, bool fast); void update(Stream stream, const array& x, bool cross_device); void wait(Stream stream, const array& x); diff --git a/mlx/ops.cpp b/mlx/ops.cpp index 5fe3d9be59..ec45591383 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -96,7 +96,7 @@ array indices_or_default( << " Got indices with invalid dtype. Indices must be integral."; throw std::invalid_argument(msg.str()); } - return astype(indices.value(), uint32); + return astype(indices.value(), uint32, s); } Shape shape(x.shape().begin(), x.shape().end() - 2); @@ -3589,7 +3589,7 @@ array gather( } // Broadcast and cast indices if necessary - auto inputs = broadcast_arrays(indices); + auto inputs = broadcast_arrays(indices, s); for (auto& idx : inputs) { idx = astype(idx, dtype, s); } @@ -3867,7 +3867,7 @@ array scatter( } // Broadcast and cast indices if necessary - auto inputs = broadcast_arrays(indices); + auto inputs = broadcast_arrays(indices, s); Shape idx_shape; if (!inputs.empty()) { @@ -4814,8 +4814,14 @@ array quantized_matmul( } std::vector inputs; if (qmode == QuantizationMode::Affine) { + // On the caller's stream: a cast on the thread's default stream is a + // second GPU stream whenever the caller passed its own (mlx-swift's + // Stream.gpu), and every cast then crosses streams through fences. inputs = { - astype(x, dtype), w, astype(scales, dtype), astype(*biases, dtype)}; + astype(x, dtype, s), + w, + astype(scales, dtype, s), + astype(*biases, dtype, s)}; } else { inputs = {x, w, scales}; } @@ -5072,7 +5078,7 @@ affine_quantize(const array& w, int group_size, int bits, StreamOrDevice s_) { scales = where(mask, scales, negative(scales, s), s); array edge = where(mask, w_min, w_max, s); array q0 = round(divide(edge, scales, s), s); - scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales); + scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales, s); array biases = where(equal(q0, zero, s), zero, edge, s); packed_w = pack_and_quantize(packed_w, scales, biases, bits, s); diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 7fee175740..404c777f1b 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -196,8 +196,19 @@ 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; + // Arrays read on another stream: the stream they are computed on, whether + // a reader waits on the fence (`fast`, a spinning wait under fast synch) or + // on an event fence (`event`), and whether a reader is on another device. + struct FenceNeed { + uint32_t stream; + bool producer_gpu; + bool cross_device{false}; + bool fast{false}; + bool event{false}; + }; + std::unordered_map needs_fence; + // GPU streams that read a CPU array, per CPU array (decided after the walk). + std::unordered_map> cpu_to_gpu_readers; // GPU streams with an array that a CPU primitive reads std::unordered_set gpu_to_cpu; @@ -207,6 +218,15 @@ array eval_impl(std::vector outputs, bool async) { // Stream fences for inter-stream synchronization std::unordered_map fences; + // Event fences for readers that must not spin. Under fast synch a GPU + // fence wait is a kernel that spins until its producer's timestamp + // arrives, and Metal does not guarantee that another command queue runs + // while a pass of this queue spins. So a GPU stream never spins on another + // GPU stream, nor on CPU work that can itself wait for another GPU stream + // (the starved queue would hold back the timestamp the spin waits for). + // Both wait on a shared event instead. CPU waits keep the fast path: a CPU + // stream is a thread and always progresses. + std::unordered_map event_fences; // Stream events for synchronization after eval std::unordered_map events; @@ -254,11 +274,24 @@ array eval_impl(std::vector outputs, bool async) { if (a.primitive().stream() != in.primitive().stream()) { bool device_switch = a.primitive().stream().device != in.primitive().stream().device; - auto [it, inserted] = needs_fence.emplace( - in.id(), - std::make_pair(in.primitive().stream().index, device_switch)); - if (!inserted) { - it->second.second |= device_switch; + auto& need = needs_fence + .emplace( + in.id(), + FenceNeed{ + static_cast( + in.primitive().stream().index), + in.primitive().device() == Device::gpu}) + .first->second; + need.cross_device |= device_switch; + bool gpu_reader = a.primitive().device() == Device::gpu; + if (in.primitive().device() == Device::gpu) { + // Another GPU stream waits on an event; the CPU spins. + (gpu_reader ? need.event : need.fast) = true; + } else if (gpu_reader) { + cpu_to_gpu_readers[in.id()].push_back( + static_cast(a.primitive().stream().index)); + } else { + need.fast = true; } if (device_switch && in.primitive().device() == Device::gpu) { gpu_to_cpu.insert(in.primitive().stream().index); @@ -290,6 +323,17 @@ array eval_impl(std::vector outputs, bool async) { dfs.pop(); } + // A GPU stream may spin on CPU work only when that CPU work can wait for + // no GPU stream but this one. + for (auto& [id, readers] : cpu_to_gpu_readers) { + auto& need = needs_fence.at(id); + for (auto reader : readers) { + bool alone = gpu_to_cpu.empty() || + (gpu_to_cpu.size() == 1 && gpu_to_cpu.count(reader) == 1); + (alone ? need.fast : need.event) = true; + } + } + // Build the tape in BFS order with a width limit int max_width = env::bfs_max_width(); dfs = std::stack, int>>(); @@ -369,7 +413,19 @@ array eval_impl(std::vector outputs, bool async) { // Use fence to wait within a single eval // Get the input array's stream fence and wait on the // output arrays stream - auto& fence = fences[it->second.first]; + auto& need = it->second; + // On the producer's own stream, wait on the fence its update used + // (as before: the update precedes in this stream). Across streams, + // a GPU stream waits on the event for another GPU stream's array, + // or for CPU work that can wait for another GPU stream: never spin. + bool same_stream = need.stream == static_cast(stream.index); + if (same_stream ? !need.fast + : (stream.device == Device::gpu && + (need.producer_gpu || !one_gpu_stream))) { + event_fences[need.stream].wait(stream, in); + continue; + } + auto& fence = fences[need.stream]; if (!one_gpu_stream || !fence.wait_in_consumer(stream, arr, i)) { fence.wait(stream, in); } @@ -405,25 +461,36 @@ array eval_impl(std::vector outputs, bool async) { } } - auto maybe_update_fence = - [&fences, &needs_fence, stream](const array& a) { - if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) { - auto it = fences.find(stream.index); - if (it == fences.end()) { - 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); - } + auto maybe_update_fence = [&fences, &event_fences, &needs_fence, stream]( + const array& a) { + if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) { + if (nf->second.event) { + auto it = event_fences.find(stream.index); + if (it == event_fences.end()) { + it = event_fences + .emplace(stream.index, Fence{stream, /* fast */ false}) + .first; + } + it->second.update(stream, a, false); + } + if (nf->second.fast) { + auto it = fences.find(stream.index); + if (it == fences.end()) { + it = fences.emplace(stream.index, Fence{stream}).first; } - }; + it->second.update(stream, a, nf->second.cross_device); + // 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.cross_device && + stream.device == Device::gpu) { + gpu::finalize(stream); + } + } + } + }; arr.set_status(array::Status::evaluated); // TODO Maybe always want the fence coherent kernel in the same cbuf diff --git a/tests/metal_fence_chain.cpp b/tests/metal_fence_chain.cpp index 47b5339595..968ab06cbb 100644 --- a/tests/metal_fence_chain.cpp +++ b/tests/metal_fence_chain.cpp @@ -65,12 +65,50 @@ int main(int argc, char** argv) { << ",\"logical_active_bytes\":0}" << std::endl; } } + // A second GPU stream in the same chain: each layer's partial is read by + // the CPU and by another GPU stream, and the producer stream reads both + // results back. The producer waits for the other GPU stream on an event + // (a spinning wait there could starve that stream's queue). + if (!cpu_only) { + auto side = new_stream(Device::gpu); + for (int width : {1, 2, 4}) { + { + auto x = zeros({width, 5120}, float32, producer); + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + auto reduced = add(partial, array(2.0f), host); + auto gate = add(partial, array(4.0f), side); + // (x + 3) + (x + 5) - (x + 5) = x + 3, exact in float32. + x = subtract( + add(reduced, gate, producer), + add(x, array(5.0f), producer), + producer); + } + eval(x); + synchronize(producer); + synchronize(side); + synchronize(host); + const float* values = x.data(); + for (size_t i = 0; i < x.size(); ++i) { + if (values[i] != layers * 3.0f) { + throw std::runtime_error("exact two-GPU-stream chain mismatch"); + } + ++comparisons; + } + } + synchronize(producer); + synchronize(side); + synchronize(host); + std::cout << "{\"event\":\"case\",\"streams\":\"two-gpu\",\"width\":" + << width << ",\"layers\":" << layers << "}" << std::endl; + } + } synchronize(producer); synchronize(host); clear_streams(); - std::cout << "{\"event\":\"passed\",\"cases\":15,\"comparisons\":" - << comparisons << ",\"device\":\"" << (cpu_only ? "cpu" : "gpu") - << "\"}" << std::endl; + std::cout << "{\"event\":\"passed\",\"cases\":" << (cpu_only ? 15 : 18) + << ",\"comparisons\":" << comparisons << ",\"device\":\"" + << (cpu_only ? "cpu" : "gpu") << "\"}" << std::endl; return 0; } catch (const std::exception& error) { std::cerr << error.what() << std::endl; diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 38b29826a2..0766549713 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -9,6 +9,7 @@ #include "mlx/backend/cuda/cuda.h" #include "mlx/mlx.h" +#include "mlx/primitives.h" using namespace mlx::core; @@ -4653,3 +4654,20 @@ TEST_CASE("roll and tile shape overflow") { auto rolled = roll(x, -2147483647 - 1); CHECK(array_equal(rolled, x).item()); } + +TEST_CASE("quantized matmul casts on the caller's stream") { + // mlx-swift passes its own stream to every op. A cast on the thread's + // default stream instead put one projection on two GPU streams. + auto s = new_stream(default_device()); + auto w = reshape(astype(arange(64 * 64), float32), {64, 64}); + auto quantized = quantize(w, 64, 4); + auto scales = astype(quantized[1], bfloat16); + auto biases = astype(quantized[2], bfloat16); + auto x = ones({1, 64}, float32); + auto out = quantized_matmul( + x, quantized[0], scales, biases, true, 64, 4, "affine", s); + // x is float32 already; the bfloat16 scales and biases are cast to it. + CHECK(out.primitive().stream() == s); + CHECK(out.inputs()[2].primitive().stream() == s); + CHECK(out.inputs()[3].primitive().stream() == s); +} From 2e16455f414fe85301b93f457e2b1c7b2054d91f Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sun, 25 Oct 2026 21:25:46 -0700 Subject: [PATCH 5/9] Pick prompt-sized steel tiles for affine quantized matmuls On a GPU without neural accelerators the steel `affine_qmm_t` kernel computed every product in 32 x 32 output tiles. A product of at least 256 rows with a 64-aligned output width now takes a 64-row x 32-column tile for 16-bit inputs and a 32 x 64 tile for FP32 inputs by default, JIT-instantiated from the same `qmm_t_impl`. Every output element still accumulates the same K slabs in the same order, so a tile decides which threadgroup computes an element, never its bits. NAX-eligible products and decode-sized products (fewer than 256 rows) are unchanged. - `MLX_QMM_STEEL_TILE` (32, 64, 6432, 3264, 6464) and `MLX_QMM_STEEL_TILE_MIN_GROUPS` choose or restore the tile; `MLX_QMM_STEEL_TILE=32` is the previous kernel path exactly. - `mlx_metal_set_thread_qmm_steel_tile` overrides the tile for the products the calling thread encodes (tests and benches). - environment_variables.rst and fork.yaml describe both. Measured on the M3 Ultra (the TP rank without NAX): a 27B 4K prompt 12.37 -> 12.06 s, a 9B 4K prompt 3.55 -> 3.46 s, same tokens. On the two-Mac pair (Qwen 3.8 27B, tensor parallel 1:1, with prompt frames submitted every four layers) time to first token at 1K/4K/16K/32K fell 1.4/1.6/3.1/2.2%, tokens identical. Tests: the cluster runtime's steel-tile tests (bytes for every tile and the default, BF16 and FP32) and its two-rank prompt-submission GPU test passed on the M5 Max, and the provider's c45 candidate chain passed. The core's own C++ tests were not built or run here; Fork Tests runs them. Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/environment_variables.rst | 17 +++++ fork.yaml | 24 +++++++ mlx/backend/common/command_buffer_limits.h | 8 +++ mlx/backend/metal/device.cpp | 19 ++++++ mlx/backend/metal/device.h | 5 ++ mlx/backend/metal/quantized.cpp | 74 +++++++++++++++++++++- mlx/utils.h | 15 +++++ 7 files changed, 159 insertions(+), 3 deletions(-) diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 80d1c1b544..187d0b9152 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -163,6 +163,23 @@ users. Their behavior may change as the implementation evolves. dot-product attention kernel. Positive values are rounded up to a multiple of ``32``. +.. envvar:: MLX_QMM_STEEL_TILE + + Output tile of the Metal steel affine quantized matmul (``x @ w.T`` with + at least 64 rows and a multiple of 64 outputs) where no neural-accelerator + kernel serves the product. The default, ``0``, takes 64 rows x 32 columns + for 16-bit inputs and 32 x 64 for FP32 inputs from 256 rows, and 32 x 32 + below. ``32`` (32 x 32, the previous tile), ``64`` (64 x 64), ``6432`` + (64 rows x 32 columns), ``3264`` (32 x 64) or ``6464`` (64 x 64 at a K + depth of 64 for 16-bit inputs in groups of 64 or more) choose one tile for + every product from 64 rows. Every tile gives the same bits; only the speed + changes. + +.. envvar:: MLX_QMM_STEEL_TILE_MIN_GROUPS + + Fewest 64 x 64 threadgroups a product must fill to take a tile other than + 32 x 32; smaller products keep 32 x 32. The default is ``0``. + CUDA ---- diff --git a/fork.yaml b/fork.yaml index 8957ea7321..2ff4fb40e7 100644 --- a/fork.yaml +++ b/fork.yaml @@ -90,6 +90,30 @@ def: - "mlx/backend/common/command_buffer_limits.h" - "mlx/backend/metal/device.h" - "mlx/backend/metal/device.cpp" + - title: "Steel affine quantized matmul: prompt-sized output tiles" + description: | + On a GPU without neural accelerators the steel `affine_qmm_t` kernel computed every + product in 32 x 32 output tiles (2 x 2 fragments a SIMD group). A product of at least + 256 rows with a 64-aligned output width now takes a 64-row x 32-column tile for 16-bit + inputs and a 32 x 64 tile for FP32 inputs by default (measured on the M3 Ultra at 512 + rows: BF16 products 4-6% faster; FP32's 64 x 64 tile was slower), JIT-instantiated from + the same `qmm_t_impl`. Every output element still accumulates the same 8-wide K slabs + in the same order with the same simdgroup multiply-accumulates over the same + dequantized values, so no bit changes; the split-K decision (made from 32 x 32 tiles) + and the NAX route are unchanged. + `MLX_QMM_STEEL_TILE` picks 32 (as before), 64, 6432, 3264 or 6464 (64 x 64 with K depth + 64 for 16-bit inputs in groups of 64 or more; FP32 tiles that deep would exceed 32 KiB of + threadgroup memory); `MLX_QMM_STEEL_TILE_MIN_GROUPS` keeps 32 x 32 below a 64 x 64 + threadgroup count; `mlx_metal_set_thread_qmm_steel_tile` overrides the tile for the + calling thread (tests and benches compare the tiles' bytes in one process). Both + variables are documented in `docs/src/usage/environment_variables.rst`. + globs: + - "mlx/backend/common/command_buffer_limits.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/quantized.cpp" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" description: | GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's diff --git a/mlx/backend/common/command_buffer_limits.h b/mlx/backend/common/command_buffer_limits.h index 2f1d37cea6..e21164140b 100644 --- a/mlx/backend/common/command_buffer_limits.h +++ b/mlx/backend/common/command_buffer_limits.h @@ -23,6 +23,14 @@ MLX_API void mlx_metal_set_thread_command_buffer_limits( int* previous_ops, int* previous_mb); +/// Output tile (32, 64, 6432, 3264 or 6464: rows x columns[, K depth]) of the +/// steel affine quantized matmul for the +/// products the calling thread encodes on a GPU without neural accelerators; +/// any other value restores MLX_QMM_STEEL_TILE. Stores the thread's previous +/// override (0 for none) in `previous_tile` when it is not null. The tile +/// changes which threadgroup computes an element, never its bits. +MLX_API void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile); + #ifdef __cplusplus } #endif diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index 386f31fb95..b5a23839af 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -523,6 +523,9 @@ namespace { // Per-thread commit limits; zero selects the device default. thread_local int thread_max_ops_per_buffer = 0; thread_local int thread_max_mb_per_buffer = 0; +// Per-thread steel quantized-matmul output tile (32, 64, 6432, 3264 or 6464); +// zero selects MLX_QMM_STEEL_TILE (see `qmm` in quantized.cpp). +thread_local int thread_qmm_steel_tile_override = 0; void set_thread_command_buffer_limits( int max_ops, @@ -540,6 +543,10 @@ void set_thread_command_buffer_limits( } } // namespace +int thread_qmm_steel_tile() { + return thread_qmm_steel_tile_override; +} + std::tuple Device::get_max_ops_mb_per_buffer() const { return std::make_tuple( thread_max_ops_per_buffer > 0 ? thread_max_ops_per_buffer @@ -1106,6 +1113,18 @@ extern "C" void mlx_metal_set_thread_command_buffer_limits( max_ops, max_mb, previous_ops, previous_mb); } +extern "C" void mlx_metal_set_thread_qmm_steel_tile( + int tile, + int* previous_tile) { + if (previous_tile != nullptr) { + *previous_tile = mlx::core::metal::thread_qmm_steel_tile_override; + } + mlx::core::metal::thread_qmm_steel_tile_override = + (tile == 32 || tile == 64 || tile == 6432 || tile == 3264 || tile == 6464) + ? tile + : 0; +} + extern "C" void mlx_metal_gemma4_expert_qmm_diagnostics_snapshot( mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics) { gemma4_expert_qmm_diagnostics_snapshot(diagnostics, false); diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 2c5e9caaf2..a7d025fbd3 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -453,6 +453,11 @@ class MLX_API Device { }; MLX_API Device& device(mlx::core::Device); + +// The calling thread's steel quantized-matmul output tile (32, 64, 6432, +// 3264 or 6464), or 0 +// for MLX_QMM_STEEL_TILE (mlx_metal_set_thread_qmm_steel_tile). +int thread_qmm_steel_tile(); MLX_API CommandEncoder& get_command_encoder(Stream s); std::unordered_map& get_command_encoders(); diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index fc5d121225..03b3cec659 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -1068,10 +1068,61 @@ void qmm( int B = out.size() / M / N; + // Prompt-sized products (256 rows or more) take a larger output tile than + // 32 x 32 on a GPU without neural accelerators (the NAX kernel above serves + // the rest): 64 rows x 32 columns for 16-bit inputs and 32 rows x 64 + // columns for FP32 by default (measured on the M3 Ultra, 512-row products of + // a 4-bit 27B: 64 x 32 is 4-6% faster than 32 x 32 for BF16; FP32's + // threadgroup tiles are twice as large, and its 64 x 64 tile is slower while + // 32 x 64 rereads the FP32 rows half as often). Every output element still + // accumulates the same 8-wide K slabs in the same order with the same + // simdgroup multiply-accumulates, from the same dequantized values, whatever + // the tile's rows, columns or K depth: no element's bits change, only which + // threadgroup computes it. MLX_QMM_STEEL_TILE (or the calling thread's + // mlx_metal_set_thread_qmm_steel_tile) picks another tile: 32 (32 x 32, as + // before), 64 (64 x 64), 6432 (64 rows x 32 columns), 3264, or 6464 (64 x 64, + // K depth 64 for 16-bit inputs in groups of 64 or more). + int requested = metal::thread_qmm_steel_tile(); + if (requested == 0) { + requested = env::qmm_steel_tile(); + int groups = + (N / 64) * ((M + 63) / 64) * std::max(1, int(out.size() / M / N)); + if (groups < env::qmm_steel_tile_min_groups()) { + requested = 32; + } else if (requested == 0) { + // Measured at prompt frames; fewer rows keep 32 x 32 (and their + // threadgroup count) unless a tile is chosen explicitly. + requested = M < 256 ? 32 : (x.itemsize() <= 2 ? 6432 : 3264); + } + } + int bm = 32, bn = 32, bk = 32; + if (transpose && mode == "affine" && M >= 64 && N % 64 == 0) { + switch (requested) { + case 64: + bm = 64, bn = 64; + break; + case 6432: + bm = 64; + break; + case 3264: + bn = 64; + break; + case 6464: + // A K depth of 64 needs groups of 64 or more, and both padded + // tiles in 32 KiB of threadgroup memory: 16-bit inputs only (FP32 + // tiles would take 34 KiB), else 64 x 64 at a K depth of 32. + bm = 64, bn = 64; + if (group_size >= 64 && x.itemsize() <= 2) { + bk = 64; + } + break; + default: + break; + } + } + bool wide_tile = bm != 32 || bn != 32 || bk != 32; int wm = 2; int wn = 2; - int bm = 32; - int bn = 32; MTL::Size group_dims(32, wn, wm); MTL::Size grid_dims((N + bn - 1) / bn, (M + bm - 1) / bm, B); @@ -1090,9 +1141,26 @@ void qmm( bits, transpose ? (aligned ? "_alN_true" : "_alN_false") : "", batched ? "_batch_1" : "_batch_0"); + if (wide_tile) { + concatenate(kname, "_bm", bm, "_bk", bk, "_bn", bn); + } std::string template_def; MTL::ComputePipelineState* kernel; - if (transpose) { + if (transpose && wide_tile) { + kernel = get_quantized_kernel_wrapped( + d, + kname, + "qmm_t", + mode, + type_string, + group_size, + bits, + aligned, + batched, + bm, + bk, + bn); + } else if (transpose) { kernel = get_quantized_kernel_wrapped( d, kname, diff --git a/mlx/utils.h b/mlx/utils.h index d539623a75..952434813d 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -206,6 +206,21 @@ inline bool residency_debug() { return residency_debug_; } +// Output tile of the steel affine quantized matmul on GPUs without neural +// accelerators (see `qmm` in backend/metal/quantized.cpp): 32, 64, 6432, +// 3264 or 6464, or 0 (default) for the input width's own tile. +inline int qmm_steel_tile() { + static int tile_ = get_var("MLX_QMM_STEEL_TILE", 0); + return tile_; +} + +// Fewest 64 x 64 threadgroups a product must fill to take a tile other than +// 32 x 32 (fewer keep 32 x 32 and their GPU occupancy). +inline int qmm_steel_tile_min_groups() { + static int groups_ = get_var("MLX_QMM_STEEL_TILE_MIN_GROUPS", 0); + return groups_; +} + inline bool metal_fast_synch() { static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0); return metal_fast_synch; From d11238f128eb204b400f0da1a215dd7f0df530fa Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sun, 25 Oct 2026 23:14:18 -0700 Subject: [PATCH 6/9] Keep 32 x 32 steel tiles where kernels are precompiled The prompt-sized steel tiles (2e16455f) exist only as run-time instantiations. CMake's default build (MLX_METAL_JIT=OFF: the Python wheels and Fork Tests) loads kernels from the precompiled library, which holds `affine_qmm_t` at 32 x 32 only, so a prompt-sized product asked it for a kernel it does not have: "Unable to load kernel affine_qmm_t_float16_t_gs_64_b_4_alN_true_batch_0_bm64_bk32_bn32" in test_quantized.test_qmm_large_dims, and the FP32 32 x 64 kernel in test_export_import. - `kernels_jit_compiled()` (kernels.h; true in jit_kernels.cpp, false in nojit_kernels.cpp) tells the two builds apart, and `qmm` takes a tile other than 32 x 32 only when it is true. Precompiled builds run exactly the previous kernels; JIT builds (mlx-swift) are unchanged. - tests/quantized_tile_tests.cpp (Metal only): 512 x 1024 products (one qmm, no split-K) at K = 96, which no neural-accelerator kernel takes, and at K = 192 in groups of 64, for float16, bfloat16 and float32. The 32 x 32 result matches the dequantized product, and every tile (the default, 64, 6432, 3264, 6464) gives its bytes. - environment_variables.rst, the header comments and fork.yaml say where the tiles apply. Tests on the M3 Ultra (no neural accelerators, like the GitHub runner), the core's C++ tests built with CMake: the new case fails on 2e16455f with precompiled kernels (30 of 36 checks throw "Unable to load kernel affine_qmm_t_..."), and passes 36/36 here with precompiled kernels and with the JIT, where every wide tile, the 64-deep one included, gives the 32 x 32 bytes. The whole doctest suite passes in both builds (294 cases, 4,093 assertions). mlx's pre-commit hooks (clang-format 21.1.8, cmake-format 0.6.13, check-yaml) and the fork.yaml check (237/237) pass. The Python suite was not run here; Fork Tests runs it. Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/environment_variables.rst | 5 +- fork.yaml | 8 ++ mlx/backend/common/command_buffer_limits.h | 4 +- mlx/backend/metal/jit_kernels.cpp | 4 + mlx/backend/metal/kernels.h | 6 ++ mlx/backend/metal/nojit_kernels.cpp | 4 + mlx/backend/metal/quantized.cpp | 6 +- mlx/utils.h | 3 +- tests/CMakeLists.txt | 3 +- tests/quantized_tile_tests.cpp | 112 +++++++++++++++++++++ 10 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 tests/quantized_tile_tests.cpp diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 187d0b9152..c6ce6b9f56 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -173,7 +173,10 @@ users. Their behavior may change as the implementation evolves. (64 rows x 32 columns), ``3264`` (32 x 64) or ``6464`` (64 x 64 at a K depth of 64 for 16-bit inputs in groups of 64 or more) choose one tile for every product from 64 rows. Every tile gives the same bits; only the speed - changes. + changes. Only builds that compile kernels at run time (``MLX_METAL_JIT=ON``) + take a tile other than 32 x 32: the precompiled kernel library of the + default build holds the 32 x 32 kernels only, so there this variable has no + effect. .. envvar:: MLX_QMM_STEEL_TILE_MIN_GROUPS diff --git a/fork.yaml b/fork.yaml index 2ff4fb40e7..5d05233073 100644 --- a/fork.yaml +++ b/fork.yaml @@ -107,6 +107,13 @@ def: threadgroup count; `mlx_metal_set_thread_qmm_steel_tile` overrides the tile for the calling thread (tests and benches compare the tiles' bytes in one process). Both variables are documented in `docs/src/usage/environment_variables.rst`. + Only builds that compile kernels at run time take these tiles: the precompiled + library instantiates `affine_qmm_t` at 32 x 32 only, so CMake builds with the default + `MLX_METAL_JIT=OFF` keep 32 x 32 (`kernels_jit_compiled()`, defined by + `jit_kernels.cpp` and `nojit_kernels.cpp`). `tests/quantized_tile_tests.cpp` runs + 512 x 1024 products (one qmm, no split-K) at K = 96 (no NAX route) and K = 192 in + groups of 64 at every tile, checks the 32 x 32 result against the dequantized + product, and every other tile against its bytes. globs: - "mlx/backend/common/command_buffer_limits.h" - "mlx/backend/metal/device.h" @@ -114,6 +121,7 @@ def: - "mlx/backend/metal/quantized.cpp" - "mlx/utils.h" - "docs/src/usage/environment_variables.rst" + - "tests/quantized_tile_tests.cpp" - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" description: | GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's diff --git a/mlx/backend/common/command_buffer_limits.h b/mlx/backend/common/command_buffer_limits.h index e21164140b..e5ca795989 100644 --- a/mlx/backend/common/command_buffer_limits.h +++ b/mlx/backend/common/command_buffer_limits.h @@ -28,7 +28,9 @@ MLX_API void mlx_metal_set_thread_command_buffer_limits( /// products the calling thread encodes on a GPU without neural accelerators; /// any other value restores MLX_QMM_STEEL_TILE. Stores the thread's previous /// override (0 for none) in `previous_tile` when it is not null. The tile -/// changes which threadgroup computes an element, never its bits. +/// changes which threadgroup computes an element, never its bits. Builds whose +/// kernels come only from the precompiled library (MLX_METAL_JIT=OFF) keep +/// 32 x 32 whatever the tile. MLX_API void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile); #ifdef __cplusplus diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index 8dfe30a15c..1eb58964b5 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -1040,6 +1040,10 @@ MTL::ComputePipelineState* get_quantized_kernel( return d.get_kernel(kernel_name, lib); } +bool kernels_jit_compiled() { + return true; +} + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, diff --git a/mlx/backend/metal/kernels.h b/mlx/backend/metal/kernels.h index 18a56ebf1b..a8dbe0614f 100644 --- a/mlx/backend/metal/kernels.h +++ b/mlx/backend/metal/kernels.h @@ -307,6 +307,12 @@ MTL::ComputePipelineState* get_quantized_kernel( const std::string& template_def, const std::string& mode); +// Whether this build compiles kernels at run time (jit_kernels.cpp), so a +// kernel can take any template instantiation, rather than loading them only +// from the precompiled library (nojit_kernels.cpp), which holds just the +// instantiations its .metal sources list. +bool kernels_jit_compiled(); + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, diff --git a/mlx/backend/metal/nojit_kernels.cpp b/mlx/backend/metal/nojit_kernels.cpp index 3795a6fb22..9165fdf35c 100644 --- a/mlx/backend/metal/nojit_kernels.cpp +++ b/mlx/backend/metal/nojit_kernels.cpp @@ -368,6 +368,10 @@ MTL::ComputePipelineState* get_quantized_kernel( return d.get_kernel(kernel_name); } +bool kernels_jit_compiled() { + return false; +} + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 03b3cec659..55141475cb 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -1096,7 +1096,11 @@ void qmm( } } int bm = 32, bn = 32, bk = 32; - if (transpose && mode == "affine" && M >= 64 && N % 64 == 0) { + // Only kernels compiled at run time take a tile other than 32 x 32: the + // precompiled library instantiates `affine_qmm_t` at 32 x 32 only, so a + // build without the JIT (CMake's default MLX_METAL_JIT=OFF) keeps it. + if (transpose && mode == "affine" && M >= 64 && N % 64 == 0 && + kernels_jit_compiled()) { switch (requested) { case 64: bm = 64, bn = 64; diff --git a/mlx/utils.h b/mlx/utils.h index 952434813d..d3bf31440d 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -208,7 +208,8 @@ inline bool residency_debug() { // Output tile of the steel affine quantized matmul on GPUs without neural // accelerators (see `qmm` in backend/metal/quantized.cpp): 32, 64, 6432, -// 3264 or 6464, or 0 (default) for the input width's own tile. +// 3264 or 6464, or 0 (default) for the input width's own tile. Builds whose +// kernels come only from the precompiled library keep 32 x 32. inline int qmm_steel_tile() { static int tile_ = get_var("MLX_QMM_STEEL_TILE", 0); return tile_; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 66136c1b9b..ca1e258000 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,7 +20,8 @@ if(MLX_BUILD_METAL) PROPERTIES TIMEOUT 60 ENVIRONMENT "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") endforeach() - list(APPEND METAL_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp) + list(APPEND METAL_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp + quantized_tile_tests.cpp) endif() include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) diff --git a/tests/quantized_tile_tests.cpp b/tests/quantized_tile_tests.cpp new file mode 100644 index 0000000000..5d1374821f --- /dev/null +++ b/tests/quantized_tile_tests.cpp @@ -0,0 +1,112 @@ +// Copyright © 2026 Eigen Labs. +#include + +#include "doctest/doctest.h" +#include "mlx/backend/common/command_buffer_limits.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { +// The calling thread's steel quantized-matmul tile for the scope; 0 is the +// default policy. +struct ScopedSteelTile { + int previous = 0; + explicit ScopedSteelTile(int tile) { + mlx_metal_set_thread_qmm_steel_tile(tile, &previous); + } + ~ScopedSteelTile() { + mlx_metal_set_thread_qmm_steel_tile(previous, nullptr); + } +}; +} // namespace + +TEST_CASE("prompt-sized affine qmm in every kernel build") { + // 512 rows and 1024 outputs take a tile wider than 32 x 32 by default where + // kernels are compiled at run time. A build whose kernels come only from the + // precompiled library must keep 32 x 32 rather than ask that library for a + // tile it never instantiated. The product fills 512 threadgroups at 32 x 32, + // so it runs as one qmm rather than split along K. K = 96 keeps the steel + // kernel on GPUs with neural accelerators too (theirs needs K % 64 == 0); + // K = 192 in groups of 64 adds the 64-deep tile where none serves it. + constexpr int M = 512, N = 1024, bits = 4; + for (auto [K, group_size] : {std::pair{96, 32}, std::pair{192, 64}}) { + auto x = reshape( + divide( + sin(arange(M * K, float32, Device::gpu) * array(0.007f), + Device::gpu), + array(std::sqrt(float(K))), + Device::gpu), + {M, K}); + auto w = reshape( + divide( + cos(arange(N * K, float32, Device::gpu) * array(0.013f), + Device::gpu), + array(std::sqrt(float(K))), + Device::gpu), + {N, K}); + for (auto dtype : {float16, bfloat16, float32}) { + CAPTURE(K); + CAPTURE(dtype); + auto xt = astype(x, dtype, Device::gpu); + auto q = quantize( + astype(w, dtype, Device::gpu), + group_size, + bits, + "affine", + std::nullopt, + Device::gpu); + auto product = [&]() { + auto out = quantized_matmul( + xt, + q[0], + q[1], + q[2], + true, + group_size, + bits, + "affine", + Device::gpu); + eval(out); + return out; + }; + array reference(0.0f); + { + ScopedSteelTile tile(32); + reference = product(); + } + auto w_hat = astype( + dequantize( + q[0], + q[1], + q[2], + group_size, + bits, + "affine", + {}, + {}, + Device::cpu), + float32, + Device::cpu); + auto expected = matmul( + astype(xt, float32, Device::cpu), + transpose(w_hat, Device::cpu), + Device::cpu); + CHECK(allclose( + astype(reference, float32, Device::cpu), + expected, + 1e-2, + 1e-2, + false, + Device::cpu) + .item()); + // Every tile computes each element from the same K slabs in the same + // order, so each gives the 32 x 32 bytes. + for (int t : {0, 64, 6432, 3264, 6464}) { + CAPTURE(t); + ScopedSteelTile tile(t); + CHECK(array_equal(product(), reference, Device::cpu).item()); + } + } + } +} From ce21a37d14444f231736d20f9d34909ee25fc3fe Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:52:28 -0700 Subject: [PATCH 7/9] Fix the run-time template of the head-dim split NAX attention Main's upstream sync brought the head-dim split NAX attention kernel (attention_nax_dsplit, used for head dims 256 and 512 on NAX GPUs). Its template has no BV parameter (the value width is BD) and its precompiled instances leave BV out, but get_steel_attention_nax_kernel in jit_kernels.cpp built the run-time source with attention_nax's arguments, BV included. Every argument after BD then moved one parameter to the left (WM got BV, WN got WM, MaskType got WN), and the source did not compile: steel_attention_nax.h:950:122: error: reference to overloaded function could not be resolved; did you mean to call it? ... attention_nax_dsplit mlx-swift builds jit_kernels.cpp, so with the merged core every head-dim 256 or 512 prefill that takes the NAX full-attention kernel on an M5 threw "Unable to build metal library from source". CMake and wheel builds use the precompiled library and were not affected, which is why Fork Tests did not see it. Upstream ml-explore/mlx main still has the bug (checked at 7ca40033). The split kernel's template now leaves BV out; attention_nax keeps its arguments. Kernel names do not change. fork.yaml describes the fix. Tests (Ultra A, M5 Ultra, Release build with MLX_METAL_JIT=ON): a probe of SDPA prefill, causal, no mask and bool mask, for head dims 64, 128, 256 and 512, bfloat16, float16 and float32, 1024 and 2048 rows: before, all 12 head-dim 256 cases with a causal or bool mask threw the error above (the unmasked and head-dim 512 cases did not take the split kernel); after, all run, and the causal head-dim 256 outputs are byte-equal to the original fix/cluster-metal-fence-wait tip 2e16455f. The bool-mask head-dim 256 outputs differ from 2e16455f because upstream #4416 now runs them in the fused NAX kernel instead of the unfused fallback. Co-Authored-By: Claude Opus 5.5 --- fork.yaml | 14 +++++++++++++ mlx/backend/metal/jit_kernels.cpp | 34 +++++++++++++++++++++---------- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/fork.yaml b/fork.yaml index 8dccd1ea09..d65455a819 100644 --- a/fork.yaml +++ b/fork.yaml @@ -547,6 +547,20 @@ def: globs: - "mlx/backend/metal/kernels/quantized_nax.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - title: "Run-time template of the head-dim split NAX attention" + description: | + Upstream's head-dim split attention (`attention_nax_dsplit`, the NAX full-attention + kernel for head dims 256 and 512) has no BV template parameter: its value width is + BD. The precompiled instances (`instantiate_attn_dsplit`) leave BV out, but the + run-time (JIT) build passed the template arguments of `attention_nax`, BV included, + so every value after BD moved one parameter to the left and the source did not + compile ("Unable to build metal library from source"). A JIT build (mlx-swift + builds this way) therefore failed every head-dim 256 or 512 prefill that takes the + NAX full-attention kernel. `get_steel_attention_nax_kernel` now leaves BV out for + the split kernel. Builds with the precompiled library did not have the bug, and the + kernel names do not change. + globs: + - "mlx/backend/metal/jit_kernels.cpp" - title: "64-bit products in the JACCL ring and the vector SDPA layout check" description: | The JACCL ring computes each wire's byte offset as `lr * n_wires * size`. Upstream diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index 376a1ed0b0..6dd45f4418 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -1422,21 +1422,33 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { std::string kernel_source; + // attention_nax_dsplit has no BV parameter (its value width is BD). + auto template_def = split_d ? get_template_definition( + lib_name, + "attention_nax_dsplit", + get_type_string(q.dtype()), + bq, + bk, + bd, + wm, + wn, + get_type_string(m.dtype())) + : get_template_definition( + lib_name, + "attention_nax", + get_type_string(q.dtype()), + bq, + bk, + bd, + bv, + wm, + wn, + get_type_string(m.dtype())); concatenate( kernel_source, metal::utils(), metal::steel_attention_nax(), - get_template_definition( - lib_name, - split_d ? "attention_nax_dsplit" : "attention_nax", - get_type_string(q.dtype()), - bq, - bk, - bd, - bv, - wm, - wn, - get_type_string(m.dtype()))); + template_def); return kernel_source; }); return d.get_kernel(kernel_name, lib, hash_name, func_consts); From caa9ed5378d83624907e97cb40061ea2326f098c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:49:28 -0700 Subject: [PATCH 8/9] Add MLX_QMV_BATCH_INVARIANT to keep quantized rows on the vector kernels Main's upstream sync added two routes that take some row counts of a quantized x @ w.T below the vector limit (get_qmv_batch_limit) away from the vector kernels: - qmv_mma / qmv_nax (ml-explore/mlx#4712): 6 to 16 rows of the floating-point modes (NVFP4, MXFP4, MXFP8) when K % 128 == 0 and N and K are large (N, K >= 2048 on GPUs with neural accelerators); - the staged NAX split-K kernel (qmm_splitk_nax, #4682): affine products from 8 rows to the limit with M * N >= 16384, on GPUs with neural accelerators. A row then has other bits at those counts than at 2 to 5 rows. Requests that share one launch (the speculative verify windows of several requests, GLM's row groups) then do not get the bits that each request gets alone. MLX_QMV_BATCH_INVARIANT=1 (env::qmv_batch_invariant, read once in each process) skips both routes for rows below the vector limit, so they run dispatch_qmv as before the sync: qmv for one row, qmv_wide from two rows (qmv where qmv_wide does not serve the mode). Each row then has the same bits at each count from 2 to the limit - 1. From the limit on, and without the switch, the routes do not change. A row alone (qmv) can have other bits than the same row among two or more rows (qmv_wide), as before. - tests/qmv_batch_invariant_tests.cpp (Metal): GLM/Qwen TP shard shapes (N x K = 4096 x 4096, 6144 x 4096, 4096 x 6144, 8704 x 5120, 5120 x 8704, 3072 x 5120, 2048 x 4096, 1024 x 4096), affine 4-bit g64 and NVFP4, bfloat16 and float32 inputs. Each window of 2 to `count` rows, at the start and at the end, has the bytes of the same rows in the `count`-row product, and each row alone has the bytes of a batch of single rows (x [R, 1, K] with broadcast weights: the decode-row path). `count` is the vector limit - 1 with the switch and 5 without it. - tests/CMakeLists.txt: the qmv_batch_invariant ctest entry runs the case in a new process with the switch on, and fails if no case has the name. Fork Tests runs that entry. - environment_variables.rst and fork.yaml describe the switch. Tests (Ultra A, M5 Ultra). Debug build with precompiled kernels, as the CI build-cpp job: the doctest suite with the switch off and on (322 cases; 10,608 and 11,400 assertions) passes except the 6 linear-algebra cases that already fail with TF32 on neural accelerators; it passes 322/322 with MLX_ENABLE_TF32=0 (switch off and on) and on the CPU. The qmv_batch_invariant entry (1,209 assertions), the allocation-cap entries (15) and the fence-chain entries (3) pass. Release builds with MLX_METAL_JIT=ON (mlx-swift's mode), the 32 shape, mode and input-type cases above at 1 to 31 rows: with the switch, every product below the vector limit is byte-equal to the pre-sync #41 head d11238f1, and verify windows of 2 to 6 rows that share a product below the limit are byte-equal to each window alone; without the switch, every product is byte-equal to ce21a37d. clang-format 21, cmake-format 0.6.13 and the fork.yaml check (145/145) pass. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fork-tests.yml | 11 ++ docs/src/usage/environment_variables.rst | 14 ++ fork.yaml | 26 ++++ mlx/backend/metal/quantized.cpp | 12 +- mlx/utils.h | 9 ++ tests/CMakeLists.txt | 15 +- tests/qmv_batch_invariant_tests.cpp | 170 +++++++++++++++++++++++ 7 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 tests/qmv_batch_invariant_tests.cpp diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index e036d361ff..277195608e 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -164,6 +164,17 @@ jobs: ctest --test-dir build -R '^metal_fence_chain_' --output-on-failure \ --no-tests=error + - name: Run the quantized matmul rows with MLX_QMV_BATCH_INVARIANT=1 + # MLX reads the switch once in each process. The C++ test steps above + # run the case with the switch off; this ctest entry runs it again + # with the switch on (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/qmv-%p-%m.profraw + run: | + ctest --test-dir build -R '^qmv_batch_invariant$' \ + --output-on-failure --no-tests=error + - name: Merge the coverage profiles if: ${{ !cancelled() && steps.build.outcome == 'success' }} run: | diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 3ad878fc9a..b41afbc334 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -143,6 +143,20 @@ Metal it to ``0`` to use the GEMM convolution for all inputs. See :doc:`precision`. +.. envvar:: MLX_QMV_BATCH_INVARIANT + + Set it to ``1`` to compute a quantized matrix product ``x @ w.T`` with + fewer rows than the vector limit only with the vector kernels: ``qmv`` for + one row and ``qmv_wide`` from two rows. Then each row gets the same bits at + each row count from 2 to the limit - 1, so the rows of different requests + can share one product. The default, ``0``, also uses faster kernels that + give a row different bits at some row counts: ``qmv_mma`` for 6 to 16 rows + of the floating-point modes, and the affine split-K kernel from 8 rows on + GPUs with neural accelerators. The vector limit is 6 to 33 rows; it + depends on the GPU and on the shape. A row alone (``qmv``) can get bits + that are different from the bits of the same row among two or more rows. + MLX reads this variable once in each process. + Advanced tuning --------------- diff --git a/fork.yaml b/fork.yaml index d65455a819..4b5e4eb1ff 100644 --- a/fork.yaml +++ b/fork.yaml @@ -122,6 +122,32 @@ def: - "mlx/utils.h" - "docs/src/usage/environment_variables.rst" - "tests/quantized_tile_tests.cpp" + - title: "Batch-invariant quantized matmul rows (opt-in)" + description: | + Opt-in (`MLX_QMV_BATCH_INVARIANT=1`, read once in each process). A quantized `x @ w.T` + with fewer rows than the vector limit (`get_qmv_batch_limit`) then runs only the vector + kernels, as upstream did before two of its routes: `qmv` for one row, and `qmv_wide` + from two rows (`qmv` where `qmv_wide` does not serve the mode on the GPU). These + routes do not run below the limit: `qmv_mma`/`qmv_nax` for 6 to 16 rows of the + floating-point modes ([ml-explore/mlx#4712](https://github.com/ml-explore/mlx/pull/4712)) + and the staged NAX split-K kernel for affine products from 8 rows + ([ml-explore/mlx#4682](https://github.com/ml-explore/mlx/pull/4682)). Each row then has + the same bits at each row count from 2 to the limit - 1, so the rows of several + requests in one launch (for example their speculative verify windows) get the bits + that each request gets alone. A row alone (`qmv`) can have other bits than the same + row among two or more rows, as before. From the limit on, and without the switch, + the routes do not change. `tests/qmv_batch_invariant_tests.cpp` compares each window + of rows with the same rows in a larger launch at GLM and Qwen tensor-parallel shapes, + for affine and NVFP4 weights with bfloat16 and float32 inputs. The tests binary runs + it without the switch (up to 5 rows), and the `qmv_batch_invariant` ctest entry, which + Fork Tests runs, runs it with the switch (every count below the limit). + globs: + - "mlx/utils.h" + - "mlx/backend/metal/quantized.cpp" + - "docs/src/usage/environment_variables.rst" + - "tests/qmv_batch_invariant_tests.cpp" + - "tests/CMakeLists.txt" + - ".github/workflows/fork-tests.yml" - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" description: | GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 48f50cff94..0d5e6c8220 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -2504,16 +2504,22 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { int vector_limit = transpose_ ? get_qmv_batch_limit(K, N, d) : 4; auto mode = quantization_mode_to_string(mode_); + // With MLX_QMV_BATCH_INVARIANT=1, rows below the vector limit use only the + // vector kernels (dispatch_qmv), as before the qmv_mma and the mid-row NAX + // split-K routes. Then each row has the same bits at each row count from 2 + // to the limit - 1. + bool vector_rows = env::qmv_batch_invariant() && M < vector_limit; + // For few rows use qmv_mma when N/K is large enough. - if (transpose_ && non_batched && (M >= 6) && (M <= 16) && + if (!vector_rows && transpose_ && non_batched && (M >= 6) && (M <= 16) && use_qmv_mma(x, w, scales, mode_, M, N, K, d)) { qmv_mma(x, w, scales, out, group_size_, bits_, M, N, K, d, s, mode); return; } // For mid rows use NAX qmm when output is large enough. - if (transpose_ && non_batched && (M >= 8) && (M < vector_limit) && - (M * N >= 16384) && + if (!vector_rows && transpose_ && non_batched && (M >= 8) && + (M < vector_limit) && (M * N >= 16384) && use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size_)) { qmm_splitk_nax( x, w, scales, biases, out, group_size_, bits_, M, N, K, d, s, mode); diff --git a/mlx/utils.h b/mlx/utils.h index b74eb120ff..f47f276431 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -233,6 +233,15 @@ inline int qmm_steel_tile_min_groups() { return groups_; } +// Quantized matmuls (x @ w.T) with fewer rows than the vector limit use only +// the vector kernels (see `QuantizedMatmul::eval_gpu` in +// backend/metal/quantized.cpp). Then a row has the same bits at each row count +// from 2 to the limit - 1. +inline bool qmv_batch_invariant() { + static bool invariant_ = get_var("MLX_QMV_BATCH_INVARIANT", 0); + return invariant_; +} + inline bool metal_fast_synch() { static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0); return metal_fast_synch; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ba9f2b4995..abb29b114d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -26,7 +26,20 @@ if(MLX_BUILD_METAL) "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") endforeach() list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp - quantized_tile_tests.cpp) + quantized_tile_tests.cpp qmv_batch_invariant_tests.cpp) + # MLX reads MLX_QMV_BATCH_INVARIANT once in each process, so this entry runs + # the case again in a new process with the switch on. The tests entries run it + # with the switch off. The entry fails also if no test case has this name. + add_test( + NAME qmv_batch_invariant + COMMAND + tests + "--test-case=quantized matmul rows keep their bits below the vector limit" + ) + set_tests_properties( + qmv_batch_invariant + PROPERTIES ENVIRONMENT "MLX_QMV_BATCH_INVARIANT=1" PASS_REGULAR_EXPRESSION + "test cases: +1 \\| +1 passed \\| +0 failed") endif() include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) diff --git a/tests/qmv_batch_invariant_tests.cpp b/tests/qmv_batch_invariant_tests.cpp new file mode 100644 index 0000000000..57047120f9 --- /dev/null +++ b/tests/qmv_batch_invariant_tests.cpp @@ -0,0 +1,170 @@ +// Copyright © 2026 Eigen Labs. +#include +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" +#include "mlx/utils.h" + +using namespace mlx::core; + +namespace { + +// A copy of get_qmv_batch_limit (backend/metal/quantized.cpp): the first row +// count of x @ w.T (K inputs, N outputs) that takes a matrix kernel. +int qmv_batch_limit(int K, int N) { + auto& d = metal::device(Device::gpu); + char size = d.get_architecture().back(); + int gen = d.get_architecture_gen(); + bool small = K <= 2048 && N <= 2048; + bool medium = K <= 4096 && N <= 4096; + if (size != 'd' && gen >= 17) { + return small ? 33 : (medium ? 25 : 13); + } + if (size != 'd' && gen >= 15) { + return small ? 13 : (medium ? 15 : 13); + } + if (size == 'd') { + return small ? 32 : (medium ? 18 : 12); + } + if (gen >= 13) { + return small ? 14 : (medium ? 10 : ((gen == 13 && size == 's') ? 7 : 6)); + } + return small ? 18 : (medium ? 12 : 10); +} + +struct Weights { + std::string mode; + int group_size; + array w; + array scales; + std::optional biases; +}; + +// Synthetic 4-bit weights with N outputs and K inputs: random packed values, +// affine in groups of 64 with bfloat16 scales and biases, or nvfp4 with +// positive e4m3 scales (bytes 0x20 to 0x4f). +Weights weights(const std::string& mode, int N, int K, uint64_t seed) { + auto key = [&](int i) { return random::key(4 * seed + i); }; + auto w = random::bits({N, K / 8}, 4, key(0), Device::gpu); + if (mode == "affine") { + auto values = [&](int i, float scale) { + return astype( + random::normal( + {N, K / 64}, float32, 0.0f, scale, key(i), Device::gpu), + bfloat16, + Device::gpu); + }; + return {mode, 64, w, values(1, 0.02f), values(2, 0.05f)}; + } + auto scales = random::randint( + array(0x20), array(0x50), {N, K / 16}, uint8, key(1), Device::gpu); + return {mode, 16, w, scales, std::nullopt}; +} + +array product(const Weights& q, const array& x) { + return quantized_matmul( + x, q.w, q.scales, q.biases, true, q.group_size, 4, q.mode, Device::gpu); +} + +// Each row of x [R, K] as its own product in one launch: x [R, 1, K] and the +// weights broadcast to [R, N, K / 8], so M = 1 and the batch is R (the +// decode rows of a batch of requests). +array single_rows(const Weights& q, const array& x) { + auto lead = [](const array& a) { return expand_dims(a, 0, Device::gpu); }; + auto y = quantized_matmul( + expand_dims(x, 1, Device::gpu), + lead(q.w), + lead(q.scales), + q.biases ? std::optional(lead(*q.biases)) : std::nullopt, + true, + q.group_size, + 4, + q.mode, + Device::gpu); + return squeeze(y, 1, Device::gpu); +} + +array rows(const array& a, int start, int stop) { + return slice(a, {start, 0}, {stop, a.shape(1)}, Device::gpu); +} + +// Compares the bytes, so that 0 and -0 differ and two NaNs can be equal. +bool same_bytes(const array& a, const array& b) { + auto bytes = [](const array& x) { + auto type = x.dtype() == float32 ? uint32 : uint16; + return view(contiguous(x, false, Device::gpu), type, Device::gpu); + }; + return array_equal(bytes(a), bytes(b), Device::cpu).item(); +} + +} // namespace + +TEST_CASE("quantized matmul rows keep their bits below the vector limit") { + // MLX reads MLX_QMV_BATCH_INVARIANT once in each process. The tests binary + // runs this case without it, and the qmv_batch_invariant ctest entry runs + // it again with MLX_QMV_BATCH_INVARIANT=1 (tests/CMakeLists.txt). + const char* value = std::getenv("MLX_QMV_BATCH_INVARIANT"); + bool invariant = value != nullptr && std::atoi(value) != 0; + REQUIRE(env::qmv_batch_invariant() == invariant); + + // Tensor-parallel shard shapes (N outputs, K inputs) of GLM and Qwen + // projections. + std::vector> shapes = { + {4096, 4096}, + {6144, 4096}, + {4096, 6144}, + {8704, 5120}, + {5120, 8704}, + {3072, 5120}, + {2048, 4096}, + {1024, 4096}}; + for (auto [N, K] : shapes) { + // With the switch, every row count below the vector limit. Without it, + // up to 5 rows: from 6 rows other kernels can serve some shapes + // (qmv_mma from 6 rows, the NAX split-K from 8 rows). + int limit = qmv_batch_limit(K, N); + int count = invariant ? limit - 1 : std::min(5, limit - 1); + for (auto mode : {"affine", "nvfp4"}) { + auto q = weights(mode, N, K, N + K); + for (auto dtype : {bfloat16, float32}) { + CAPTURE(N); + CAPTURE(K); + CAPTURE(mode); + CAPTURE(dtype); + CAPTURE(count); + auto x = astype( + random::normal( + {count, K}, float32, 0.0f, 1.0f, random::key(K), Device::gpu), + dtype, + Device::gpu); + auto all = product(q, x); + eval(all); + // A window of m rows alone (one request) has the bits of the same + // rows among all the rows (several requests in one launch), at the + // start and at the end. From 2 rows the vector kernel is qmv_wide + // (or qmv where qmv_wide does not serve the mode on this GPU). + for (int m = 2; m <= count; ++m) { + CAPTURE(m); + CHECK(same_bytes(product(q, rows(x, 0, m)), rows(all, 0, m))); + CHECK(same_bytes( + product(q, rows(x, count - m, count)), + rows(all, count - m, count))); + } + // One row is qmv: alone, it has the bits that it has in a batch of + // single rows. It can have other bits among more rows. + auto singles = single_rows(q, x); + for (int i = 0; i < count; ++i) { + CAPTURE(i); + CHECK(same_bytes( + product(q, rows(x, i, i + 1)), rows(singles, i, i + 1))); + } + } + } + } +} From b2d92e5b6a4aa455b67360be935369b9018cd87c Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 27 Oct 2026 17:56:57 -0500 Subject: [PATCH 9/9] Update the fast fence before the event fence; test two GPU streams that feed the CPU - transforms.cpp: an array read by the CPU and by another GPU stream updates the fast fence first and the event fence second. The fast update with cross_device can move the array (CUDA queues a copy to unified memory and swaps the pointer), so an event recorded before it let the other GPU stream read the new buffer before the copy finished. MLX_EAGER_FENCE_COMMIT now commits after both updates. - metal_fence_chain: a case where both GPU streams feed the CPU stream, so the producer waits for the CPU result on an event of the CPU stream and the CPU stream waits for both GPU streams. Before, only GPU-to-GPU event waits ran. Co-Authored-By: Claude Opus 5.5 --- docs/src/usage/using_streams.rst | 3 ++- fork.yaml | 9 +++++--- mlx/transforms.cpp | 35 +++++++++++++++++--------------- tests/metal_fence_chain.cpp | 33 +++++++++++++++++++++++++++++- 4 files changed, 59 insertions(+), 21 deletions(-) diff --git a/docs/src/usage/using_streams.rst b/docs/src/usage/using_streams.rst index 345ab09e05..a4211c55b1 100644 --- a/docs/src/usage/using_streams.rst +++ b/docs/src/usage/using_streams.rst @@ -34,7 +34,8 @@ GPU stream waiting for CPU work that can itself wait for another GPU stream. The other CPU-to-GPU and GPU-to-CPU waits keep the fast path. The standalone ``metal_fence_chain`` test checks exact GPU-to-CPU-to-GPU chains -with shared side roots and request-array retirement. CTest runs separate +with shared side roots, chains where two GPU streams feed the CPU, and +request-array retirement. CTest runs separate processes with fast synchronization and several command-buffer sizes, with a 60-second timeout per process. This component test does not qualify distributed collective order, a transport, or an installed model service. diff --git a/fork.yaml b/fork.yaml index 4b5e4eb1ff..2de78d4e8f 100644 --- a/fork.yaml +++ b/fork.yaml @@ -419,7 +419,8 @@ def: path. Without it, a spinning wait can run before a GPU producer needed by the CPU work it awaits. Arithmetic and command-buffer limits do not change. A standalone bounded test checks exact GPU-to-CPU-to-GPU chains, - shared side roots and request-array retirement at several buffer sizes. + shared side roots, chains where two GPU streams feed the CPU, and request-array + retirement at several buffer sizes. Fork Tests executes the three CTest processes on its Metal runner and rejects a missing test registration. This component coverage does not establish an installed RDMA model fix. @@ -438,8 +439,10 @@ def: the first one spins, so the producing queue can starve and both stop. An eval whose graph spans two GPU streams therefore waits for the other GPU stream on a shared event (the non-fast path), while CPU <-> GPU waits keep the fast path. An array read - both by the CPU and by another GPU stream updates both fences. Synchronization only: - results do not change. + both by the CPU and by another GPU stream updates both fences, the fast fence first: + its cross-device update can move the array (CUDA moves it to unified memory), and the + event must be recorded after the move. `MLX_EAGER_FENCE_COMMIT` commits after both + updates. Synchronization only: results do not change. globs: - "mlx/fence.h" - "mlx/transforms.cpp" diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 6162cbe10d..a5460ae11e 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -470,6 +470,17 @@ array eval_impl(std::vector outputs, bool async) { auto maybe_update_fence = [&fences, &event_fences, &needs_fence, stream]( const array& a) { if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) { + // The fast update comes first: with cross_device it can move `a` + // (CUDA moves it to unified memory), and the event update must + // come after that move so that event waiters see the moved data. + if (nf->second.fast) { + auto it = fences.find(stream.index); + if (it == fences.end()) { + it = fences.emplace(stream.index, Fence{stream}).first; + } + nf->second.fast_value = + it->second.update(stream, a, nf->second.cross_device); + } if (nf->second.event) { auto it = event_fences.find(stream.index); if (it == event_fences.end()) { @@ -479,22 +490,14 @@ array eval_impl(std::vector outputs, bool async) { } nf->second.event_value = it->second.update(stream, a, false); } - if (nf->second.fast) { - auto it = fences.find(stream.index); - if (it == fences.end()) { - it = fences.emplace(stream.index, Fence{stream}).first; - } - nf->second.fast_value = - it->second.update(stream, a, nf->second.cross_device); - // 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.cross_device && - stream.device == Device::gpu) { - gpu::finalize(stream); - } + // MLX_EAGER_FENCE_COMMIT=1: commit the GPU work now, after both + // updates, 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.fast && nf->second.cross_device && + stream.device == Device::gpu) { + gpu::finalize(stream); } } }; diff --git a/tests/metal_fence_chain.cpp b/tests/metal_fence_chain.cpp index 968ab06cbb..1c568ef2e5 100644 --- a/tests/metal_fence_chain.cpp +++ b/tests/metal_fence_chain.cpp @@ -102,11 +102,42 @@ int main(int argc, char** argv) { std::cout << "{\"event\":\"case\",\"streams\":\"two-gpu\",\"width\":" << width << ",\"layers\":" << layers << "}" << std::endl; } + // Both GPU streams feed the CPU in the same chain, so no GPU stream may + // spin on the CPU work: the producer waits for the CPU result on an + // event of the CPU stream, and the CPU stream waits for both. + for (int width : {1, 2, 4}) { + { + auto x = zeros({width, 5120}, float32, producer); + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + // (x - x) + 2 = 2, exact in float32. + auto gate = add(subtract(x, x, side), array(2.0f), side); + auto reduced = add(partial, gate, host); + x = add(reduced, array(3.0f), producer); + } + eval(x); + synchronize(producer); + synchronize(side); + synchronize(host); + const float* values = x.data(); + for (size_t i = 0; i < x.size(); ++i) { + if (values[i] != layers * 6.0f) { + throw std::runtime_error("exact two-GPU-to-CPU chain mismatch"); + } + ++comparisons; + } + } + synchronize(producer); + synchronize(side); + synchronize(host); + std::cout << "{\"event\":\"case\",\"streams\":\"two-to-cpu\",\"width\":" + << width << ",\"layers\":" << layers << "}" << std::endl; + } } synchronize(producer); synchronize(host); clear_streams(); - std::cout << "{\"event\":\"passed\",\"cases\":" << (cpu_only ? 15 : 18) + std::cout << "{\"event\":\"passed\",\"cases\":" << (cpu_only ? 15 : 21) << ",\"comparisons\":" << comparisons << ",\"device\":\"" << (cpu_only ? "cpu" : "gpu") << "\"}" << std::endl; return 0;