diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index 8cad0b2499..1da61a584d 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -9,7 +9,7 @@ name: Fork Tests # with the GPU and then with the CPU as the default device, # and the JACCL tests with simulated verbs (tests/jaccl). # Then it runs the standalone allocation cap tests, one -# process for each case. +# process for each case, and the bounded Metal fence chains. # python-gpu runs the Python tests with the GPU as the default device. # python-cpu runs the Python tests with the CPU as the default device. # metal-build-and-test @@ -167,6 +167,28 @@ jobs: ctest --test-dir build -R '^process_allocation_cap' -V \ --no-tests=error + - name: Run the bounded Metal fence chains + # metal_fence_chain runs exact GPU -> CPU -> GPU chains with fast + # synchronization at three command buffer sizes, one ctest entry for + # each, each with a 60 s timeout (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + 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 + + - 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 3874e136a3..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 --------------- @@ -179,6 +193,26 @@ 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. 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 + + 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/docs/src/usage/using_streams.rst b/docs/src/usage/using_streams.rst index 058bc59dea..a4211c55b1 100644 --- a/docs/src/usage/using_streams.rst +++ b/docs/src/usage/using_streams.rst @@ -16,3 +16,26 @@ 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. + +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, 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 40f8fef456..8adb49b1be 100644 --- a/fork.yaml +++ b/fork.yaml @@ -85,6 +85,69 @@ 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`. + 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. A wide tile passes upstream's + template arguments in order (global scale, then BM, BK, BN); upstream's own 64 x 64 + FP4 tile (half-loader `fp_qmm_t`, precompiled) keeps its name and its selection. + globs: + - "mlx/backend/common/command_buffer_limits.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/quantized.cpp" + - "mlx/backend/metal/kernels.h" + - "mlx/backend/metal/jit_kernels.cpp" + - "mlx/backend/metal/nojit_kernels.cpp" + - "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 @@ -353,6 +416,57 @@ def: - "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 + 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, 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. + 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: "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, 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" + - "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 @@ -470,18 +584,18 @@ def: globs: - "mlx/backend/metal/kernels/quantized_nax.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - - title: "JIT instantiation of the NAX head-dim split attention kernel" - description: | - `get_steel_attention_nax_kernel` builds the JIT source of both `attention_nax` and - `attention_nax_dsplit`, and upstream passes `bv` to both. `attention_nax_dsplit` has - no `BV` template parameter (its value head dim is `BD`), so every later argument - shifts by one, an integer lands in the `MaskType` slot, and the library does not - compile. JIT builds such as mlx-swift's compile this kernel at runtime for full - attention with head dim 256 or 512 and at least 1,024 query tokens on NAX GPUs, and - the caller's process exited with "Unable to build metal library from source". The - fork passes the split kernel the same arguments as its instantiation in - `steel_attention_nax.metal`; the non-split kernel is unchanged. Builds that use the - precompiled metallib were not affected. This is a latent upstream bug (PR #48). + - 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" diff --git a/mlx/backend/common/command_buffer_limits.h b/mlx/backend/common/command_buffer_limits.h index 2f1d37cea6..e5ca795989 100644 --- a/mlx/backend/common/command_buffer_limits.h +++ b/mlx/backend/common/command_buffer_limits.h @@ -23,6 +23,16 @@ 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. 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 } #endif diff --git a/mlx/backend/cuda/fence.cpp b/mlx/backend/cuda/fence.cpp index d410b46907..bea4022bc5 100644 --- a/mlx/backend/cuda/fence.cpp +++ b/mlx/backend/cuda/fence.cpp @@ -25,6 +25,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&, uint32_t value) { auto& f = cast(); if (value == 0) { diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index c51489aad1..66f599e35e 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -542,6 +542,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, @@ -559,6 +562,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 @@ -1130,6 +1137,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 43275dc619..92e6b4589b 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -460,6 +460,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/fence.cpp b/mlx/backend/metal/fence.cpp index bf5ae3754e..b6f86e5fce 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -12,12 +12,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) { @@ -94,6 +95,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, uint32_t value) { auto& f = *static_cast(fence_.get()); diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index 5cfeebd928..f231b9b483 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -1069,6 +1069,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 ded6c834ab..f19e8a7df1 100644 --- a/mlx/backend/metal/kernels.h +++ b/mlx/backend/metal/kernels.h @@ -312,6 +312,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 93f8cf311f..4adb17659c 100644 --- a/mlx/backend/metal/nojit_kernels.cpp +++ b/mlx/backend/metal/nojit_kernels.cpp @@ -375,6 +375,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 f43a4ad5b5..0d5e6c8220 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -1219,11 +1219,65 @@ 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; + // 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; + 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 bk = 32; - int bn = 32; // Tune for larger tile with Fp4HalfLoader. if (use_fp4_half_loader(x, mode, global_scale, bits) && transpose) { @@ -1256,8 +1310,11 @@ void qmm( bits, transpose ? (aligned ? "_alN_true" : "_alN_false") : "", batched ? "_batch_1" : "_batch_0", - (bm == 64 && bn == 64) ? "_bm_64_bn_64" : "", + (!wide_tile && bm == 64 && bn == 64) ? "_bm_64_bn_64" : "", global_scale ? "_hgs" : ""); + if (wide_tile) { + concatenate(kname, "_bm", bm, "_bk", bk, "_bn", bn); + } std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { @@ -2447,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/backend/no_gpu/fence.cpp b/mlx/backend/no_gpu/fence.cpp index 48547869b5..566f575e6c 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&, uint32_t value) { auto event = cast().event; event.set_value(value); diff --git a/mlx/fence.h b/mlx/fence.h index a76d96e745..80a05cf6d4 100644 --- a/mlx/fence.h +++ b/mlx/fence.h @@ -25,6 +25,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); uint32_t update(Stream stream, const array& x, bool cross_device); void wait(Stream stream, const array& x, uint32_t value); diff --git a/mlx/ops.cpp b/mlx/ops.cpp index b67fbd0342..bb7053d0e0 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -3775,7 +3775,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); } @@ -4054,7 +4054,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()) { @@ -4967,8 +4967,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}; } @@ -5238,7 +5244,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); biases = where(equal(q0, zero, s), zero, edge, s); } diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index f5ae87cde3..a5460ae11e 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -198,12 +198,22 @@ array eval_impl(std::vector outputs, bool async) { return default_stream(default_device()); }(); - struct FenceInfo { - int stream_index; - bool cross_device; - uint32_t value{0}; + // 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}; + // The values that the fence updates returned (see Fence::update). + uint32_t fast_value{0}; + uint32_t event_value{0}; }; - std::unordered_map needs_fence; + 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; @@ -213,6 +223,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; @@ -260,11 +279,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(), - FenceInfo{in.primitive().stream().index, device_switch}); - if (!inserted) { - it->second.cross_device |= 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); @@ -296,6 +328,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>>(); @@ -375,11 +418,22 @@ 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& info = it->second; - auto& fence = fences.at(info.stream_index); + 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.at(need.stream).wait(stream, in, need.event_value); + continue; + } + auto& fence = fences.at(need.stream); if (!one_gpu_stream || - !fence.wait_in_consumer(stream, arr, i, info.value)) { - fence.wait(stream, in, info.value); + !fence.wait_in_consumer(stream, arr, i, need.fast_value)) { + fence.wait(stream, in, need.fast_value); } } else if (in.event().valid()) { if (in.event().is_signaled()) { @@ -413,26 +467,40 @@ 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; - } - nf->second.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); - } + 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()) { + it = event_fences + .emplace(stream.index, Fence{stream, /* fast */ false}) + .first; + } + nf->second.event_value = it->second.update(stream, a, false); + } + // 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); + } + } + }; arr.set_status(array::Status::evaluated); // TODO Maybe always want the fence coherent kernel in the same cbuf diff --git a/mlx/utils.h b/mlx/utils.h index 86d77527e1..f47f276431 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -217,6 +217,31 @@ 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. 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_; +} + +// 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_; +} + +// 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 83876c2f4c..abb29b114d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -16,7 +16,30 @@ if(MLX_BUILD_CUDA) endif() if(MLX_BUILD_METAL) - list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp) + 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 GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_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/metal_fence_chain.cpp b/tests/metal_fence_chain.cpp new file mode 100644 index 0000000000..1c568ef2e5 --- /dev/null +++ b/tests/metal_fence_chain.cpp @@ -0,0 +1,148 @@ +// 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; + } + } + // 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; + } + // 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 : 21) + << ",\"comparisons\":" << comparisons << ",\"device\":\"" + << (cpu_only ? "cpu" : "gpu") << "\"}" << std::endl; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << std::endl; + return 1; + } +} diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index f74db9bef1..e670542b91 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4938,3 +4938,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); +} 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))); + } + } + } + } +} 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()); + } + } + } +}