Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
fe35554
Preserve singleton FP32 arithmetic for Bonsai packed rows
jonathan308 Oct 23, 2026
b1f007a
Apply required Swift formatting to Bonsai arithmetic changes
jonathan308 Oct 23, 2026
af2c35d
Pin core ordering for fast Metal fence waits
jonathan308 Oct 23, 2026
613671c
Pin the core that keeps GPU streams off each other's fast fences
jonathan308 Oct 25, 2026
2502edf
Pin the core with prompt-sized steel tiles
jonathan308 Oct 26, 2026
3832c0d
Pin the core that keeps precompiled MLX builds on 32 x 32 tiles
jonathan308 Oct 26, 2026
e6ea833
Merge the cluster Swift stack with main 69594861 into the Bonsai row …
jonathan308 Oct 26, 2026
5b0fe5b
Merge the current #61 head 3832c0de into the refreshed Bonsai row branch
jonathan308 Oct 26, 2026
6f7646a
Merge the restitched cluster Swift stack (#56) into the Bonsai row br…
jonathan308 Oct 26, 2026
89144f9
Pin the core and C merged with main for the fence-ordering branch
jonathan308 Oct 26, 2026
f70ddf7
Pin the core with MLX_QMV_BATCH_INVARIANT for the fence-ordering branch
jonathan308 Oct 26, 2026
31ffa0d
Merge the re-pinned sealed all-sum branch into the row-arithmetic branch
jonathan308 Oct 27, 2026
078a6e2
Correct the Bonsai row and steel-tile docs; cover singleton rows again
davidtai Oct 27, 2026
bb95212
Merge main e5ea7601 (the merge of #56) into the Bonsai row branch (#61)
davidtai Oct 27, 2026
4df8cdf
Pin mlx e637499f (#41) and mlx-c 2ac897e3 (#15) with the review fixes
davidtai Oct 27, 2026
c633d22
Pin mlx 72dffa2d, the moved head of Layr-Labs/mlx#41
davidtai Oct 27, 2026
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
5 changes: 5 additions & 0 deletions Source/Cmlx/include-framework/mlx-backend-metal-device.h
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,11 @@ class MLX_API Device {
};

MLX_API Device& device(mlx::core::Device);

// The calling thread's steel quantized-matmul output tile (32, 64, 6432,
// 3264 or 6464), or 0
// for MLX_QMM_STEEL_TILE (mlx_metal_set_thread_qmm_steel_tile).
int thread_qmm_steel_tile();
MLX_API CommandEncoder& get_command_encoder(Stream s);

std::unordered_map<int, CommandEncoder>& get_command_encoders();
Expand Down
17 changes: 13 additions & 4 deletions Source/Cmlx/include-framework/mlx-c-distributed_group.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ typedef void (*mlx_distributed_bootstrap_release)(void* context);
* Strict JACCL initialization through an owner callback, without TCPAllGather.
* Existing cached JACCL initialization is rejected; it is not reauthenticated.
* Both callbacks are required. When release_context is non-null, this call
* consumes one context reference on every path. Release can occur only when
* the native backend cache is destroyed, not when one group handle is freed.
* consumes one context reference on every path. On success, release runs when
* the last reference to the native group is dropped; the backend cache and
* every group handle and graph that uses the group hold one, so in practice
* release runs at process exit. Do not call this concurrently with any other
* distributed initialization: the native backend cache is not locked.
* Callback failure is permanent. This API itself does not authenticate bytes.
* Bounds: 2..64 ranks, 1..1MiB per rank, at most 8MiB total; the total bound
* must fit all ranks at their per-rank bound. Use a fresh worker per epoch.
Expand All @@ -76,8 +79,14 @@ int mlx_distributed_init_jaccl_with_bootstrap(
* partials cross the link only as frames the installed codec seals and opens
* (a frame is plaintext bytes + overhead). Callbacks run on the CPU stream's
* thread, must not reenter MLX and must not throw; nonzero refuses (the
* evaluation fails). counter advances by one per sealed all-sum, identically
* on both ranks. A null seal removes the codec.
* evaluation fails). counter advances by one per evaluated sealed collective
* (all-sum, reduce-scatter, all-gather), identically on both ranks. It is one
* sequence per process: it starts at 0 in each process and is not reset when
* a codec is installed, so keys must be fresh per process for (key, counter)
* to stay unique. A null seal or a null open removes the codec and returns 0.
* Each graph copies the codec installed when the graph is built, context
* included: context must stay valid until every such graph is evaluated or
* freed, even after the codec is removed or replaced.
*/
typedef int (*mlx_distributed_seal_fn)(
void* context, const void* plaintext, size_t bytes, void* frame, uint64_t counter);
Expand Down
25 changes: 25 additions & 0 deletions Source/Cmlx/include-framework/mlx-utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,31 @@ inline bool residency_debug() {
return residency_debug_;
}

// Output tile of the steel affine quantized matmul on GPUs without neural
// accelerators (see `qmm` in backend-metal-quantized.cpp): 32, 64, 6432,
// 3264 or 6464, or 0 (default) for the input width's own tile. Builds whose
// kernels come only from the precompiled library keep 32 x 32.
inline int qmm_steel_tile() {
static int tile_ = get_var("MLX_QMM_STEEL_TILE", 0);
return tile_;
}

// Fewest 64 x 64 threadgroups a product must fill to take a tile other than
// 32 x 32 (fewer keep 32 x 32 and their GPU occupancy).
inline int qmm_steel_tile_min_groups() {
static int groups_ = get_var("MLX_QMM_STEEL_TILE_MIN_GROUPS", 0);
return groups_;
}

// Quantized matmuls (x @ w.T) with fewer rows than the vector limit use only
// the vector kernels (see `QuantizedMatmul::eval_gpu` in
// backend-metal-quantized.cpp). Then a row has the same bits at each row count
// from 2 to the limit - 1.
inline bool qmv_batch_invariant() {
static bool invariant_ = get_var("MLX_QMV_BATCH_INVARIANT", 0);
return invariant_;
}

inline bool metal_fast_synch() {
static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0);
return metal_fast_synch;
Expand Down
17 changes: 13 additions & 4 deletions Source/Cmlx/include/mlx/c/distributed_group.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ typedef void (*mlx_distributed_bootstrap_release)(void* context);
* Strict JACCL initialization through an owner callback, without TCPAllGather.
* Existing cached JACCL initialization is rejected; it is not reauthenticated.
* Both callbacks are required. When release_context is non-null, this call
* consumes one context reference on every path. Release can occur only when
* the native backend cache is destroyed, not when one group handle is freed.
* consumes one context reference on every path. On success, release runs when
* the last reference to the native group is dropped; the backend cache and
* every group handle and graph that uses the group hold one, so in practice
* release runs at process exit. Do not call this concurrently with any other
* distributed initialization: the native backend cache is not locked.
* Callback failure is permanent. This API itself does not authenticate bytes.
* Bounds: 2..64 ranks, 1..1MiB per rank, at most 8MiB total; the total bound
* must fit all ranks at their per-rank bound. Use a fresh worker per epoch.
Expand All @@ -76,8 +79,14 @@ int mlx_distributed_init_jaccl_with_bootstrap(
* partials cross the link only as frames the installed codec seals and opens
* (a frame is plaintext bytes + overhead). Callbacks run on the CPU stream's
* thread, must not reenter MLX and must not throw; nonzero refuses (the
* evaluation fails). counter advances by one per sealed all-sum, identically
* on both ranks. A null seal removes the codec.
* evaluation fails). counter advances by one per evaluated sealed collective
* (all-sum, reduce-scatter, all-gather), identically on both ranks. It is one
* sequence per process: it starts at 0 in each process and is not reset when
* a codec is installed, so keys must be fresh per process for (key, counter)
* to stay unique. A null seal or a null open removes the codec and returns 0.
* Each graph copies the codec installed when the graph is built, context
* included: context must stay valid until every such graph is evaluated or
* freed, even after the codec is removed or replaced.
*/
typedef int (*mlx_distributed_seal_fn)(
void* context, const void* plaintext, size_t bytes, void* frame, uint64_t counter);
Expand Down
8 changes: 8 additions & 0 deletions Source/Cmlx/include/mlx/command_buffer_limits.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ void mlx_metal_set_thread_command_buffer_limits(
int* previous_ops,
int* previous_mb);

/// Output tile (32, 64, 6432, 3264 or 6464: rows x columns[, K depth]) of the
/// steel affine quantized matmul for the
/// products the calling thread encodes on a GPU without neural accelerators;
/// any other value restores MLX_QMM_STEEL_TILE. Stores the thread's previous
/// override (0 for none) when the out pointer is not null. Every element of
/// a product keeps its bits at either tile.
void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile);

#ifdef __cplusplus
}
#endif
Expand Down
2 changes: 1 addition & 1 deletion Source/Cmlx/mlx
2 changes: 1 addition & 1 deletion Source/Cmlx/mlx-c
22 changes: 22 additions & 0 deletions Source/MLX/GPU+Metal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -400,4 +400,26 @@ extension GPU {
}
return try body()
}

/// Runs `body` with the output tile of MLX's steel affine quantized
/// matmul (`tile`: 32 or 64 elements a side, 6432 or 3264 for 64 x 32 or
/// 32 x 64, 6464 for 64 x 64 with a K depth of 64 for 16-bit inputs in
/// groups of 64 or more and of 32 otherwise; any other value: the
/// process's own, `MLX_QMM_STEEL_TILE`, by default 64 x 32 for 16-bit and
/// 32 x 64 for FP32 inputs from 256 rows) for the products this thread
/// encodes on a GPU without
/// neural accelerators, then restores the thread's previous choice.
/// Evaluation encodes on the thread that calls `eval`, so `body` must make
/// that call itself. The tile decides which threadgroup computes an
/// element, never its bits: every element accumulates the same K slabs
/// in the same order at either tile. A build whose kernels come only from
/// the precompiled library (no Metal JIT) keeps 32 x 32 whatever the tile.
public static func withQuantizedMatmulSteelTile<R>(
_ tile: Int, _ body: () throws -> R
) rethrows -> R {
var previous: Int32 = 0
mlx_metal_set_thread_qmm_steel_tile(Int32(clamping: tile), &previous)
defer { mlx_metal_set_thread_qmm_steel_tile(previous, nil) }
return try body()
}
}
15 changes: 14 additions & 1 deletion Source/MLXNN/Hadamard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public struct SignedBlockHadamard {
/// Recover the original basis after looking up folded embedding rows.
public func inverse(_ x: MLXArray) -> MLXArray {
validate(x)
return (hadamardTransform(x.asType(.float32).reshaped([-1, blockSize])).reshaped(x.shape)
return
(hadamardTransform(x.asType(.float32).reshaped([-1, blockSize])).reshaped(x.shape)
* signs).asType(x.dtype)
}

Expand Down Expand Up @@ -224,6 +225,18 @@ public final class HadamardQuantizedLinear: QuantizedLinear {

public override func callAsFunction(_ x: MLXArray) -> MLXArray {
let rotated = transform(gdnLayout.map { $0(x) } ?? x)
// Bonsai's signed block1024/affine2 pack advertises FP32 arithmetic.
// Multi-row projections must not enter the architecture-dependent
// TF32 matrix kernel. Preserve the scalar packed reduction per row;
// singleton decode and every other Hadamard policy stay unchanged.
if rotated.dtype == .float32, rotated.ndim >= 2,
rotated.size / transform.width > 1, bits == 2, groupSize == 128,
transform.blockSize == 1024, scales.dtype == .float16
{
return constantCachedForward(
rotated, allowFloat16: permitsFloat16ConstantReuse,
independentRows: true)
}
if permitsFloat16ConstantReuse && rotated.dtype == .float32 {
return constantCachedForward(rotated, allowFloat16: true)
}
Expand Down
38 changes: 34 additions & 4 deletions Source/MLXNN/Quantized.swift
Original file line number Diff line number Diff line change
Expand Up @@ -395,10 +395,24 @@ open class QuantizedLinear: Linear, Quantized {
constantCachedForward(x, allowFloat16: false)
}

/// Affine FP32 rows `[..., K]`, each through MLX's single-row (M=1)
/// kernel as its own call would run it, with the FP32 widening of the
/// BF16 scales and biases that `callAsFunction` caches (one copy for
/// both, made on the caller's stream) instead of a fresh widening inside
/// every call.
///
/// - Precondition: `x` is FP32 with two or more dimensions, and the layer
/// uses `.affine` quantization. Other inputs stop the process.
public func independentRowsForward(_ x: MLXArray) -> MLXArray {
constantCachedForward(x, allowFloat16: false, independentRows: true)
}

/// Shared arithmetic path; FP16 widening reuse is private and opt-in for
/// an eligible packed-Hadamard caller. Ordinary quantized layers retain
/// the established BF16-only cache contract.
func constantCachedForward(_ x: MLXArray, allowFloat16: Bool) -> MLXArray {
func constantCachedForward(
_ x: MLXArray, allowFloat16: Bool, independentRows: Bool = false
) -> MLXArray {
// The native affine operation already widens BF16 constants when x
// is FP32. Reuse precisely that conversion, without changing its
// promotion policy or touching MXFP4's packed U8 scales.
Expand All @@ -415,9 +429,25 @@ open class QuantizedLinear: Linear, Quantized {
allowFloat16: allowFloat16) ?? offsets)
: offsets
}
var output = quantizedMM(
x, weight, scales: scales, biases: biases, transpose: true,
groupSize: groupSize, bits: bits, mode: mode)
let outputShape = Array(x.shape.dropLast()) + [weight.dim(0)]
// Only the signed-Hadamard FP32 contract and `independentRowsForward`
// opt into this branch. A leading weight dimension keeps every row at M=1, avoiding the
// architecture-dependent TF32 matrix path without unpacking weights.
// Ordinary quantized callers preserve their existing operator below.
var output: MLXArray
if independentRows {
precondition(x.dtype == .float32 && x.ndim >= 2 && mode == .affine)
output = quantizedMM(
x.reshaped([-1, 1, x.dim(-1)]), weight.expandedDimensions(axis: 0),
scales: scales.expandedDimensions(axis: 0),
biases: biases?.expandedDimensions(axis: 0), transpose: true,
groupSize: groupSize, bits: bits, mode: mode
).reshaped(outputShape)
} else {
output = quantizedMM(
x, weight, scales: scales, biases: biases, transpose: true,
groupSize: groupSize, bits: bits, mode: mode)
}
output = applyNVFP4GlobalScale(output, globalScale: globalScale)
if let bias {
let bias =
Expand Down
Loading
Loading