Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Source/Cmlx/include-framework/mlx-c-metal.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ extern "C" {
/**@{*/

int mlx_metal_is_available(bool* res);
int mlx_metal_set_batch_invariant_limit(int limit);
int mlx_metal_get_batch_invariant_limit(int* res);
int mlx_metal_start_capture(const char* path);
int mlx_metal_stop_capture(void);

Expand Down
2 changes: 2 additions & 0 deletions Source/Cmlx/include/mlx/c/metal.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ extern "C" {
/**@{*/

int mlx_metal_is_available(bool* res);
int mlx_metal_set_batch_invariant_limit(int limit);
int mlx_metal_get_batch_invariant_limit(int* res);
int mlx_metal_start_capture(const char* path);
int mlx_metal_stop_capture(void);

Expand Down
2 changes: 1 addition & 1 deletion Source/Cmlx/mlx-c
Submodule mlx-c updated 2 files
+18 −0 mlx/c/metal.cpp
+2 −0 mlx/c/metal.h
19 changes: 19 additions & 0 deletions Source/MLX/GPU+Metal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,25 @@ public enum GPU {

public typealias Snapshot = Memory.Snapshot

/// Maximum short-block dimension using canonical Metal reduction plans for
/// supported inference kernels.
///
/// This covers dense matmul, transposed-weight quantized matmul, and vector
/// SDPA queries up to length eight; it does not make every MLX operation
/// batch invariant. This is useful for greedy speculative decoding. Set to
/// zero to disable. Increasing the limit can reduce performance. The setting
/// is process-wide and should remain stable while concurrent work executes.
public static var batchInvariantLimit: Int {
get {
var result: Int32 = 0
mlx_metal_get_batch_invariant_limit(&result)
return Int(result)
}
set {
mlx_metal_set_batch_invariant_limit(Int32(clamping: newValue))
}
}

/// Get the actively used memory in bytes.
///
/// Note, this will not always match memory use reported by the system because
Expand Down
107 changes: 107 additions & 0 deletions Tests/MLXTests/BatchInvariantTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright © 2026 Apple Inc.

import MLX
import XCTest

final class BatchInvariantTests: XCTestCase {

override class func setUp() {
setDefaultDevice()
}

func testMatmulMatchesSingleRow() {
let previous = GPU.batchInvariantLimit
GPU.batchInvariantLimit = 4
defer { GPU.batchInvariantLimit = previous }

let m = 4
let k = 4096
let n = 4096
let x = sin(arange(0, m * k).asType(.float32) * 0.013)
.reshaped(m, k).asType(.bfloat16)
let weight = cos(arange(0, n * k).asType(.float32) * 0.009)
.reshaped(n, k).asType(.bfloat16)
let xLast = x[(m - 1) ..< m]

let block = matmul(x, weight.T)
let single = matmul(xLast, weight.T)
eval(block, single)

XCTAssertTrue(block[(m - 1) ..< m].arrayEqual(single).item())
}

func testSDPAMatchesSingleQuery() {
let previous = GPU.batchInvariantLimit
GPU.batchInvariantLimit = 8
defer { GPU.batchInvariantLimit = previous }

let queryHeads = 2
let kvHeads = 1
let queryLength = 8
let headDimension = 64
let queries = sin(
arange(0, queryHeads * queryLength * headDimension).asType(.float32) * 0.017
)
.reshaped(1, queryHeads, queryLength, headDimension)
.asType(.bfloat16)

for keyLength in [1_028, 8_196, 16_388, 65_540] {
let keys = cos(
arange(0, kvHeads * keyLength * headDimension).asType(.float32) * 0.011
)
.reshaped(1, kvHeads, keyLength, headDimension)
.asType(.bfloat16)
let values = sin(
arange(0, kvHeads * keyLength * headDimension).asType(.float32) * 0.007
)
.reshaped(1, kvHeads, keyLength, headDimension)
.asType(.bfloat16)
let block = MLXFast.scaledDotProductAttention(
queries: queries, keys: keys, values: values,
scale: 1 / sqrt(Float(headDimension)), mask: .causal)

for row in 0 ..< queryLength {
let prefix = keyLength - queryLength + row + 1
let single = MLXFast.scaledDotProductAttention(
queries: queries[0 ..< 1, 0..., row ..< (row + 1), 0...],
keys: keys[0 ..< 1, 0..., 0 ..< prefix, 0...],
values: values[0 ..< 1, 0..., 0 ..< prefix, 0...],
scale: 1 / sqrt(Float(headDimension)), mask: .none)
let blockRow = block[0 ..< 1, 0..., row ..< (row + 1), 0...]
eval(blockRow, single)
XCTAssertTrue(
blockRow.arrayEqual(single).item(),
"keyLength=\(keyLength), row=\(row), prefix=\(prefix)")
}
}
}

func testQuantizedMatmulMatchesSingleRows() {
let previous = GPU.batchInvariantLimit
let limit = 12
GPU.batchInvariantLimit = limit
defer { GPU.batchInvariantLimit = previous }

let k = 4_096
let n = 512
let x = sin(arange(0, limit * k).asType(.float32) * 0.013)
.reshaped(limit, k)
let weight = cos(arange(0, n * k).asType(.float32) * 0.009)
.reshaped(n, k)
let q = quantized(weight, groupSize: 32, bits: 4)

for m in 1 ... limit {
let block = quantizedMM(
x[0 ..< m], q.wq, scales: q.scales, biases: q.biases,
groupSize: 32, bits: 4)
for row in 0 ..< m {
let single = quantizedMM(
x[row ..< (row + 1)], q.wq, scales: q.scales, biases: q.biases,
groupSize: 32, bits: 4)
let blockRow = block[row ..< (row + 1)]
eval(blockRow, single)
XCTAssertTrue(blockRow.arrayEqual(single).item(), "m=\(m), row=\(row)")
}
}
}
}
Loading