From b7434f7f8bbf94fbecc2c58fe5dac615f459533f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:28:16 -0700 Subject: [PATCH 01/12] Revert the NAX gather_qmm simdgroup skip (#4352) on this tree Upstream ml-explore/mlx c7ff35d97 ("Skip unnecessary simdgroup computations for quantised MOE matmuls on NAX", #4352) reached this fork through the v0.32.2 squash (734241bb), not by ancestry, in the form that #4572 later gave it: `const bool sg_active = sgp_sm > 0;` and two `if (sg_active)` blocks around the MMA loop in each of fp_gather_qmm_rhs_nax (fp_quantized_nax.h) and affine_gather_qmm_rhs_nax (quantized_nax.h). This removes the flag and runs the MMA in every simdgroup again, as before #4352. It is the same change as the earlier revert of #4352 on 0.32.2 (e9debbeaa) and its re-application on the 0.32.3 kernels, hand-ported because the surrounding lines differ here. Why: these kernels run only on GPUs with NAX. On a two-Mac JACCL pair with one NAX GPU, mixture-of-experts serving with the skip present lost all-reduce completions, and 92 to 96 GiB stayed wired on the host until it was rebooted. The builds that served that pair afterwards carried the revert. It is therefore kept out of every build that runs distributed on mixed hardware. Output is unchanged: stores stay bounded by sgp_sm, and the rows past the tile that the MMA now reads are either inside M (rows_in_bounds) or loaded as zeros by load_safe with sgp_sm rows. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ccf517a04bb168258009be33042b4acd677dc913) --- fork.yaml | 9 ++ mlx/backend/metal/kernels/fp_quantized_nax.h | 100 +++++++++---------- mlx/backend/metal/kernels/quantized_nax.h | 88 ++++++++-------- 3 files changed, 95 insertions(+), 102 deletions(-) diff --git a/fork.yaml b/fork.yaml index 3a72e886dd..d392efc724 100644 --- a/fork.yaml +++ b/fork.yaml @@ -296,6 +296,15 @@ def: floating-point kernels have no global-scale input, and the NAX kernels keep the fork's bound for the last K tile. The section disappears once the fork rebases onto an upstream commit at or past `90089440`. + + One upstream change in these NAX kernels is reverted on purpose: the simdgroup skip + of [ml-explore/mlx#4352](https://github.com/ml-explore/mlx/pull/4352) (`c7ff35d9`, + which arrived with the v0.32.2 changes; `#4572` kept it as + `sg_active = sgp_sm > 0`). `fp_gather_qmm_rhs_nax` and `affine_gather_qmm_rhs_nax` run + the MMA in every simdgroup again. With the skip, mixture-of-experts serving on a + two-Mac JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB + wired until a reboot. Stores stay bounded by `sgp_sm`, so the output is unchanged. + Keep the revert at every rebase onto upstream. globs: - ".gitignore" - "benchmarks/python/swiglu_bench.py" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 39fbfd0d54..c7f9f8fcc7 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -882,8 +882,6 @@ template < using AccumType = float; - const bool sg_active = sgp_sm > 0; - NAXTile Dtile; Dtile.clear(); @@ -913,35 +911,31 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } - - if constexpr (transpose) { - Btile.template load( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load( - Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); } + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } xn += BK; @@ -955,32 +949,28 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - const short psk = min(int(SK), max(0, (BK - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); - - if constexpr (transpose) { - Btile.template load( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load( - Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + const short psk = min(int(SK), max(0, (BK - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } } diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 0921d007a3..bf90bb84fa 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -1561,8 +1561,6 @@ template < using AccumType = float; - const bool sg_active = sgp_sm > 0; - NAXTile Dtile; Dtile.clear(); @@ -1593,33 +1591,31 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; - - volatile int compiler_barrier; - - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } - - if constexpr (transpose) { - Btile.template load(Ws + tn * BK_padded + kk1); - } else { - Btile.template load(Ws + tn + kk1 * BN_padded); - } - - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); - - (void)compiler_barrier; + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); } + + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; } xn += BK; @@ -1633,30 +1629,28 @@ template < STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile Atile; - NAXTile Btile; + NAXTile Atile; + NAXTile Btile; - volatile int compiler_barrier; + volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + const short psk = min(int(SK), max(0, (BK - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); - if constexpr (transpose) { - Btile.template load(Ws + tn * BK_padded + kk1); - } else { - Btile.template load(Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load(Ws + tn * BK_padded + kk1); + } else { + Btile.template load(Ws + tn + kk1 * BN_padded); + } - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); - (void)compiler_barrier; - } + (void)compiler_barrier; } } From 0077571e8330ce6d4a06c394f25f55e146227451 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:20:08 -0700 Subject: [PATCH 02/12] fix(metal): bound sorted quantized NAX tail loads Use the remaining reduction width for the final activation tile. Check row and packed-column bounds before reading affine or floating-quantized weights and scales, then zero padding lanes. Add exact-value partial-tile and NaN-neighbor regression coverage for affine, MXFP4, MXFP8 and NVFP4. The companion Swift regression reproduced 48 failing geometries and passes all 272 cases with this repair. The original MiMo and Qwen fallback failures also pass on M5 Max. AI assistance: Codex diagnosed, implemented and tested this patch under the repository owner's explicit direction. (cherry picked from commit eb576eb2684f9d97dd2460db52edd717decc6b58) --- fork.yaml | 18 +++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 25 ++++---- mlx/backend/metal/kernels/quantized_nax.h | 52 ++++++++-------- python/tests/test_quantized.py | 62 ++++++++++++++++++++ 4 files changed, 116 insertions(+), 41 deletions(-) diff --git a/fork.yaml b/fork.yaml index d392efc724..eebcaa1509 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,15 +169,29 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" + - title: "Quantized NAX partial-tile bounds" + description: | + Sorted gathered matrix products use the remaining reduction width for a + partial activation tile. Safe affine and floating-quantized weight loaders + check row and packed-column bounds before reading weights or scales, then + zero invalid lanes. This prevents finite tails from reading the next row, + including a following NaN row. Exact Python regressions cover affine, + MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + Aligned dispatch and accumulation precision remain unchanged. + globs: + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official v0.32.2 by applying upstream's changes rather than merging them, so `git` sees them as - fork commits even though every file below is byte-identical to upstream `v0.32.2` + fork commits even though the imported content matches upstream `v0.32.2` (CUDA backend, CPU SIMD, kernels, Python bindings and tests, repository CI and templates, `AGENTS.md` / `CLAUDE.md`, docs). Listed here so the page does not credit Layr-Labs with upstream's changes; the section disappears once the fork rebases onto - an upstream commit at or past v0.32.2. + an upstream commit at or past v0.32.2. Later fork changes to these paths + are described in their own sections, including quantized NAX tile bounds. globs: - ".pre-commit-config.yaml" - "AGENTS.md" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index c7f9f8fcc7..04f8262b3a 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -149,14 +149,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -165,10 +158,18 @@ struct QuantizedBlockLoader { int k = 0; for (int i = 0; i < n_steps_per_read; i++) { - T scale = dequantize_scale(scales[i]); + const bool scale_in_bounds = (bj + k) * pack_factor < src_tile_dim.x; + T scale = + scale_in_bounds ? dequantize_scale(scales[i]) : T(0); for (int j = 0; j < n_reads_per_scale; j++) { - dequantize( - src[k * bytes_per_pack], scale, dst + k * pack_factor); + if ((bj + k) * pack_factor < src_tile_dim.x) { + dequantize( + src[k * bytes_per_pack], scale, dst + k * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[k * pack_factor + p] = T(0); + } + } k++; } } @@ -954,7 +955,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index bf90bb84fa..68f0ee2dd5 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -653,14 +653,7 @@ struct QuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -670,11 +663,17 @@ struct QuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -793,14 +792,7 @@ struct QuantizedBlockLoader< return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -810,11 +802,17 @@ struct QuantizedBlockLoader< T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } @@ -1634,7 +1632,7 @@ template < volatile int compiler_barrier; - const short psk = min(int(SK), max(0, (BK - kk1))); + const short psk = min(int(SK), max(0, (k_remain - kk1))); Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); if constexpr (transpose) { diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 461175f013..f0edfa7455 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1600,6 +1600,68 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y4, atol=tol)) @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") + @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") + def test_gather_qmm_sorted_partial_tiles(self): + # Exact sums expose reading a following row as reduction-tile padding. + counts = [17, 3, 31, 14] + indices = [expert for expert, count in enumerate(counts) for _ in range(count)] + rhs = mx.array(indices, dtype=mx.uint32) + experts = [0.25, 0.5, 1.0, 2.0] + for mode, dtype, k, n in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.float16, mx.bfloat16], + [32, 64, 96, 128], + [32, 96], + ): + with self.subTest(mode=mode, dtype=dtype, k=k, n=n): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 scales are 1/4, 1/2, 1, 2. + wq = mx.full((4, n, k // 8), 0x22222222, dtype=mx.uint32) + scales = mx.broadcast_to( + mx.array([40, 48, 56, 64], dtype=mx.uint8)[:, None, None], + (4, n, k // 16), + ) + packed = (wq, scales) + else: + weights = mx.broadcast_to( + mx.array(experts, dtype=dtype)[:, None, None], (4, n, k) + ) + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + for poison in [False, True]: + rows = [ + float("nan") if poison and i % 2 else float(i % 3 + 1) + for i in range(len(indices)) + ] + x = mx.broadcast_to( + mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) + ) + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=rhs, + transpose=True, + group_size=group_size, + bits=bits, + mode=mode, + sorted_indices=True, + ) + expected = mx.array( + [ + rows[row] * k * experts[expert] + for row, expert in enumerate(indices) + ], + dtype=dtype, + )[:, None, None] + self.assertEqual(actual.shape, (len(indices), 1, n)) + equal = (actual == expected) | ( + mx.isnan(actual) & mx.isnan(expected) + ) + self.assertTrue(mx.all(equal).item(), f"poison={poison}") + def test_gather_qmm_sorted_sliced_weight(self): E, R, D, N = 8, 64, 256, 64 dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 From 6beeabd8373ccdbda8e8edc3e11cb4ab593cca68 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:42:26 -0700 Subject: [PATCH 03/12] test(metal): exercise contiguous sorted quantized activation tiles (cherry picked from commit 65eb14fa3f64a56c9a807004b5af1b5f93f0c13d) --- python/tests/test_quantized.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index f0edfa7455..e5c81c3995 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1640,7 +1640,7 @@ def test_gather_qmm_sorted_partial_tiles(self): mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) ) actual = mx.gather_qmm( - x, + mx.contiguous(x), *packed, rhs_indices=rhs, transpose=True, From e3799f2325ee8d16772ae1657a47613a59890dca Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:58:51 -0700 Subject: [PATCH 04/12] Give floating-point NAX loaders a distinct Metal symbol (cherry picked from commit f7bbf7d73b1c8779ca0c58cf338027a48d877454) --- fork.yaml | 5 ++++- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/fork.yaml b/fork.yaml index eebcaa1509..d9bbd94138 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,7 +169,7 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" - - title: "Quantized NAX partial-tile bounds" + - title: "Quantized NAX tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders @@ -177,6 +177,9 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + The floating-point NAX loader has a distinct type name: its layout + differs from the non-NAX loader, and sharing a name corrupts MXFP4 + results when the offline Metal linker combines both translation units. Aligned dispatch and accumulation precision remain unchanged. globs: - "mlx/backend/metal/kernels/quantized_nax.h" diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 04f8262b3a..f4db25db46 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -79,7 +79,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct FPQuantizedNAXBlockLoader { MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; @@ -107,7 +107,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedNAXBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -222,7 +222,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); // Instantiate Loader - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, BN, BK, @@ -366,7 +366,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< T, BK, BN, @@ -815,7 +815,7 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, transpose ? BN : BK, transpose ? BK : BN, From d02ac7778c9d8137b30989eeba0e018de46c894c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:06:28 -0700 Subject: [PATCH 05/12] Separate incompatible quantized Metal loader implementations (cherry picked from commit 1fb86d3fab639d9ba0e1d08a5ceb91423b416b78) --- fork.yaml | 10 ++++-- mlx/backend/metal/kernels/fp_quantized.h | 32 ++++++++--------- mlx/backend/metal/kernels/fp_quantized_nax.h | 10 +++--- mlx/backend/metal/kernels/quantized.h | 38 ++++++++++---------- mlx/backend/metal/kernels/quantized_nax.h | 30 ++++++++-------- 5 files changed, 62 insertions(+), 58 deletions(-) diff --git a/fork.yaml b/fork.yaml index d9bbd94138..ebc7bb8a81 100644 --- a/fork.yaml +++ b/fork.yaml @@ -177,12 +177,16 @@ def: zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. - The floating-point NAX loader has a distinct type name: its layout - differs from the non-NAX loader, and sharing a name corrupts MXFP4 - results when the offline Metal linker combines both translation units. + Each affine/floating-point, legacy/NAX loader has a distinct type name. + Their layouts or bodies differ; sharing a name corrupts MXFP4 results + when the offline Metal linker combines the translation units. The + incompatible affine/FP pack-factor helpers and legacy/NAX vector loaders + also use distinct names. Aligned dispatch and accumulation precision remain unchanged. globs: + - "mlx/backend/metal/kernels/quantized.h" - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index e6c6a1de65..579ddf95ac 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -155,8 +155,8 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); +struct FPQuantizedBlockLoader { + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -181,7 +181,7 @@ struct QuantizedBlockLoader { const device uint8_t* src; const device uint8_t* scales; - QuantizedBlockLoader( + FPQuantizedBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -272,7 +272,7 @@ METAL_FUNC void fp_qmv_quad_impl( uint quad_gid [[quadgroup_index_in_threadgroup]], uint quad_lid [[thread_index_in_quadgroup]]) { constexpr int quads_per_simd = SIMD_SIZE / QUAD_SIZE; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int values_per_thread = D / QUAD_SIZE; constexpr int steps_per_thread = values_per_thread < group_size ? 1 : values_per_thread / group_size; @@ -342,7 +342,7 @@ METAL_FUNC void fp_qmv_fast_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int packs_per_thread = 2; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -430,7 +430,7 @@ METAL_FUNC void fp_qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -590,7 +590,7 @@ METAL_FUNC void fp_qmv_wide_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = SIMD_SIZE / k_lanes; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int nf4 = group_size / 4; // float4 lanes per quant group @@ -705,7 +705,7 @@ METAL_FUNC void fp_qvm_impl( uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = group_size / pack_factor; @@ -831,7 +831,7 @@ METAL_FUNC void fp_qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -841,7 +841,7 @@ METAL_FUNC void fp_qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BN, BK, @@ -955,7 +955,7 @@ METAL_FUNC void fp_qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -966,7 +966,7 @@ METAL_FUNC void fp_qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BK, BN, @@ -1894,7 +1894,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BN * BK_padded]; @@ -2011,7 +2011,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2030,7 +2030,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index f4db25db46..45e1bfebd3 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; } @@ -80,7 +80,7 @@ template < short group_size, short bits> struct FPQuantizedNAXBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -216,7 +216,7 @@ METAL_FUNC void fp_qmm_t_impl( (void)lid; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); @@ -361,7 +361,7 @@ METAL_FUNC void fp_qmm_n_impl( (void)lid; (void)M; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -810,7 +810,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype)); diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index 7b6f36eee1..d5a2953b32 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -15,7 +15,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -577,7 +577,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -589,7 +589,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -610,7 +610,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -769,7 +769,7 @@ METAL_FUNC void qmv_fast_impl( constexpr int packs_per_thread = bits == 2 ? 1 : 2; constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -836,7 +836,7 @@ METAL_FUNC void qmv_impl( constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -1094,7 +1094,7 @@ METAL_FUNC void qvm_impl( uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int tn = 32 / pack_factor; @@ -1220,7 +1220,7 @@ METAL_FUNC void qmm_t_expert_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1230,7 +1230,7 @@ METAL_FUNC void qmm_t_expert_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1348,7 +1348,7 @@ METAL_FUNC void qmm_t_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1358,7 +1358,7 @@ METAL_FUNC void qmm_t_impl( BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1474,7 +1474,7 @@ METAL_FUNC void qmm_n_impl( constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1485,7 +1485,7 @@ METAL_FUNC void qmm_n_impl( BlockMMA; using loader_x_t = mlx::steel:: BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BK, BN, @@ -2118,7 +2118,7 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); threadgroup T Xs[BM * BK_padded]; @@ -2713,7 +2713,7 @@ template < return; } - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = BK + 16 / sizeof(T); threadgroup T Xs[BM * BK_padded]; @@ -2798,7 +2798,7 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2817,7 +2817,7 @@ template < transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, @@ -2935,7 +2935,7 @@ template constexpr float eps = 1e-7; constexpr int simd_size = 32; constexpr float n_bins = (1 << bits) - 1; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int values_per_reduce = group_size / simd_size; constexpr int writes_per_reduce = pack_factor / values_per_reduce; @@ -3037,7 +3037,7 @@ template device T* out [[buffer(3)]], uint2 index [[thread_position_in_grid]], uint2 grid_dim [[threads_per_grid]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); size_t offset = index.x + grid_dim.x * size_t(index.y); diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 68f0ee2dd5..60893f0f0e 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4; template -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); } @@ -29,7 +29,7 @@ inline constexpr short get_bytes_per_pack() { } template -inline U load_vector(const device T* x, thread U* x_thread) { +inline U nax_load_vector(const device T* x, thread U* x_thread) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -108,7 +108,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { } template -inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { +inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -579,7 +579,7 @@ template < short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedNAXBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -591,7 +591,7 @@ struct QuantizedBlockLoader { bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -612,7 +612,7 @@ struct QuantizedBlockLoader { const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -706,7 +706,7 @@ template < short reduction_dim, short tgp_size, short bits> -struct QuantizedBlockLoader< +struct AffineQuantizedNAXBlockLoader< T, BROWS, BCOLS, @@ -725,7 +725,7 @@ struct QuantizedBlockLoader< bits == 8, "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); - MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -751,7 +751,7 @@ struct QuantizedBlockLoader< const device T* scales; const device T* biases; - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -959,12 +959,12 @@ METAL_FUNC void qmm_t_nax_tgp_impl( (void)lid; - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BN, BK, @@ -1103,12 +1103,12 @@ METAL_FUNC void qmm_n_nax_tgp_impl( static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BK, BN, @@ -1484,12 +1484,12 @@ template < uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor(); + constexpr int pack_factor = get_affine_pack_factor(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, From 9266fda0b38aae916f06e394ae5b551b141bfb2b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:49:37 -0700 Subject: [PATCH 06/12] Fix legacy quantized partial-tile bounds (cherry picked from commit adbc349ba623be417993ec083afbb11d07ec42a9) --- fork.yaml | 5 +++-- mlx/backend/metal/kernels/fp_quantized.h | 19 +++++++++--------- mlx/backend/metal/kernels/quantized.h | 25 ++++++++++++------------ 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/fork.yaml b/fork.yaml index ebc7bb8a81..48e89c6b01 100644 --- a/fork.yaml +++ b/fork.yaml @@ -169,11 +169,12 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" - - title: "Quantized NAX tile bounds and distinct loader symbols" + - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders - check row and packed-column bounds before reading weights or scales, then + check row and packed-column bounds on both legacy and NAX paths before + reading weights or scales, then zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index 579ddf95ac..35dc88961f 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -221,14 +221,7 @@ struct FPQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -237,8 +230,14 @@ struct FPQuantizedBlockLoader { T scale = dequantize_scale(*scales); for (int i = 0; i < n_reads; i++) { - dequantize( - src[i * bytes_per_pack], scale, dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + src[i * bytes_per_pack], scale, dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index d5a2953b32..ad347e113f 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -651,14 +651,7 @@ struct AffineQuantizedBlockLoader { return; } - if (reduction_dim == 1 && bi >= src_tile_dim.x) { - for (int i = 0; i < n_reads * pack_factor; i++) { - dst[i] = T(0); - } - return; - } - - if (reduction_dim == 0 && bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -668,11 +661,17 @@ struct AffineQuantizedBlockLoader { T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } } From 2a0c9bbb72bc801773fa4b512b55ca2962361f42 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:22:02 -0700 Subject: [PATCH 07/12] Enforce optional Metal backing caps and preserve CPU quantized sums (cherry picked from commit 9e22e1998a3b6f7f6f4ad58dc2038ecf9f4d0cb9) --- fork.yaml | 21 + mlx/backend/common/process_allocation_cap.h | 192 +++++++ mlx/backend/cpu/quantized.cpp | 18 +- mlx/backend/cuda/allocator.cpp | 9 + mlx/backend/metal/allocator.cpp | 237 ++++++++- mlx/backend/metal/allocator.h | 10 + mlx/backend/metal/resident.cpp | 16 +- mlx/backend/no_gpu/allocator.cpp | 9 + mlx/memory.h | 6 + python/tests/test_quantized.py | 74 +++ tests/allocator_tests.cpp | 2 +- tests/standalone/process_allocation_cap.cpp | 204 ++++++++ .../process_allocation_cap_metal.cpp | 494 ++++++++++++++++++ 13 files changed, 1274 insertions(+), 18 deletions(-) create mode 100644 mlx/backend/common/process_allocation_cap.h create mode 100644 tests/standalone/process_allocation_cap.cpp create mode 100644 tests/standalone/process_allocation_cap_metal.cpp diff --git a/fork.yaml b/fork.yaml index 48e89c6b01..6c2053ae3c 100644 --- a/fork.yaml +++ b/fork.yaml @@ -98,12 +98,22 @@ def: overflow-checked) cache-reuse limit shared with `BufferCache`. Metal, CPU and CUDA allocators implement the same interface; the allocator's own behaviour stays the authority. These describe allocator accounting, not process RSS. (PR #15) + The public process-allocation cap API adds install-once Metal backing enforcement. + Reservations include pending allocations and the fixed heap. Owned page-aligned VM + regions use Metal no-copy buffers; credit returns after the deallocator unmaps them. + Foreign wrappers retain caller ownership. CPU/CUDA reject this optional API; soft + memory limits are unchanged. Residency insertion rolls back failed registration before + callers release buffers, including ordinary uncapped allocations. Standalone CPU and + real-Metal tests cover delayed release, churn, and injected construction failures. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" + - "mlx/backend/common/process_allocation_cap.h" + - "tests/standalone/process_allocation_cap*.cpp" - "mlx/backend/common/buffer_cache.h" - "mlx/backend/metal/allocator.h" - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/metal/resident.cpp" - "mlx/backend/cuda/allocator.h" - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" @@ -190,6 +200,17 @@ def: - "mlx/backend/metal/kernels/fp_quantized.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" - "python/tests/test_quantized.py" + - title: "CPU quantized accumulation precision" + description: | + Scalar affine, MXFP4, MXFP8 and NVFP4 matrix products accumulate in FP32 + and convert once when writing each output. Both matrix orientations and + the FP group sum preserve partial sums instead of rounding every addition + to BF16 or FP16. Exact CPU regressions compare constant products with + dequantized matmul, including sorted and unsorted gathered affine paths. + Quantization, packing, indexing and Metal kernels remain unchanged. + globs: + - "mlx/backend/cpu/quantized.cpp" + - "python/tests/test_quantized.py" - title: "Upstream v0.32.2 sync carried in PR #10" description: | **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official diff --git a/mlx/backend/common/process_allocation_cap.h b/mlx/backend/common/process_allocation_cap.h new file mode 100644 index 0000000000..d92723b73e --- /dev/null +++ b/mlx/backend/common/process_allocation_cap.h @@ -0,0 +1,192 @@ +// Copyright © 2026 Eigen Labs. +#pragma once + +#include +#include +#include +#include +#include + +namespace mlx::core::allocator { + +struct ProcessAllocationCapSnapshot { + bool installed{false}; + size_t limit_bytes{0}; + size_t heap_bytes{0}; + size_t live_bytes{0}; + size_t cached_bytes{0}; + size_t pending_bytes{0}; + size_t unreclaimed_bytes{0}; + size_t charged_bytes{0}; + size_t peak_bytes{0}; +}; + +// Reference release alone cannot refund backing credit. +class ProcessAllocationCap { + public: + void install(size_t limit, size_t heap) { + std::lock_guard lock(mutex_); + if (state_.installed || !limit || heap > limit) { + throw std::invalid_argument("allocation cap install refused"); + } + state_.installed = true; + state_.limit_bytes = limit; + state_.heap_bytes = heap; + state_.charged_bytes = state_.peak_bytes = heap; + } + + void reserve(size_t bytes) { + std::lock_guard lock(mutex_); + if (!state_.installed || + bytes > state_.limit_bytes - state_.charged_bytes) { + throw std::runtime_error("native allocation cap exceeded"); + } + state_.pending_bytes += bytes; + state_.charged_bytes += bytes; + if (state_.charged_bytes > state_.peak_bytes) { + state_.peak_bytes = state_.charged_bytes; + } + } + + // Only a reservation for which no backing was acquired can be rolled back. + void failed_before_acquisition(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.pending_bytes, bytes); + state_.pending_bytes -= bytes; + state_.charged_bytes -= bytes; + } + void acquired(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.pending_bytes, state_.live_bytes, bytes); + } + void cache(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.live_bytes, state_.cached_bytes, bytes); + } + void reuse(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.cached_bytes, state_.live_bytes, bytes); + } + void relinquish(size_t bytes, bool cached = false) { + std::lock_guard lock(mutex_); + transfer( + cached ? state_.cached_bytes : state_.live_bytes, + state_.unreclaimed_bytes, + bytes); + } + void destroyed(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.unreclaimed_bytes, bytes); + state_.unreclaimed_bytes -= bytes; + state_.charged_bytes -= bytes; + } + ProcessAllocationCapSnapshot snapshot() const { + std::lock_guard lock(mutex_); + return state_; + } + + private: + static void require(size_t available, size_t bytes) { + if (bytes > available) { + throw std::logic_error("allocation cap ledger mismatch"); + } + } + static void transfer(size_t& from, size_t& to, size_t bytes) { + require(from, bytes); + if (bytes > std::numeric_limits::max() - to) { + throw std::overflow_error("allocation cap ledger overflow"); + } + from -= bytes; + to += bytes; + } + mutable std::mutex mutex_; + ProcessAllocationCapSnapshot state_; +}; + +// Shared by allocator bookkeeping and the Metal deallocator block. The callback +// never takes the allocator mutex. Release must finish before credit is +// returned. +class ProcessBackingLease { + public: + using Release = bool (*)(void*, size_t); + ProcessBackingLease(std::shared_ptr cap, size_t bytes) + : cap_(std::move(cap)), bytes_(bytes) { + cap_->reserve(bytes_); + } + ~ProcessBackingLease() { + finish(); + } + void attach(void* pointer, Release release) noexcept { + std::lock_guard lock(mutex_); + pointer_ = pointer; + release_ = release; + } + void acquired() { + std::lock_guard lock(mutex_); + if (state_ != State::pending) { + throw std::logic_error("backing already retired"); + } + cap_->acquired(bytes_); + state_ = State::live; + } + void cache() { + std::lock_guard lock(mutex_); + if (state_ != State::live) { + throw std::logic_error("backing cache mismatch"); + } + cap_->cache(bytes_); + state_ = State::cached; + } + void reuse() { + std::lock_guard lock(mutex_); + if (state_ != State::cached) { + throw std::logic_error("backing reuse mismatch"); + } + cap_->reuse(bytes_); + state_ = State::live; + } + void retire() { + std::lock_guard lock(mutex_); + if (state_ != State::live && state_ != State::cached) { + throw std::logic_error("backing retirement mismatch"); + } + cap_->relinquish(bytes_, state_ == State::cached); + state_ = State::retired; + } + void finish() noexcept { + std::lock_guard lock(mutex_); + if (state_ == State::finished) { + return; + } + // Foreign wrappers have no release function: their caller retains + // ownership. + const bool released = !release_ || release_(pointer_, bytes_); + if (state_ == State::pending && released) { + cap_->failed_before_acquisition(bytes_); + } else { + if (state_ == State::pending) { + cap_->acquired(bytes_); + } + if (state_ != State::retired) { + cap_->relinquish(bytes_, state_ == State::cached); + } + if (released) { + cap_->destroyed(bytes_); + } + } + // A failed backing release is permanently charged; it cannot be retried + // after ownership has been relinquished to a deallocator callback. + state_ = State::finished; + } + + private: + enum class State { pending, live, cached, retired, finished }; + std::shared_ptr cap_; + size_t bytes_; + void* pointer_{nullptr}; + Release release_{nullptr}; + State state_{State::pending}; + std::mutex mutex_; +}; + +} // namespace mlx::core::allocator diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 15e00cd913..30b11c87d6 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -108,15 +108,16 @@ void _qmm( constexpr int bytes_per_pack = get_bytes_per_pack(bits); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const T* scales_local = scales; const T* biases_local = biases; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -147,6 +148,7 @@ void _qmm( } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -174,7 +176,7 @@ void _qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = *scales_local++; T bias = *biases_local++; @@ -458,14 +460,15 @@ void fp_qmm( constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; + std::vector sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const uint8_t* scales_local = scales; - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0); for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++; for (int n = 0; n < N; n += group_size) { @@ -484,6 +487,7 @@ void fp_qmm( } } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -506,11 +510,11 @@ void fp_qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = dequantize_scale(*scales_local++); - T gsum = 0; + float gsum = 0; for (int kw = 0; kw < packs_in_group; kw++) { if constexpr (bits == 4) { gsum += (*x_local++) * static_cast(FP4_LUT[w_local[0] & 0xf]); diff --git a/mlx/backend/cuda/allocator.cpp b/mlx/backend/cuda/allocator.cpp index e483317845..b29cc3a2b3 100644 --- a/mlx/backend/cuda/allocator.cpp +++ b/mlx/backend/cuda/allocator.cpp @@ -440,6 +440,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return cu::allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return cu::allocator().set_memory_limit(limit); } diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9b80840a18..97fc684aca 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -6,6 +6,7 @@ #include "mlx/memory.h" #include +#include #include #include #include @@ -52,6 +53,7 @@ MetalAllocator::MetalAllocator(Device& d) vm_page_size, [](MTL::Buffer* buf) { return buf->length(); }, [this](MTL::Buffer* buf) { + relinquish_capped(buf, true); if (!buf->heap()) { residency_sets_.erase(buf); } @@ -136,6 +138,125 @@ size_t MetalAllocator::set_wired_limit(size_t limit) { return limit; }; +void MetalAllocator::install_process_allocation_cap(size_t bytes) { + std::unique_lock lock(mutex_); + if (buffer_allocation_attempted_) { + throw std::invalid_argument( + "allocation cap requires a pristine buffer allocator"); + } + cap_->install(bytes, heap_ ? heap_->size() : 0); + cap_installed_ = true; +} + +ProcessAllocationCapSnapshot +MetalAllocator::get_process_allocation_cap_snapshot() { + return cap_->snapshot(); +} + +void MetalAllocator::relinquish_capped(MTL::Buffer* buffer, bool cached) { + if (!cap_installed_) { + return; + } + auto entry = capped_buffers_.find(buffer); + if (entry == capped_buffers_.end()) { + throw std::logic_error("untracked capped buffer"); + } + if (entry->second) { + entry->second->retire(); + } + capped_buffers_.erase(entry); +} + +Buffer MetalAllocator::malloc_capped( + size_t size, + std::unique_lock& lock) { + if (auto* cached = buffer_cache_.reuse_from_cache(size)) { + if (auto lease = capped_buffers_.at(cached)) { + lease->reuse(); + } + active_memory_ += cached->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{cached}; + } + // Trim idle backing before refusing a new shape. Actual callbacks, not cache + // eviction, return credit; externally retained buffers remain charged. + auto snapshot = cap_->snapshot(); + const auto charge = allocator::round_allocation_size(size, vm_page_size); + if (charge > device_->maxBufferLength()) { + throw std::invalid_argument( + "page-aligned backing exceeds Metal buffer limit"); + } + if (charge > snapshot.limit_bytes - snapshot.charged_bytes || + num_resources_ >= resource_limit_ || + buffer_cache_.cache_size() > max_pool_size_) { + num_resources_ -= buffer_cache_.clear(); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + MTL::Buffer* buffer = nullptr; + std::shared_ptr lease; + if (size < small_size_ && heap_) { + buffer = heap_->newBuffer(size, resource_options); + } + if (!buffer) { + // Reserve before releasing allocator lock, including in-flight allocations. + lease = std::make_shared(cap_, charge); + ++num_resources_; + lock.unlock(); + try { + void* pages = mmap( + nullptr, + charge, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + if (pages == MAP_FAILED) { + throw std::bad_alloc(); + } + lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + buffer = device_->newBuffer( + pages, charge, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + if (!buffer) { + throw std::runtime_error("Metal no-copy allocation failed"); + } + lease->acquired(); + } catch (...) { + if (buffer) { + buffer->release(); + } else { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); + } else { + ++num_resources_; + } + try { + capped_buffers_.emplace(buffer, lease); + if (!buffer->heap()) { + residency_sets_.insert(buffer); + } + } catch (...) { + capped_buffers_.erase(buffer); + if (lease) { + lease->retire(); + } + --num_resources_; + buffer->release(); + throw; + } + active_memory_ += buffer->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{buffer}; +} + Buffer MetalAllocator::malloc(size_t size) { // Metal doesn't like empty buffers if (size == 0) { @@ -159,6 +280,10 @@ Buffer MetalAllocator::malloc(size_t size) { // Try the cache std::unique_lock lk(mutex_); + buffer_allocation_attempted_ = true; + if (cap_installed_) { + return malloc_capped(size, lk); + } MTL::Buffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { size_t mem_required = get_active_memory() + get_cache_memory() + size; @@ -211,10 +336,16 @@ Buffer MetalAllocator::malloc(size_t size) { throw std::runtime_error(msg.str()); } lk.lock(); - num_resources_++; - if (!buf->heap()) { - residency_sets_.insert(buf); + try { + if (!buf->heap()) { + residency_sets_.insert(buf); + } + } catch (...) { + lk.unlock(); + buf->release(); + throw; } + num_resources_++; } active_memory_ += buf->length(); @@ -243,7 +374,13 @@ void MetalAllocator::free(Buffer buffer) { active_memory_ -= buf->length(); if (get_cache_memory() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); + if (cap_installed_) { + if (auto lease = capped_buffers_.at(buf)) { + lease->cache(); + } + } } else { + relinquish_capped(buf, false); num_resources_--; if (!buf->heap()) { residency_sets_.erase(buf); @@ -259,15 +396,91 @@ size_t MetalAllocator::size(Buffer buffer) const { } Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { - auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + std::unique_lock lock(mutex_); + buffer_allocation_attempted_ = true; + if (!cap_installed_) { + lock.unlock(); + auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + if (!buf) { + return Buffer{nullptr}; + } + lock.lock(); + try { + residency_sets_.insert(buf); + } catch (...) { + lock.unlock(); + buf->release(); + throw; + } + active_memory_ += buf->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + num_resources_++; + return Buffer{static_cast(buf)}; + } + std::shared_ptr lease; + if (cap_installed_) { + if (!size || size % vm_page_size || + reinterpret_cast(ptr) % vm_page_size || !ptr || + size > device_->maxBufferLength()) { + throw std::invalid_argument( + "capped foreign backing must be page aligned"); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + lease = std::make_shared(cap_, size); + } + ++num_resources_; + lock.unlock(); + MTL::Buffer* buf = nullptr; + try { + if (lease) { + // Charge wrapper lifetime; never free or assume ownership of caller + // pages. + buf = device_->newBuffer( + ptr, size, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + } else { + buf = device_->newBuffer(ptr, size, resource_options, nullptr); + } + if (buf && lease) { + lease->acquired(); + } + } catch (...) { + if (buf) { + buf->release(); + } else if (lease) { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); if (!buf) { - return Buffer{nullptr}; + if (lease) { + lease->finish(); + } + --num_resources_; + throw std::runtime_error("capped Metal no-copy wrapper allocation failed"); + } + try { + if (lease) { + capped_buffers_.emplace(buf, lease); + } + residency_sets_.insert(buf); + } catch (...) { + if (lease) { + capped_buffers_.erase(buf); + lease->retire(); + } + --num_resources_; + buf->release(); + throw; } - std::unique_lock lk(mutex_); - residency_sets_.insert(buf); active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); - num_resources_++; return Buffer{static_cast(buf)}; } @@ -278,6 +491,7 @@ void MetalAllocator::release(Buffer buffer) { } std::unique_lock lk(mutex_); active_memory_ -= buf->length(); + relinquish_capped(buf, false); num_resources_--; residency_sets_.erase(buf); lk.unlock(); @@ -308,6 +522,13 @@ size_t get_allocation_size_upper_bound(size_t size) { return result; } +void install_process_allocation_cap(size_t bytes) { + metal::allocator().install_process_allocation_cap(bytes); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + return metal::allocator().get_process_allocation_cap_snapshot(); +} + size_t set_cache_limit(size_t limit) { return metal::allocator().set_cache_limit(limit); } diff --git a/mlx/backend/metal/allocator.h b/mlx/backend/metal/allocator.h index 623055e92c..b184944224 100644 --- a/mlx/backend/metal/allocator.h +++ b/mlx/backend/metal/allocator.h @@ -24,6 +24,8 @@ class MetalAllocator : public allocator::Allocator { virtual Buffer make_buffer(void* ptr, size_t size) override; virtual void release(Buffer buffer) override; + void install_process_allocation_cap(size_t bytes); + ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); MemorySnapshot get_memory_snapshot(); size_t get_active_memory() { return active_memory_; @@ -93,6 +95,14 @@ class MetalAllocator : public allocator::Allocator { static constexpr size_t resource_high_water_num_ = 9; static constexpr size_t resource_high_water_den_ = 10; + Buffer malloc_capped(size_t size, std::unique_lock& lock); + void relinquish_capped(MTL::Buffer* buffer, bool cached); + std::shared_ptr cap_{ + std::make_shared()}; + bool cap_installed_{false}; + bool buffer_allocation_attempted_{false}; + std::map> + capped_buffers_; std::mutex mutex_; }; diff --git a/mlx/backend/metal/resident.cpp b/mlx/backend/metal/resident.cpp index 2436993637..fede178a5a 100644 --- a/mlx/backend/metal/resident.cpp +++ b/mlx/backend/metal/resident.cpp @@ -150,8 +150,20 @@ void ResidencySets::insert(MTL::Allocation* buf) { if (total_wired_ + bytes > capacity_) { return; } - uint32_t idx = add_to_set_locked(buf, it->second); - sets_[idx].set->commit(); + try { + uint32_t idx = add_to_set_locked(buf, it->second); + sets_[idx].set->commit(); + } catch (...) { + // Registration must not leave a pointer to a buffer the caller will + // release. + if (it->second.set_id != kNoSet) { + const uint32_t idx = it->second.set_id; + remove_from_set_locked(buf, it->second); + sets_[idx].set->commit(); + } + buf_to_set_.erase(it); + throw; + } } void ResidencySets::erase(MTL::Allocation* buf) { diff --git a/mlx/backend/no_gpu/allocator.cpp b/mlx/backend/no_gpu/allocator.cpp index f766707bce..06f9bcd79d 100644 --- a/mlx/backend/no_gpu/allocator.cpp +++ b/mlx/backend/no_gpu/allocator.cpp @@ -213,6 +213,15 @@ size_t get_peak_memory() { void reset_peak_memory() { return allocator::common_allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return allocator::common_allocator().set_memory_limit(limit); } diff --git a/mlx/memory.h b/mlx/memory.h index f2e7bf225f..d36201b51a 100644 --- a/mlx/memory.h +++ b/mlx/memory.h @@ -7,9 +7,15 @@ #include #include "mlx/api.h" +#include "mlx/backend/common/process_allocation_cap.h" namespace mlx::core { +using ProcessAllocationCapSnapshot = allocator::ProcessAllocationCapSnapshot; +// One-way, pristine-allocator installation. Not a whole-process/host limit. +MLX_API void install_process_allocation_cap(size_t bytes); +MLX_API ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); + struct MemorySnapshot { size_t active_memory; size_t cache_memory; diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index e5c81c3995..d860196acf 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -1599,6 +1599,80 @@ def scatter_unsort(x, inv_order, shape=None): self.assertTrue(mx.allclose(y1, y3, atol=tol)) self.assertTrue(mx.allclose(y1, y4, atol=tol)) + def test_cpu_quantized_accumulation_modes_and_orientations(self): + with mx.stream(mx.cpu): + for mode, dtype, transpose, k in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.bfloat16, mx.float16, mx.float32], + [False, True], + [96, 3072], + ): + with self.subTest(mode=mode, dtype=dtype, transpose=transpose, k=k): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + x = mx.full((1, k), 3, dtype=dtype) + weights = mx.full((32, k) if transpose else (k, 32), 2, dtype=dtype) + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 code 64 is exactly 2. + packed = ( + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 8), + 0x22222222, + dtype=mx.uint32, + ), + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 16), + 64, + dtype=mx.uint8, + ), + ) + else: + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + dequantized = mx.dequantize( + *packed, group_size=group_size, bits=bits, mode=mode + ) + reference = x @ (dequantized.T if transpose else dequantized) + expected = mx.full((1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + actual = mx.quantized_matmul( + x, + *packed, + transpose=transpose, + group_size=group_size, + bits=bits, + mode=mode, + ) + self.assertTrue(mx.array_equal(actual, expected)) + + def test_affine_qmm_cpu_low_precision_accumulation(self): + with mx.stream(mx.cpu): + for dtype, bits, k in product( + [mx.bfloat16, mx.float16, mx.float32], [3, 4, 6], [96, 128] + ): + with self.subTest(dtype=dtype, bits=bits, k=k): + x = mx.full((1, 1, k), 3, dtype=dtype) + weights = mx.full((1, 32, k), 2, dtype=dtype) + packed = mx.quantize(weights, group_size=32, bits=bits) + reference = x @ mx.swapaxes( + mx.dequantize(*packed, group_size=32, bits=bits), -1, -2 + ) + expected = mx.full((1, 1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + for sorted_indices in [False, True]: + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=mx.array([0], dtype=mx.uint32), + group_size=32, + bits=bits, + sorted_indices=sorted_indices, + ) + self.assertTrue(mx.array_equal(actual, expected)) + actual = mx.quantized_matmul(x, *packed, group_size=32, bits=bits) + self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") def test_gather_qmm_sorted_partial_tiles(self): diff --git a/tests/allocator_tests.cpp b/tests/allocator_tests.cpp index d5ff60525b..bab64689bc 100644 --- a/tests/allocator_tests.cpp +++ b/tests/allocator_tests.cpp @@ -182,7 +182,7 @@ TEST_CASE("test memory snapshot does not wait for stream work") { auto status = snapshot.wait_for(std::chrono::seconds(1)); release.set_value(); synchronize(stream); - snapshot.get(); + (void)snapshot.get(); CHECK_EQ(status, std::future_status::ready); } diff --git a/tests/standalone/process_allocation_cap.cpp b/tests/standalone/process_allocation_cap.cpp new file mode 100644 index 0000000000..1500baac9d --- /dev/null +++ b/tests/standalone/process_allocation_cap.cpp @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. +#include "mlx/backend/common/process_allocation_cap.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/backend/common/allocation_footprint.h" + +using namespace mlx::core::allocator; +using Cap = ProcessAllocationCap; +using Lease = ProcessBackingLease; + +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + assert(refused); +} +void invariant(const Cap& cap) { + auto s = cap.snapshot(); + assert( + s.charged_bytes == + s.heap_bytes + s.live_bytes + s.cached_bytes + s.pending_bytes + + s.unreclaimed_bytes); + assert(s.charged_bytes <= s.peak_bytes && s.peak_bytes <= s.limit_bytes); +} +std::atomic releases{0}; +bool unmap(void* p, size_t n) { + ++releases; + return munmap(p, n) == 0; +} + +using Callback = void (^)(); +Callback retainedCallback(std::shared_ptr lease) { + return Block_copy(^{ + lease->finish(); + }); +} + +int main() { + const size_t page = static_cast(getpagesize()); + { + Cap c; + refuses([&] { c.install(0, 0); }); + refuses([&] { c.install(3, 4); }); + assert(!c.snapshot().installed); + c.install(16, 4); + refuses([&] { c.install(32, 4); }); + c.reserve(12); + refuses([&] { c.reserve(1); }); + c.failed_before_acquisition(12); + assert(c.snapshot().charged_bytes == 4); + invariant(c); + Cap huge; + huge.install(SIZE_MAX, SIZE_MAX - 1); + huge.reserve(1); + refuses([&] { huge.reserve(SIZE_MAX); }); + huge.failed_before_acquisition(1); + invariant(huge); + refuses([&] { round_allocation_size(SIZE_MAX, page); }); + } + { + auto c = std::make_shared(); + c->install(4 * page, page); + // Real VM backing, real copied Blocks ABI; no Metal/device initialization. + for (int i = 0; i < 1000; ++i) { + auto lease = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + lease->attach(p, unmap); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->cache(); + lease->reuse(); + lease->retire(); + lease.reset(); + assert(c->snapshot().unreclaimed_bytes == page); + assert(c->snapshot().charged_bytes == 2 * page); + callback(); + callback(); // defensive idempotence; unmap exactly once + Block_release(callback); + assert(c->snapshot().charged_bytes == page); + invariant(*c); + } + assert( + releases == 1000); // Churn does not accumulate a fake high-water cap. + } + { + auto c = std::make_shared(); + c->install(page, 0); + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + refuses( + [&] { Lease next(c, 1); }); // retained Metal equivalent blocks refund + std::thread completion([&] { callback(); }); + completion.join(); + Block_release(callback); + Lease next(c, page); // delayed completion makes capacity reusable + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + { + Lease failed(c, page); + } // no VM acquired + assert(c->snapshot().charged_bytes == 0); + auto failed = std::make_shared(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + failed->attach(p, unmap); + failed->finish(); // Metal constructor returned nil after VM acquisition + failed.reset(); + assert(c->snapshot().charged_bytes == 0 && releases == 1001); + Lease quarantine(c, page); + quarantine.attach(nullptr, [](void*, size_t) { return false; }); + quarantine.acquired(); + quarantine.retire(); + quarantine.finish(); + assert(c->snapshot().unreclaimed_bytes == page); + refuses([&] { Lease next(c, 1); }); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + // Foreign pages stay caller-owned even after callback and ledger refund. + auto* p = static_cast(mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + assert(p != MAP_FAILED); + p[0] = 42; + { + Lease wrapper(c, page); + wrapper.acquired(); + wrapper.retire(); + wrapper.finish(); + } + assert(p[0] == 42 && c->snapshot().charged_bytes == 0); + assert(munmap(p, page) == 0); + } + { + auto c = std::make_shared(); + c->install(1, 0); + std::atomic arrived{0}, successes{0}; + std::atomic release{false}; + std::vector threads; + for (int i = 0; i < 2; ++i) { + threads.emplace_back([&] { + std::shared_ptr lease; + try { + lease = std::make_shared(c, 1); + ++successes; + } catch (...) { + } + ++arrived; + while (!release) { + std::this_thread::yield(); + } + }); + } + while (arrived != 2) { + std::this_thread::yield(); + } + assert(successes == 1 && c->snapshot().pending_bytes == 1); + release = true; + for (auto& t : threads) { + t.join(); + } + assert(c->snapshot().charged_bytes == 0); + invariant(*c); + } + { + auto c = std::make_shared(); + c->install(page, 0); + std::weak_ptr weak = c; + auto lease = std::make_shared(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + c.reset(); + assert(!weak.expired()); + callback(); + Block_release(callback); + assert(weak.expired()); // callback owns ledger, not an allocator stack + // reference + } + std::cout + << "PASS: install/overflow, 1000 VM churn cycles, delayed copied block, " + "failure rollback/quarantine, foreign ownership, concurrent reserve, ledger lifetime\n"; +} diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp new file mode 100644 index 0000000000..9ebd9340b5 --- /dev/null +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -0,0 +1,494 @@ +// Copyright © 2026 Eigen Labs. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mlx/allocator.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" + +using namespace mlx::core; +namespace a = mlx::core::allocator; +void require(bool value, const char* what) { + if (!value) { + throw std::runtime_error(what); + } +} +template +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + require(refused, "required refusal did not occur"); +} +auto snapshot() { + return get_process_allocation_cap_snapshot(); +} +void settled(size_t expected) { + for (int i = 0; i < 200 && snapshot().charged_bytes != expected; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require( + snapshot().charged_bytes == expected, "callback credit did not settle"); +} + +// Process-local Metal API interception; no production failure switches. +IMP original_no_copy = nullptr; +IMP original_allocate = nullptr; +IMP original_residency = nullptr; +MTL::Buffer* retained_failure_buffer = nullptr; +bool reject_no_copy = false; +MTL::Buffer* intercept_no_copy( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + if (reject_no_copy) { + reject_no_copy = false; + return nullptr; + } + auto fn = reinterpret_cast( + original_no_copy); + auto* b = fn(self, selector, p, n, opts, cleanup); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::Buffer* intercept_allocate( + id self, + SEL selector, + NS::UInteger n, + MTL::ResourceOptions opts) { + auto fn = reinterpret_cast< + MTL::Buffer* (*)(id, SEL, NS::UInteger, MTL::ResourceOptions)>( + original_allocate); + auto* b = fn(self, selector, n, opts); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::ResidencySet* +fail_residency(id, SEL, MTL::ResidencySetDescriptor*, NS::Error**) { + throw std::bad_alloc(); // insert has already added its map entry +} +struct Intercept { + Method method; + IMP previous; + Intercept(MTL::Device* device, const char* selector, IMP replacement) + : method(class_getInstanceMethod( + object_getClass(reinterpret_cast(device)), + sel_registerName(selector))), + previous(nullptr) { + require(method != nullptr, "Metal interception selector missing"); + previous = method_setImplementation(method, replacement); + } + ~Intercept() { + method_setImplementation(method, previous); + } +}; + +struct PendingMetalConstruction { + std::mutex mutex; + std::condition_variable changed; + size_t entered{0}; + bool complete{false}; + std::array retained{nullptr, nullptr}; + IMP original{nullptr}; +}; +PendingMetalConstruction* pending_construction = nullptr; +MTL::Buffer* intercept_pending( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + auto& state = *pending_construction; + auto fn = reinterpret_cast( + state.original); + // Construct real Metal buffers before holding their return to the allocator. + auto* buffer = fn(self, selector, p, n, opts, cleanup); + std::unique_lock lock(state.mutex); + const auto index = state.entered++; + if (index < state.retained.size() && buffer) { + buffer->retain(); + state.retained[index] = buffer; + } + state.changed.notify_all(); + if (index < state.retained.size()) { + state.changed.wait(lock, [&] { return state.complete; }); + } + return buffer; +} +void concurrent_case(size_t page) { + auto& device = metal::device(Device::gpu); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + const auto chunk = (cap - heap) / 2; + require( + chunk % page == 0 && chunk * 2 + heap == cap, + "nonintegral test envelope"); + PendingMetalConstruction state; + pending_construction = &state; + std::array buffers{a::Buffer(nullptr), a::Buffer(nullptr)}; + std::array errors; + bool both_pending = false, contender_refused = false; + ProcessAllocationCapSnapshot pending_snapshot; + size_t actual_bytes = 0; + a::Buffer contender(nullptr); + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_pending)); + state.original = hook.previous; + std::array workers; + for (size_t i = 0; i < workers.size(); ++i) { + workers[i] = std::thread([&, i] { + try { + buffers[i] = a::malloc(chunk); + } catch (...) { + errors[i] = std::current_exception(); + } + }); + } + { + std::unique_lock lock(state.mutex); + both_pending = state.changed.wait_for( + lock, std::chrono::seconds(5), [&] { return state.entered == 2; }); + if (both_pending && state.retained[0] && state.retained[1]) { + actual_bytes = + state.retained[0]->length() + state.retained[1]->length(); + } + } + pending_snapshot = snapshot(); + if (both_pending) { + try { + contender = a::malloc(page); + } catch (const std::exception&) { + contender_refused = true; + } + } + { + std::lock_guard lock(state.mutex); + state.complete = true; + } + state.changed.notify_all(); + for (auto& worker : workers) { + worker.join(); + } + } + pending_construction = nullptr; + require( + both_pending, + "allocator did not allow two real in-flight Metal allocations"); + require(!errors[0] && !errors[1], "real Metal construction failed"); + require(actual_bytes + heap == cap, "unexpected actual Metal backing total"); + require( + pending_snapshot.pending_bytes == 2 * chunk && + pending_snapshot.charged_bytes == cap && + pending_snapshot.live_bytes == 0, + "in-flight Metal backing was not reserved before completion"); + require( + contender_refused && !contender.ptr() && state.entered == 2, + "contender reached Metal despite exhausted pending budget"); + require( + snapshot().peak_bytes == cap && snapshot().pending_bytes == 0 && + snapshot().live_bytes == 2 * chunk, + "pending-to-live transfer changed cap charge"); + for (auto buffer : buffers) { + a::free(buffer); + } + clear_cache(); + require( + snapshot().unreclaimed_bytes == 2 * chunk && + snapshot().charged_bytes == cap, + "allocator release refunded externally retained Metal backing"); + refuses([&] { a::malloc(page); }); + state.retained[0]->release(); + settled(heap + chunk); + auto recovered = a::malloc(chunk); + require( + snapshot().charged_bytes == cap && snapshot().peak_bytes == cap, + "callback recovery failed exact-cap replacement"); + a::free(recovered); + clear_cache(); + settled(heap + chunk); + state.retained[1]->release(); + settled(heap); + require( + snapshot().pending_bytes == 0 && snapshot().unreclaimed_bytes == 0, + "concurrent allocation left stranded charges"); +} +void failure_case(const std::string& mode, size_t page) { + const bool capped = mode.find("ordinary") == std::string::npos; + const bool foreign = mode.find("foreign") != std::string::npos; + auto& device = metal::device(Device::gpu); + auto& sets = device.residency_sets(); + (void)snapshot(); // initialize allocator and its fixed heap + if (capped) { + install_process_allocation_cap(8 << 20); + } + const auto baseline = capped ? snapshot().charged_bytes : 0; + set_cache_limit(0); + if (mode == "nil-foreign") { + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(p != MAP_FAILED, "foreign map failed"); + int deleter_calls = 0; + bool threw = false; + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = hook.previous; + reject_no_copy = true; + try { + array foreign_array( + p, {static_cast(page / sizeof(float))}, float32, [&](void*) { + ++deleter_calls; + }); + } catch (const std::exception&) { + threw = true; + } + } + require(munmap(p, page) == 0, "caller unmap failed"); + require(threw, "nil wrapper silently copied instead of throwing"); + require(deleter_calls == 0, "failed wrapper invoked caller deleter"); + settled(baseline); + return; + } + set_wired_limit(8 << 20); + sets.set_max_bytes_per_set(page); + const auto wired = sets.wired_size(); + const auto resources = get_num_resources(); + const auto active = get_active_memory(); + void* foreign_pages = nullptr; + if (foreign) { + foreign_pages = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(foreign_pages != MAP_FAILED, "foreign map failed"); + } + { + Intercept no_copy( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast(intercept_no_copy)); + original_no_copy = no_copy.previous; + Intercept allocated( + device.mtl_device(), + "newBufferWithLength:options:", + reinterpret_cast(intercept_allocate)); + original_allocate = allocated.previous; + Intercept registration( + device.mtl_device(), + "newResidencySetWithDescriptor:error:", + reinterpret_cast(fail_residency)); + original_residency = registration.previous; + refuses([&] { + if (foreign) { + (void)a::make_buffer(foreign_pages, page); + } else { + (void)a::malloc(page); + } + }); + } + require( + retained_failure_buffer != nullptr, + "failure did not reach allocated buffer"); + // Keep the object alive to diagnose stale registration without dereferencing + // freed memory. On the broken path resize wires this failed allocation. + set_wired_limit((8 << 20) + page); + require( + sets.wired_size() == wired, + "failed insert left a tracked Metal allocation"); + require( + get_num_resources() == resources && get_active_memory() == active, + "failed registration changed allocator counters"); + if (capped) { + require( + snapshot().charged_bytes == baseline + page, + "retained failure refunded early"); + } + require( + retained_failure_buffer->retainCount() == 1, + "allocator leaked failed buffer reference"); + retained_failure_buffer->release(); + retained_failure_buffer = nullptr; + if (capped) { + settled(baseline); + } + if (foreign) { + require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); + } +} +int main(int argc, char** argv) { + try { + require(argc == 2, "one fresh-process case required"); + const std::string mode = argv[1]; + const size_t page = static_cast(getpagesize()); + if (mode == "concurrent") { + concurrent_case(page); + } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { + failure_case(mode, page); + } else if (mode == "late") { + auto b = a::malloc(page); + a::free(b); + clear_cache(); + refuses([] { install_process_allocation_cap(8 << 20); }); + require(!snapshot().installed, "late install mutated state"); + } else { + // The allocator's fixed heap is created when queried, before + // installation. + require(!snapshot().installed, "process already capped"); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + const auto baseline = snapshot(); + const auto heap = baseline.heap_bytes; + require( + heap > 0 && baseline.charged_bytes == heap, + "existing heap not charged"); + require(baseline.limit_bytes == cap, "wrong cap"); + if (mode == "install") { + refuses([&] { install_process_allocation_cap(cap); }); + refuses([&] { install_process_allocation_cap(cap + page); }); + require(snapshot().limit_bytes == cap, "limit changed"); + refuses([] { a::malloc(SIZE_MAX); }); + require( + snapshot().charged_bytes == heap, "overflow leaked reservation"); + auto exact = a::malloc(cap - heap); + require(snapshot().charged_bytes == cap, "exact fill mismatch"); + refuses([&] { a::malloc(page); }); + a::free(exact); + clear_cache(); + settled(heap); + } else if (mode == "retained") { + auto b = a::malloc(cap - heap); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::free(b); + clear_cache(); + require( + snapshot().unreclaimed_bytes == cap - heap, + "release refunded early"); + require(snapshot().charged_bytes == cap, "extra reference lost charge"); + refuses([&] { a::malloc(page); }); + metal->release(); + settled(heap); + auto replacement = a::malloc(cap - heap); + a::free(replacement); + clear_cache(); + settled(heap); + } else if (mode == "churn") { + auto tiny = a::malloc(8); + require( + static_cast(tiny.ptr())->heap() != nullptr, + "fixed heap unused"); + require(snapshot().charged_bytes == heap, "heap double charged"); + a::free(tiny); + clear_cache(); + for (size_t i = 0; i < 1000; ++i) { + const auto size = page * (1 + i % 31); + auto b = a::malloc(size); + const auto bytes = snapshot().charged_bytes; + auto pointer = b.ptr(); + a::free(b); + require( + snapshot().cached_bytes > 0 && snapshot().charged_bytes == bytes, + "cache transfer refunded credit"); + auto reused = a::malloc(size); + require( + reused.ptr() == pointer && snapshot().charged_bytes == bytes, + "cache reuse allocated new backing"); + a::free(reused); + clear_cache(); + settled(heap); + } + require(snapshot().peak_bytes < cap, "churn accumulated backing"); + } else if (mode == "foreign") { + void* p = mmap( + nullptr, + page, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + require(p != MAP_FAILED, "foreign map failed"); + static_cast(p)[0] = 42; + auto b = a::make_buffer(p, page); + require(b.ptr() != nullptr, "foreign wrapper failed"); + auto* metal = static_cast(b.ptr()); + metal->retain(); + a::release(b); + require( + snapshot().charged_bytes == heap + page, + "foreign wrapper refunded early"); + metal->release(); + settled(heap); + require( + static_cast(p)[0] == 42, + "caller pages invalidated"); + refuses([&] { a::make_buffer(static_cast(p) + 1, page); }); + require(munmap(p, page) == 0, "caller unmap failed"); + } else if (mode == "gpu") { + { + // Real native graph roots stay owned through GPU evaluation and + // readback. + auto input = arange(1024, float32, Device::gpu); + auto output = + add(multiply(input, array(2.0f), Device::gpu), + array(3.0f), + Device::gpu); + async_eval(output); + synchronize(default_stream(Device::gpu)); + for (int i = 0; i < 1024; ++i) { + require( + output.data()[i] == i * 2.0f + 3.0f, + "GPU value mismatch"); + } + require(snapshot().live_bytes > 0, "evaluated roots uncharged"); + } + synchronize(default_stream(Device::gpu)); + clear_cache(); + settled(heap); + } else { + throw std::runtime_error("unknown case"); + } + require(snapshot().pending_bytes == 0, "pending reservation leaked"); + require(snapshot().charged_bytes <= cap, "cap exceeded"); + } + std::cout << "PASS " << mode << '\n'; + return 0; + } catch (const std::exception& e) { + std::cerr << "FAIL " << e.what() << '\n'; + return 1; + } +} From 99dc5f4235413e466be89f8ed8ff8a6d6b71de3f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:40:16 -0700 Subject: [PATCH 08/12] Cover page-backed small buffers in detached Metal footprints Keep the allocation bound stable before and after process cap installation. Add real ordinary/capped boundary coverage without changing allocation, ownership, process-cap enforcement or the policy ABI. Document the bound. Implemented and validated with OpenAI Codex. (cherry picked from commit 4d913204912559099eff856cd56efdcc9d305d5f) --- docs/src/usage/unified_memory.rst | 18 +++++++++ fork.yaml | 7 ++++ mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 37 ++++++++++++++++++- 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 57f54bc23b..8541fec358 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -76,3 +76,21 @@ If we time the computation fully on the GPU, we get 2.8 milliseconds. But if we run the computation with ``d1=mx.gpu`` and ``d2=mx.cpu``, then the time is only about 1.4 milliseconds, about twice as fast. These times were measured on an M1 Max. + +Native allocation footprint bounds +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The C++ ``get_allocation_footprint_policy()`` returns a detached value that +bounds one allocator buffer, including alignment and permitted cache reuse. +On Metal, every positive request has a minimum footprint of one VM page +before the cache-reuse allowance is added. This covers the page-backed +fallback used by the optional process-allocation cap, including requests +smaller than one page. A policy captured before cap installation remains +valid afterward. Zero bytes still has a zero bound; arithmetic overflow is +refused. + +For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes +have an upper bound of 32,767 bytes. The bound is conservative; it is not a +measurement of the buffer's actual backing. The cap accounts for its fixed +heap separately. Per-buffer footprint bounds and the optional cap do not +replace whole-process memory budgets or OS headroom checks. diff --git a/fork.yaml b/fork.yaml index 6c2053ae3c..b1f122d03b 100644 --- a/fork.yaml +++ b/fork.yaml @@ -105,6 +105,12 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. + Metal footprint quotations apply a one-VM-page minimum to every positive request + before adding the cache-reuse allowance, covering capped page-backed fallback even + when the policy was captured before cap installation. Standalone fresh-process + ordinary and capped cases compare actual backing with detached and direct bounds + at subpage and page boundaries; zero and overflow remain explicit controls. + The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" - "mlx/backend/common/allocation_footprint.h" @@ -118,6 +124,7 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 97fc684aca..037bedbd3d 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -511,7 +511,8 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; + // Capped fallback buffers use whole VM pages, including subpage requests. + return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index 9ebd9340b5..d50feb8b1b 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -350,12 +350,47 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } +void footprint_case(size_t page, bool capped) { + const auto quoted = get_allocation_footprint_policy(); + if (capped) { + install_process_allocation_cap(8 << 20); + } + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + for (auto requested : std::array{ + 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { + auto buffer = a::malloc(requested); + const auto actual = a::allocator().size(buffer); + size_t bound = 0; + const bool valid = quoted.upper_bound(requested, bound); + const auto direct = get_allocation_size_upper_bound(requested); + a::free(buffer); + clear_cache(); + settled(heap); + std::cout << "footprint requested=" << requested << " actual=" << actual + << " bound=" << bound << '\n'; + require( + valid && direct == bound, "pre-cap policy changed after installation"); + require( + actual >= requested && actual <= bound, + "actual backing exceeds quotation"); + require( + snapshot().pending_bytes == 0, "footprint check leaked reservation"); + } + require( + get_allocation_size_upper_bound(0) == 0, + "empty allocation bound changed"); + refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "concurrent") { + if (mode == "footprint" || mode == "footprint-ordinary") { + footprint_case(page, mode == "footprint"); + } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { failure_case(mode, page); From 23164b8bcf944cb92e221ee6a145e4c822d2b5d3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:05:56 -0700 Subject: [PATCH 09/12] Preserve capped Metal backing ownership and validate custom launch dimensions Prefault capped no-copy backing before handing it to Metal. Add a one-shot JACCL startup wait budget with C-facing group operations and failure cleanup tests. Validate custom Metal launch dimensions and bound the 1024-thread pipeline retry to the declared geometry. CPU policy, bridge, allocation-ledger and evaluator regressions pass. Native GPU and end-to-end qualification are tracked separately. Single-Mac release split: this pick keeps only the Metal half (CPU prefault of capped no-copy backing, validated custom-kernel launch dimensions and the bounded pipeline retry). The JACCL startup wait budget and its group API stay on darkbloom/sealed-all-sum with the rest of the two-Mac code. (cherry picked from commit 54975cd06be07a51128e48754729a5620e04a325) --- docs/src/dev/custom_metal_kernels.rst | 14 ++++ docs/src/usage/unified_memory.rst | 6 ++ fork.yaml | 14 ++++ mlx/backend/metal/allocator.cpp | 7 ++ mlx/backend/metal/custom_kernel.cpp | 73 +++++++++++++---- python/tests/test_metal_threadgroup_bounds.py | 80 +++++++++++++++++++ .../process_allocation_cap_metal.cpp | 55 ++++++++++++- 7 files changed, 234 insertions(+), 15 deletions(-) create mode 100644 python/tests/test_metal_threadgroup_bounds.py diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index 6a9471fd51..f3ad478438 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -466,3 +466,17 @@ We can then implement the backwards pass as follows: There's an even larger speed up for the vjp: ``676.4ms -> 16.7ms => 40x speed up`` + +Threadgroup compiler capacity +----------------------------- + +Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, +a thread count within UINT32_MAX, and axes within the device limits. Invalid +geometry is refused before output allocation. A capable original pipeline is +kept. For a nonempty grid containing complete 1024-wide groups, exactly +``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +uses a distinct source/library identity and must itself support the full +threadgroup. Compile errors and remaining capacity failures propagate. This +does not change shader math, precision, group/grid axes, or guarantee that a +particular shader can compile at 1024. Other geometries receive no retry. diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 8541fec358..10d925c349 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -94,3 +94,9 @@ have an upper bound of 32,767 bytes. The bound is conservative; it is not a measurement of the buffer's actual backing. The cap accounts for its fixed heap separately. Per-buffer footprint bounds and the optional cap do not replace whole-process memory budgets or OS headroom checks. + +Capped no-copy backing is touched once per VM page from the CPU before it is +wrapped as a Metal buffer. This makes the process physical footprint include +pages first written by GPU work. It preserves the allocator cap and does not +replace load admission or operating-system memory headroom. The fresh-process +``gpu-footprint`` regression checks GPU-written backing; it requires Metal. diff --git a/fork.yaml b/fork.yaml index b1f122d03b..5df09b43b7 100644 --- a/fork.yaml +++ b/fork.yaml @@ -110,6 +110,8 @@ def: when the policy was captured before cap installation. Standalone fresh-process ordinary and capped cases compare actual backing with detached and direct bounds at subpage and page boundaries; zero and overflow remain explicit controls. + Capped no-copy pages are first touched on the CPU so process physical + footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. globs: - "mlx/memory.h" @@ -186,6 +188,18 @@ def: - "mlx/backend/metal/kernels/binary_ops.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" + - title: "Validated custom Metal threadgroups and bounded compiler retry" + description: | + Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond + the device limits before allocating outputs. A nonempty grid with complete + x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + declaration. The original capable pipeline is retained; retry compilation + and the selected pipeline's actual capacity remain authoritative. Other + geometries refuse without clamping. Shader math and dispatch axes do not change. + globs: + - "python/tests/test_metal_threadgroup_bounds.py" + - "docs/src/dev/custom_metal_kernels.rst" - title: "Quantized tile bounds and distinct loader symbols" description: | Sorted gathered matrix products use the remaining reduction width for a diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 037bedbd3d..9db99ed59f 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -216,6 +216,13 @@ Buffer MetalAllocator::malloc_capped( throw std::bad_alloc(); } lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + // Fault every page from the CPU before wrapping it. Pages a no-copy + // buffer first receives through the GPU are not charged to this + // process's physical footprint, which hides the model from the OS + // memory-pressure accounting and from Activity Monitor. + for (size_t offset = 0; offset < charge; offset += vm_page_size) { + static_cast(pages)[offset] = 0; + } buffer = device_->newBuffer( pages, charge, resource_options, ^(void*, NS::UInteger) { lease->finish(); diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 65c33d2448..33f502a718 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -8,6 +8,8 @@ #include #include +#include +#include namespace mlx::core::fast { @@ -18,7 +20,30 @@ void CustomKernel::eval_gpu( (void)is_precompiled_; (void)shared_memory_; + const auto [tx, ty, tz] = threadgroup_; + const auto [gx, gy, gz] = grid_; + if (tx <= 0 || ty <= 0 || tz <= 0 || gx < 0 || gy < 0 || gz < 0) { + throw std::invalid_argument("Invalid custom kernel launch dimensions."); + } + size_t tg_size = 1; + for (auto dimension : {tx, ty, tz}) { + if (static_cast(dimension) > + std::numeric_limits::max() / tg_size) { + throw std::invalid_argument( + "Custom kernel threadgroup size exceeds 32 bits."); + } + tg_size *= static_cast(dimension); + } + auto& s = stream(); + auto& d = metal::device(s.device); + const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + if (static_cast(tx) > device_max.width || + static_cast(ty) > device_max.height || + static_cast(tz) > device_max.depth) { + throw std::invalid_argument( + "Custom kernel threadgroup exceeds device dimensions."); + } for (auto i : mutable_inputs_) { if (i < 0 || i >= inputs.size()) { @@ -56,13 +81,45 @@ void CustomKernel::eval_gpu( checked_inputs.push_back(check_input(in)); } - auto& d = metal::device(s.device); - std::string lib_name = fmt::format( "{}_{:x}_{}", name_, std::hash{}(source_), compile_options_); auto lib = d.get_library( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); + auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && + gx % tx == 0 && gy > 0 && gz > 0; + if (tg_size > max_tg_size && retry_geometry) { + const std::string declaration = "[[kernel]] void " + name_ + "("; + const auto position = source_.find(declaration); + if (position != std::string::npos && + source_.find(declaration, position + declaration.size()) == + std::string::npos) { + // Keep the dispatch geometry and give the compiler its required size. + auto constrained_source = source_; + constrained_source.insert( + position, + "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + + ")]] "); + auto constrained_name = + lib_name + "_required_tg_" + std::to_string(tg_size); + auto constrained_lib = d.get_library( + constrained_name, compile_options_, [&constrained_source] { + return metal::utils() + constrained_source; + }); + kernel = d.get_kernel(name_, constrained_lib); + max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + } + } + if (tg_size > max_tg_size) { + std::ostringstream msg; + msg << "Thread group size (" << tg_size << ") is greater than " + << " the maximum allowed threads per threadgroup (" << max_tg_size + << "). Kernel: " << name_ << "; threadgroup=(" << tx << "," << ty << "," + << tz << "); grid=(" << gx << "," << gy << "," << gz << ")."; + throw std::invalid_argument(msg.str()); + } + auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); int index = 0; @@ -96,18 +153,6 @@ void CustomKernel::eval_gpu( index++; } - const auto [tx, ty, tz] = threadgroup_; - auto tg_size = tx * ty * tz; - auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - if (tg_size > max_tg_size) { - std::ostringstream msg; - msg << "Thread group size (" << tg_size << ") is greater than " - << " the maximum allowed threads per threadgroup (" << max_tg_size - << ")."; - throw std::invalid_argument(msg.str()); - } - - const auto [gx, gy, gz] = grid_; MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); MTL::Size grid_dims = MTL::Size(gx, gy, gz); diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py new file mode 100644 index 0000000000..f074676be6 --- /dev/null +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -0,0 +1,80 @@ +# Custom Metal launch validation. + +import unittest + +import mlx.core as mx + + +@unittest.skipIf(not mx.metal.is_available(), "Metal is unavailable; not a pass") +class ThreadgroupBoundsTests(unittest.TestCase): + def test_invalid_dimensions_precede_compilation(self): + # A compiler attempt would raise RuntimeError instead of ValueError. + cases = [ + ((0, 1, 1), (1024, 1, 1), "dimensions"), + ((1, 0, 1), (1024, 1, 1), "dimensions"), + ((1, 1, 0), (1024, 1, 1), "dimensions"), + ((-1, 1, 1), (1024, 1, 1), "dimensions"), + ((1, -1, 1), (1024, 1, 1), "dimensions"), + ((1, 1, -1), (1024, 1, 1), "dimensions"), + ((1024, 1, 1), (-1, 1, 1), "dimensions"), + ((1024, 1, 1), (1, -1, 1), "dimensions"), + ((1024, 1, 1), (1, 1, -1), "dimensions"), + ((65536, 65536, 1), (1024, 1, 1), "32 bits"), + ( + (2147483647, 2147483647, 2147483647), + (1024, 1, 1), + "32 bits", + ), + ((2147483647, 1, 1), (1024, 1, 1), "device dimensions"), + ((1, 2147483647, 1), (1024, 1, 1), "device dimensions"), + ((1, 1, 2147483647), (1024, 1, 1), "device dimensions"), + ] + for index, (group, grid, message) in enumerate(cases): + with self.subTest(group=group, grid=grid): + kernel = mx.fast.metal_kernel( + name=f"invalid_geometry_{index}", + input_names=[], + output_names=["out"], + source="INTENTIONAL_INVALID_METAL;", + ensure_row_contiguous=True, + ) + with self.assertRaisesRegex(ValueError, message): + outputs = kernel( + inputs=[], + grid=grid, + threadgroup=group, + output_shapes=[(1,)], + output_dtypes=[mx.uint32], + init_value=0, + stream=mx.gpu, + ) + mx.eval(outputs) + + def test_legal_launch_keeps_threads_and_values(self): + for group in [32, 256, 1024]: + kernel = mx.fast.metal_kernel( + name="thread_count_and_math", + input_names=["a"], + output_names=["out", "count"], + source=""" + uint i = thread_position_in_grid.x; + out[i] = a[i] * 2.0f + 1.0f; + count[i] = threads_per_threadgroup.x; + """, + ) + a = mx.arange(2048, dtype=mx.float32) + out, count = kernel( + inputs=[a], + grid=(2048, 1, 1), + threadgroup=(group, 1, 1), + output_shapes=[(2048,), (2048,)], + output_dtypes=[mx.float32, mx.uint32], + stream=mx.gpu, + ) + mx.eval(out, count) + self.assertTrue(mx.array_equal(out, a * 2 + 1).item()) + self.assertTrue(mx.all(count == group).item()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index d50feb8b1b..ed5c4959f7 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Eigen Labs. +#include #include #include #include @@ -383,12 +384,64 @@ void footprint_case(size_t page, bool capped) { refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); } +// Capped backing is owned no-copy VM. Pages first written by the GPU must +// still be charged to this process, or the OS cannot see the model's memory. +size_t physical_footprint() { + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + require( + task_info( + mach_task_self(), + TASK_VM_INFO, + reinterpret_cast(&info), + &count) == KERN_SUCCESS, + "task footprint unavailable"); + return static_cast(info.phys_footprint); +} + +bool footprint_growth_at_least(size_t before, size_t after, size_t expected) { + return after >= before && after - before >= expected; +} + +void footprint_delta_case() { + require( + !footprint_growth_at_least(1024, 1023, 512), + "decrease wrapped into growth"); + require( + !footprint_growth_at_least(1024, 1024, 1), "unchanged footprint grew"); + require(!footprint_growth_at_least(1024, 1535, 512), "short growth passed"); + require(footprint_growth_at_least(1024, 1536, 512), "exact growth failed"); + require( + !footprint_growth_at_least(SIZE_MAX, 0, 1), "maximum baseline wrapped"); +} + +void gpu_footprint_case() { + const size_t bytes = size_t(512) << 20; + install_process_allocation_cap(size_t(2) << 30); + const auto before = physical_footprint(); + { + auto filled = + full({int(bytes / sizeof(float))}, 1.0f, float32, Device::gpu); + eval(filled); + synchronize(default_stream(Device::gpu)); + const auto after = physical_footprint(); + require( + footprint_growth_at_least(before, after, bytes - (bytes >> 4)), + "GPU-written capped backing missing from process footprint"); + } + clear_cache(); +} + int main(int argc, char** argv) { try { require(argc == 2, "one fresh-process case required"); const std::string mode = argv[1]; const size_t page = static_cast(getpagesize()); - if (mode == "footprint" || mode == "footprint-ordinary") { + if (mode == "footprint-delta") { + footprint_delta_case(); + } else if (mode == "gpu-footprint") { + gpu_footprint_case(); + } else if (mode == "footprint" || mode == "footprint-ordinary") { footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); From 2bba342de9759c6e8d1048e13fcc30868c86374c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:32:34 -0700 Subject: [PATCH 10/12] fix(metal): retry 512-thread kernels with explicit compiler capacity (cherry picked from commit 3a1791192aaf6b834d8e2a12fde623026045a4ec) --- docs/src/dev/custom_metal_kernels.rst | 8 ++++---- fork.yaml | 4 ++-- mlx/backend/metal/custom_kernel.cpp | 4 ++-- python/tests/test_metal_threadgroup_bounds.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/src/dev/custom_metal_kernels.rst b/docs/src/dev/custom_metal_kernels.rst index f3ad478438..8c160167ef 100644 --- a/docs/src/dev/custom_metal_kernels.rst +++ b/docs/src/dev/custom_metal_kernels.rst @@ -473,10 +473,10 @@ Threadgroup compiler capacity Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, a thread count within UINT32_MAX, and axes within the device limits. Invalid geometry is refused before output allocation. A capable original pipeline is -kept. For a nonempty grid containing complete 1024-wide groups, exactly -``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL -``max_total_threads_per_threadgroup(1024)`` declaration attribute. The retry +kept. For a nonempty grid containing complete 512- or 1024-wide groups, exactly +``(512, 1, 1)`` or ``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(requestedWidth)`` declaration attribute. The retry uses a distinct source/library identity and must itself support the full threadgroup. Compile errors and remaining capacity failures propagate. This does not change shader math, precision, group/grid axes, or guarantee that a -particular shader can compile at 1024. Other geometries receive no retry. +particular shader can compile at the requested width. Other geometries receive no retry. diff --git a/fork.yaml b/fork.yaml index 5df09b43b7..1c6588ee55 100644 --- a/fork.yaml +++ b/fork.yaml @@ -192,8 +192,8 @@ def: description: | Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond the device limits before allocating outputs. A nonempty grid with complete - x-axis multiples of 1024 and group (1024,1,1) may retry an insufficient - pipeline with max_total_threads_per_threadgroup(1024) on its unique generated + x-axis multiples of the group width and groups (512,1,1) or (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(requestedWidth) on its unique generated declaration. The original capable pipeline is retained; retry compilation and the selected pipeline's actual capacity remain authoritative. Other geometries refuse without clamping. Shader math and dispatch axes do not change. diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 33f502a718..3ee8f3d029 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -87,8 +87,8 @@ void CustomKernel::eval_gpu( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - const bool retry_geometry = tx == 1024 && ty == 1 && tz == 1 && gx >= tx && - gx % tx == 0 && gy > 0 && gz > 0; + const bool retry_geometry = (tx == 512 || tx == 1024) && ty == 1 && tz == 1 && + gx >= tx && gx % tx == 0 && gy > 0 && gz > 0; if (tg_size > max_tg_size && retry_geometry) { const std::string declaration = "[[kernel]] void " + name_ + "("; const auto position = source_.find(declaration); diff --git a/python/tests/test_metal_threadgroup_bounds.py b/python/tests/test_metal_threadgroup_bounds.py index f074676be6..49466d0440 100644 --- a/python/tests/test_metal_threadgroup_bounds.py +++ b/python/tests/test_metal_threadgroup_bounds.py @@ -51,7 +51,7 @@ def test_invalid_dimensions_precede_compilation(self): mx.eval(outputs) def test_legal_launch_keeps_threads_and_values(self): - for group in [32, 256, 1024]: + for group in [32, 256, 512, 1024]: kernel = mx.fast.metal_kernel( name="thread_count_and_math", input_names=["a"], From 4a3557460a1ba308fcc2b8b0b62bbeec20569355 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:06:36 -0700 Subject: [PATCH 11/12] Revert "Cover page-backed small buffers in detached Metal footprints" This reverts commit 99dc5f4235413e466be89f8ed8ff8a6d6b71de3f. --- docs/src/usage/unified_memory.rst | 14 ++------ fork.yaml | 6 ---- mlx/backend/metal/allocator.cpp | 3 +- .../process_allocation_cap_metal.cpp | 35 ------------------- 4 files changed, 3 insertions(+), 55 deletions(-) diff --git a/docs/src/usage/unified_memory.rst b/docs/src/usage/unified_memory.rst index 10d925c349..2430806e2c 100644 --- a/docs/src/usage/unified_memory.rst +++ b/docs/src/usage/unified_memory.rst @@ -82,18 +82,8 @@ Native allocation footprint bounds The C++ ``get_allocation_footprint_policy()`` returns a detached value that bounds one allocator buffer, including alignment and permitted cache reuse. -On Metal, every positive request has a minimum footprint of one VM page -before the cache-reuse allowance is added. This covers the page-backed -fallback used by the optional process-allocation cap, including requests -smaller than one page. A policy captured before cap installation remains -valid afterward. Zero bytes still has a zero bound; arithmetic overflow is -refused. - -For example, with 16,384-byte VM pages, requests from 1 through 16,384 bytes -have an upper bound of 32,767 bytes. The bound is conservative; it is not a -measurement of the buffer's actual backing. The cap accounts for its fixed -heap separately. Per-buffer footprint bounds and the optional cap do not -replace whole-process memory budgets or OS headroom checks. +Zero bytes has a zero bound; arithmetic overflow is refused. The bound does +not apply a one-page minimum to requests smaller than one page. Capped no-copy backing is touched once per VM page from the CPU before it is wrapped as a Metal buffer. This makes the process physical footprint include diff --git a/fork.yaml b/fork.yaml index 1c6588ee55..3c9334dcaa 100644 --- a/fork.yaml +++ b/fork.yaml @@ -105,11 +105,6 @@ def: memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. - Metal footprint quotations apply a one-VM-page minimum to every positive request - before adding the cache-reuse allowance, covering capped page-backed fallback even - when the policy was captured before cap installation. Standalone fresh-process - ordinary and capped cases compare actual backing with detached and direct bounds - at subpage and page boundaries; zero and overflow remain explicit controls. Capped no-copy pages are first touched on the CPU so process physical footprint accounts for pages later written by the GPU. The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. @@ -126,7 +121,6 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" - - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 9db99ed59f..6ae5030267 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -518,8 +518,7 @@ MetalAllocator& allocator() { } // namespace metal AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { - // Capped fallback buffers use whole VM pages, including subpage requests. - return {vm_page_size, vm_page_size, vm_page_size, 0, vm_page_size}; + return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; } size_t get_allocation_size_upper_bound(size_t size) { diff --git a/tests/standalone/process_allocation_cap_metal.cpp b/tests/standalone/process_allocation_cap_metal.cpp index ed5c4959f7..23c9ded0da 100644 --- a/tests/standalone/process_allocation_cap_metal.cpp +++ b/tests/standalone/process_allocation_cap_metal.cpp @@ -351,39 +351,6 @@ void failure_case(const std::string& mode, size_t page) { require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); } } -void footprint_case(size_t page, bool capped) { - const auto quoted = get_allocation_footprint_policy(); - if (capped) { - install_process_allocation_cap(8 << 20); - } - set_cache_limit(0); - const auto heap = snapshot().heap_bytes; - for (auto requested : std::array{ - 1, 8, 255, 256, 384, page - 1, page, page + 1, page * 2 + 1}) { - auto buffer = a::malloc(requested); - const auto actual = a::allocator().size(buffer); - size_t bound = 0; - const bool valid = quoted.upper_bound(requested, bound); - const auto direct = get_allocation_size_upper_bound(requested); - a::free(buffer); - clear_cache(); - settled(heap); - std::cout << "footprint requested=" << requested << " actual=" << actual - << " bound=" << bound << '\n'; - require( - valid && direct == bound, "pre-cap policy changed after installation"); - require( - actual >= requested && actual <= bound, - "actual backing exceeds quotation"); - require( - snapshot().pending_bytes == 0, "footprint check leaked reservation"); - } - require( - get_allocation_size_upper_bound(0) == 0, - "empty allocation bound changed"); - refuses([] { get_allocation_size_upper_bound(SIZE_MAX); }); -} - // Capped backing is owned no-copy VM. Pages first written by the GPU must // still be charged to this process, or the OS cannot see the model's memory. size_t physical_footprint() { @@ -441,8 +408,6 @@ int main(int argc, char** argv) { footprint_delta_case(); } else if (mode == "gpu-footprint") { gpu_footprint_case(); - } else if (mode == "footprint" || mode == "footprint-ordinary") { - footprint_case(page, mode == "footprint"); } else if (mode == "concurrent") { concurrent_case(page); } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { From 6ee3062c7fcba32f36eb50cbb9df3d1d755735ba Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:23:01 -0700 Subject: [PATCH 12/12] fork.yaml: keep describing docs/src/usage/unified_memory.rst The file still differs from upstream (capped no-copy backing paragraph), so its glob stays in the allocator accounting section. --- fork.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/fork.yaml b/fork.yaml index 3c9334dcaa..40e9ba2465 100644 --- a/fork.yaml +++ b/fork.yaml @@ -121,6 +121,7 @@ def: - "mlx/backend/cuda/allocator.cpp" - "mlx/backend/no_gpu/allocator.cpp" - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" - title: "FP32 partial sums in two-pass vector SDPA" description: | The two-pass vector SDPA cast unnormalized partial sums to the input dtype before