From 5c9e46a763ef44c9fd89c923a194b78afb7e8c13 Mon Sep 17 00:00:00 2001 From: Mario Cho Date: Thu, 3 Dec 2026 23:21:59 +0900 Subject: [PATCH] perf(metal): floor the SDPA query-chunk row count to a Neural Accelerator tile At the 256 MiB default a head_dim 512 array-mask call is cut into 419-row chunks, which differs from the single call by 3.05e-5 (1 to 2 fp16 ulp) on M5. A chunk size that is not a tile multiple changes the kernel's reduction. `query_chunk_len` now rounds its result down to a multiple of `NA_TILE_SIZE` (32) through a new `align_to_na_tile_floor`, the counterpart to the existing ceiling helper: rounding up would spend budget the caller already decided it did not have, so the floor never exceeds its input. A count below one tile is returned unchanged for the same reason. Verified: - `layers::tests::query_chunk_len_splits_evenly_within_budget` asserts the alignment on cells that really need it (209 -> 192, 100 -> 96 rows) and that the budget still bounds every chunk; mutation-checked by removing the floor, which fails it with `chunk 209 is not a tile multiple`. - `utils::tests::test_align_to_na_tile_floor_never_exceeds_its_input` sweeps 0..=1024 and pins that the floor never grows its input. - `cargo test -p mlxcel-core --lib -- --test-threads=1`: 2688 passed, 7 ignored, 0 failed. `cargo fmt --check` and `cargo clippy -p mlxcel-core --lib --tests -- -D warnings` clean. Not verified here: the issue's `sdpa_chunk_peak_memory_probe` run needs an M5-class host. On this 32 GB M1 Pro the probe aborts with `Insufficient Memory (kIOGPUCommandBufferCallbackErrorOutOfMemory)` before it can report a max abs diff, so the 256 MiB equality claim still needs an M5 session. Refs #3052 --- src/lib/mlxcel-core/src/layers.rs | 42 +++++++++++++++++++++-- src/lib/mlxcel-core/src/utils.rs | 55 +++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/lib/mlxcel-core/src/layers.rs b/src/lib/mlxcel-core/src/layers.rs index 2960d48a7..d8c866178 100644 --- a/src/lib/mlxcel-core/src/layers.rs +++ b/src/lib/mlxcel-core/src/layers.rs @@ -6202,7 +6202,11 @@ fn query_chunk_len(per_row_bytes: usize, q_len: i32, budget: usize) -> Option UniquePtr { let len: usize = shape.iter().map(|d| *d as usize).product(); @@ -9524,7 +9529,8 @@ mod tests { // Fits: no chunking. assert_eq!(query_chunk_len(100, 10, 1000), None); assert_eq!(query_chunk_len(100, 10, 1_000_000), None); - // 10 rows * 100 B = 1000 B over a 400 B budget -> 3 chunks of 4/4/2. + // 10 rows * 100 B = 1000 B over a 400 B budget -> 3 chunks of 4/4/2; + // a chunk below one tile is left as the budget derived it. assert_eq!(query_chunk_len(100, 10, 400), Some(4)); // Exactly one row over budget still splits in two. assert_eq!(query_chunk_len(100, 10, 999), Some(5)); @@ -9535,6 +9541,38 @@ mod tests { // Every chunk's scores stay within budget. let chunk = query_chunk_len(1000, 100, 7000).unwrap(); assert!(chunk as usize * 1000 <= 7000); + // #3052: the row count is a whole Neural Accelerator tile, so the + // kernel's reduction does not change with the chunk boundary. + // Cells where the budget-derived count is above one tile and not a + // tile multiple, so the floor has to do work: the head_dim 512 shape + // from #3052 (209 rows) and a smaller one (100 rows). The last two + // stay below one tile, where the budget's own value has to stand. + for (per_row, q_len, budget) in [ + (1_280_000, 20000, 256 << 20), + (1000, 2000, 100_000), + (100, 1000, 2_100), + (100, 10, 400), + (1000, 100, 7000), + ] { + let Some(chunk) = query_chunk_len(per_row, q_len, budget) else { + continue; + }; + let chunk = chunk as usize; + // Above one tile the row count is a whole tile; below it the + // budget's own value stands, because rounding up would overspend. + if chunk >= NA_TILE_SIZE { + assert_eq!( + chunk % NA_TILE_SIZE, + 0, + "chunk {chunk} is not a tile multiple \ + (per_row {per_row}, q_len {q_len}, budget {budget})" + ); + } + assert!( + chunk * per_row <= budget.max(per_row), + "chunk {chunk} of {per_row} B rows leaves the budget {budget}" + ); + } } #[test] diff --git a/src/lib/mlxcel-core/src/utils.rs b/src/lib/mlxcel-core/src/utils.rs index 959c0f73a..49e7caef1 100644 --- a/src/lib/mlxcel-core/src/utils.rs +++ b/src/lib/mlxcel-core/src/utils.rs @@ -1895,6 +1895,36 @@ pub fn align_to_na_tile(len: usize) -> usize { len.div_ceil(NA_TILE_SIZE) * NA_TILE_SIZE } +/// Round a length down to the nearest multiple of `NA_TILE_SIZE`, never above +/// the input. +/// +/// The floor counterpart to [`align_to_na_tile`], for a length that is a +/// stride rather than a padded extent: rounding such a value up would push it +/// past the bound it came from. A query-chunk row count is the case (#3052) — +/// the budget decided how many rows fit, so the tile-aligned count has to stay +/// inside that budget. +/// +/// A length below one tile is returned unchanged. Rounding it up to a tile +/// would exceed the bound the caller derived it from, and rounding it to zero +/// would make a chunk that never advances. +/// +/// # Examples +/// ```ignore +/// assert_eq!(align_to_na_tile_floor(10), 10); +/// assert_eq!(align_to_na_tile_floor(32), 32); +/// assert_eq!(align_to_na_tile_floor(63), 32); +/// assert_eq!(align_to_na_tile_floor(64), 64); +/// assert_eq!(align_to_na_tile_floor(419), 416); +/// assert_eq!(align_to_na_tile_floor(0), 0); +/// ``` +#[inline] +pub fn align_to_na_tile_floor(len: usize) -> usize { + if len < NA_TILE_SIZE { + return len; + } + (len / NA_TILE_SIZE) * NA_TILE_SIZE +} + /// Create a causal attention mask for a tile-aligned padded prefill. /// /// The input sequence has `actual_len` real tokens followed by `pad_len = @@ -2142,6 +2172,31 @@ mod tests { assert_eq!(align_to_na_tile(65), 96); } + #[test] + fn test_align_to_na_tile_floor_never_exceeds_its_input() { + // The floor exists so a budget-derived count can be tiled without + // leaving the budget (#3052), which is where it differs from + // `align_to_na_tile`: never above the input, for any input. + for len in 0..=1024usize { + let floored = align_to_na_tile_floor(len); + assert!(floored <= len, "{len} -> {floored} grew"); + if len < NA_TILE_SIZE { + assert_eq!(floored, len, "{len} below one tile must be unchanged"); + } else { + assert_eq!(floored % NA_TILE_SIZE, 0, "{len} -> {floored} is not tiled"); + let distance = align_to_na_tile(len) - floored; + assert!( + distance == 0 || distance == NA_TILE_SIZE, + "{len} -> {floored} is {} tiles from the ceiling", + distance as f64 / NA_TILE_SIZE as f64 + ); + } + } + assert_eq!(align_to_na_tile_floor(419), 416); + assert_eq!(align_to_na_tile_floor(32), 32); + assert_eq!(align_to_na_tile_floor(31), 31); + } + #[test] fn test_create_padded_prefill_mask_shape() { // actual_len=10, padded_len=32, offset=0