Repository navigation
Distributed support - #482
Conversation
Compile mlx-c/mlx/c/distributed.cpp and distributed_group.cpp into the Cmlx target. No backend is enabled yet, so every backend reports unavailable and distributed::init() returns an empty group of size 1. Adds MLXDistributed.isAvailable() and a test, which together verify the wrappers both compile and link.
Build mlx/distributed/ring/ring.cpp instead of the no_ring.cpp stub. Ring needs only TCP sockets, so it builds on every platform without additional include paths or SDK requirements. Without MLX_HOSTFILE and MLX_RANK, ring::init() returns null for a non-strict init, so the default group remains an empty group of size 1 and single-process tests are unaffected.
Port mlx.core.distributed to Swift: MLXDistributed.Group with rank, size and split, plus the eight collectives and point to point operations (allSum, allMax, allMin, allGather, sumScatter, send, recv, recvLike). Following the rest of the Swift API none of these throw -- errors raised by MLX are reported through mlx_set_error_handler and surface via withError()/checkedEval(). Tests run single process: at size one MLX short circuits the collectives to the identity and rejects the point to point operations, which covers the whole API surface without a launcher.
Port the core of mlx.nn.layers.distributed: AllToShardedLinear and ShardedToAllLinear, the shardLinear/shardInPlace helpers, sumGradients and averageGradients. Python's segments argument accepts an int or a list of either indices or fractions; that becomes the Segments enum here. The from_linear class methods become convenience initializers taking a Linear, matching how QuantizedLinear converts. The quantized layers and fully_shard are not included.
The distributed primitives have no GPU implementation on Metal -- AllReduce::eval_gpu and friends in backend/metal/distributed.cpp throw unconditionally -- so a collective submitted to the default GPU stream always fails. MLX handles this by letting each backend choose its device when no stream is given: Group::communication_stream returns to_stream(s, Device::cpu) for ring, mpi and jaccl, and Device::gpu for nccl. That path is unreachable through mlx-c, whose mlx_stream_get_() rejects a null handle, so Swift has to pass a concrete stream. Default to the CPU stream, which is correct for every backend that can be built on Apple platforms. This will need revisiting if nccl is ever enabled; the real fix is for mlx-c to accept an unspecified stream.
The test process is itself a rank: with MLX_TEST_DISTRIBUTED=1 the first
process reserves two loopback ports, writes a temporary hostfile,
re-executes the test bundle as rank 1 and runs as rank 0. Both ranks
execute the same body, so no separate worker executable is needed --
this mirrors how the Python distributed tests are run under mlx.launch.
Skipped unless MLX_TEST_DISTRIBUTED=1, matching the Python tests, which
are likewise not part of CI. It can be enabled by adding a second
xctest invocation with that variable set.
There is a single test method because MLX caches the group per process,
and because every rank must issue the same collectives in the same
order. The single process tests skip during a multi process run, since
their assertions describe a group of size one.
Run with:
xcodebuild build-for-testing -scheme mlx-swift-Package -destination 'platform=macOS'
MLX_TEST_DISTRIBUTED=1 xcrun xctest -XCTest DistributedRingTests \
~/Library/Developer/Xcode/DerivedData/mlx-swift-*/Build/Products/Debug/MLXTests.xctest
The single process tests only exercise the sharded layers in a group of size one, where sharding is the identity and the interesting paths -- splitting the weight, selecting this rank's slice, reducing inside the layer -- never run. Every rank seeds identically and builds the same Linear, then: AllToShardedLinear holds half the output dimensions; gathering the transposed partial results reassembles the columns in rank order and must equal the unsharded result. ShardedToAllLinear holds half the input dimensions and is fed the matching slice; its internal allSum must reproduce the unsharded result on both ranks.
mlx_distributed_init reports failure through the error handler and leaves the group handle null. Wrapping that in a Group produced an object whose rank and size silently read as zero, so a caller that did not wrap the call tightly in withError got a plausible looking group that was quietly broken. Make both initialize and split failable, and add globalGroup for the common case where a non-strict init cannot meaningfully fail. NOT BUILT.
|
Pushed one fix found while enabling JACCL: |
| public func shardLinear( | ||
| _ layer: Linear, sharding: ShardingType, segments: Segments = .count(1), | ||
| group: MLXDistributed.Group? = nil | ||
| ) -> Module { | ||
| switch sharding { | ||
| case .allToSharded: | ||
| AllToShardedLinear(layer, segments: segments, group: group) |
There was a problem hiding this comment.
If passed a QuantizedLinear this will (I think) not do anything good. It looks like the python side has QuantizedAllToShardedLinear etc.
There was a problem hiding this comment.
Fixed in a4988de. Added QuantizedAllToShardedLinear and QuantizedShardedToAllLinear, as in Python, and shardLinear returns the quantized flavor for a QuantizedLinear. Sharding a quantized layer's inputs checks that every shard holds whole quantization groups. The float initializers also throw if they're handed a QuantizedLinear directly. Also added ports of test_shard_linear and test_quantized_sharded_linear_construction
|
Doesn't have to be fixed right away, but the new test files have to be added in the xcode/MLX.xcodeproj. I think just opening that file in Xcode should populate it. |
| /// the result is sharded across the group. | ||
| /// | ||
| /// The gradients are automatically aggregated from each member of the group. | ||
| open class AllToShardedLinear: Module, UnaryLayer { |
There was a problem hiding this comment.
Is this something that would be substituted inside the model, like quantization does today? If so, I wonder:
- do we need marker protocols like Quantizable/Quantized?
- should this be a subtype of Linear?
Still working on understanding how you use this in practice so these questions might be silly.
There was a problem hiding this comment.
Reading the python code it isn't generic like quantization. There is an optional method at the LanguageModel layer:
def shard(self, group: Optional[mx.distributed.Group] = None):
group = group or mx.distributed.init()
N = group.size()
for layer in self.model.layers:
# Shard the self attention
layer.self_attn.q_proj = shard_linear(
layer.self_attn.q_proj, "all-to-sharded", group=group
)
layer.self_attn.k_proj = shard_linear(
layer.self_attn.k_proj, "all-to-sharded", group=group
)So I think Quantizable/Quantized isn't strictly required. We could add it, but there is no clear use for it.
Making this a subtype might be useful. Otherwise we would have to change the swift models from declaring modules as Linear -> modules as UnaryLayer. I think it loses some of the documentation of the actual types but since authors have to write the shard method by hand anyway, it could be ok.
So combining the two ideas, perhaps a protocol like ShardableLinear would be useful -- both Linear and AllToShardedLinear could conform. This keeps the documentation of the type and prevents accidental sharding of the wrong layers.
Anyway, something to think of -- this PR isn't adding the adoption just yet, only the underpinnings.
There was a problem hiding this comment.
The sharded layers now subclass Linear (the quantized ones QuantizedLinear), so a model's shard method can install them in its existing @ModuleInfo var …: Linear properties with update(modules:) the same way quantization does, and models don't have to switch to UnaryLayer. Quantizing after sharding keeps the layers sharded.
If you prefer I can use the suggested protocol instead.
There was a problem hiding this comment.
I think Linear is sufficient -- we can always add it later if it seems like it would be useful.
| private func shard( | ||
| _ parameters: ModuleParameters, group: MLXDistributed.Group, | ||
| _ sharding: ShardingPredicate | ||
| ) -> ModuleParameters { |
There was a problem hiding this comment.
Looking at how this works on the python side:
# mlx-lm def sharded_load
model, _ = load_model(
model_path, lazy=True, strict=False, trust_remote_code=trust_remote_code
)
# dkoski -- still lazy at this point
if tensor_group is not None:
model.shard(tensor_group)
if pipeline_group is not None:
model.model.pipeline(pipeline_group)
mx.eval(model.parameters())We have recently made some changes that make loading faster but non-lazy -- that may defeat some of this behavior (meaning, I think, very large models will require full memory to load at peak).
Well, this is special loading code for distributed in python, so I guess we need something similar in swift. Anyway, just highlighting the point that swift is maybe diverging slightly from the python core in loading.
@aleroot FYI
There was a problem hiding this comment.
I assume the special loading code should be in mlx-swift-lm, not here in mlx-swift. Is that correct? Is there anything in mlx-swift we should change to make that possible?
There was a problem hiding this comment.
Correct, in mlx-swift-lm. No, I don't think anything here needs to change, it was just something I noticed since there has been work in that area recently that may go counter to the distributed effort. It should be fine -- it may be a different load path.
| /// | ||
| /// - Parameters: | ||
| /// - backend: the backend to use, defaulting to ``Backend/any`` | ||
| /// - strict: if `true` report an error when no backend can be initialized |
There was a problem hiding this comment.
How is the error reported?
I wonder if this would be easier if we had two calls: one that throws and one that does not?
There was a problem hiding this comment.
split and initialize now throw the MLX error. I didn't add a second call.
| public func shardLinear( | ||
| _ layer: Linear, sharding: ShardingType, segments: Segments = .count(1), | ||
| group: MLXDistributed.Group? = nil | ||
| ) -> Module { |
There was a problem hiding this comment.
See the question below on AllToShardedLinear -- this probably needs to return something that can be called. A plain Module type doesn't have callAsFunction()
There was a problem hiding this comment.
shardLinear now returns Linear
xcode/MLX.xcodeproj keeps its own list of Cmlx sources, separate from Package.swift. Enabling ring only in Package.swift left the Xcode project compiling the no_ring.cpp stub, so isAvailable(.ring) was false there and testRingIsAvailable failed in the xcodeproj CI job. Exclude no_ring.cpp instead of ring.cpp, matching Package.swift. The test files themselves needed no change: Tests/MLXTests is a synchronized folder, so the Xcode project already builds and runs them. Co-Authored-By: Claude Opus 5 <[email protected]>
Remove AllToShardedLinear, ShardedToAllLinear, shardLinear, shardInPlace, sumGradients and averageGradients. They are not ready to merge: - QuantizedLinear is a Linear subclass, so shardLinear and the Linear initializers accept one, copy its packed uint32 weight, drop its scales and biases, and fail in the first forward pass. Python dispatches quantized layers to QuantizedAllToShardedLinear and QuantizedShardedToAllLinear instead. - The layers are not Linear subclasses, so update(modules:) cannot swap them into a model that declares `@ModuleInfo var proj: Linear`, which is how the mlx-swift-lm models declare their projections. QuantizedLinear can be swapped in because it is one. - shardLinear returns Module, which has no callAsFunction, so the result has to be cast before it can be called. - Python's sharded_load shards a lazily loaded model before evaluating it, so no process materializes the full weights. How that maps onto model loading in Swift has not been worked out. They return in a separate PR together with an mlx-swift-lm prototype that exercises them. This PR keeps the MLXDistributed API and the ring backend. Co-Authored-By: Claude Opus 5 <[email protected]>
initialize and split fail as soon as they are called, so report failure by throwing, as loadArrays does, instead of returning an optional. The optional gave callers nothing to check. Outside withError an MLX error terminates the process before nil is returned, and inside withError the error is rethrown when the block exits, so a caller never sees nil either way. globalGroup, the non-optional convenience, trapped when initialization failed -- even inside withError -- and a non-strict initialize does fail when a backend is configured but cannot form its group, e.g. when MLX_HOSTFILE names a file that does not exist. The collectives stay non-throwing. They are lazy, so communication and most of its failures happen at evaluation, where checkedEval reports them. Also document that MLX caches each backend's group, including the size one fallback of a non-strict call, so a later strict call for that backend returns the cached group instead of throwing. Co-Authored-By: Claude Opus 5 <[email protected]>
The ring test only worked when run by xctest directly. Under xcodebuild test the spawned rank inherited XCTest's session environment and waited for Xcode instead of running the test, while rank 0 waited for it to connect, forever. - Spawn ranks without XCTest's session variables, and mark them with a variable of their own instead of treating any MLX_RANK as a spawned rank. - Add a watchdog: if a spawned rank exits with an error, or the ranks do not finish within two minutes, terminate them and exit with a failure instead of hanging. - Use three ranks, so the left and right neighbors of a rank are different processes, and send in both directions. - Port the reduction coverage of the Python distributed tests: allSum, allMax and allMin over seven types and sizes up to 1024x1024, which exercises the ring's chunked transfers. Also drop the claim that the Python distributed tests are excluded from CI. MLX runs them with eight ranks on macOS and Linux. Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
DistributedRingTests is skipped unless MLX_TEST_DISTRIBUTED=1 because it starts processes and opens loopback sockets, so without this step CI never tests a group larger than one. It takes about ten seconds. MLX runs its ring tests in CI as well, with eight ranks. Co-Authored-By: Claude Opus 5 <[email protected]>
Glibc types SOCK_STREAM as an enum rather than the Int32 that socket() takes, and the socket calls need Glibc imported. The Linux CI jobs build with CMake, which does not build the tests, so this only appears in a swift test run on Linux. Co-Authored-By: Claude Opus 5 <[email protected]>
They default to the CPU stream, where the ring, JACCL and MPI backends communicate. NCCL, which only exists in a CUDA build, communicates on the GPU and needs stream: .gpu, so say that in the MLXDistributed docs rather than only in a comment. Co-Authored-By: Claude Opus 5 <[email protected]>
The layers this PR removed could not be used: a model declares its projections as `@ModuleInfo var proj: Linear`, and update(modules:) only accepts a module of that type, so a plain Module never fit. They also accepted a QuantizedLinear -- which in Swift is a Linear -- copied its packed uint32 weight into a float layer, dropped the scales and biases, and failed in addmm on the first forward pass. - AllToShardedLinear and ShardedToAllLinear subclass Linear, so a model can swap them in and callers can call the result. - Add QuantizedAllToShardedLinear and QuantizedShardedToAllLinear, the two classes Python has and this port was missing. They subclass QuantizedLinear and use quantizedMM, and the sharded-to-all one applies the bias after the reduction rather than to its own partial product. - shardLinear returns Linear and matches QuantizedLinear before Linear, since the first is a subclass of the second. - Sharding the input of a quantized layer splits the packed dimension, so reject a split that would cut a quantization group. Python validates only the group size. - Override toQuantized on all four, so quantizing a model after sharding keeps the communication instead of silently replacing the layers with plain QuantizedLinear. Failing to form a group now throws rather than trapping, following initialize, so the initializers, shardInPlace and averageGradients throw. Co-Authored-By: Claude Opus 5 <[email protected]>
The ring test carried the process handling itself: reserving loopback ports, writing the hostfile, re-executing the bundle as each rank with XCTest's session variables removed, and the watchdog. Move it to DistributedHarness so other tests can ask for ranks, with the rank count as a parameter. A process can only join one ring because MLX caches the group, so the harness now skips a second body in the same process with an explanation instead of letting it hang against the ring the first one built. Co-Authored-By: Claude Opus 5 <[email protected]>
This is the test that was missing. Python shards a Linear and its quantized version in both directions, compares against the unsharded layer, and checks the gradients of a four layer model; nothing equivalent existed here, which is why a quantized layer could be sharded into garbage without any test noticing. The body runs twice: in a single process, where sharding degenerates but the layers are still built and run, and across four ranks, where each one holds a different slice. The single process half runs in ordinary CI -- with the quantized dispatch disabled it fails there, which is where this bug should have been caught. Co-Authored-By: Claude Opus 5 <[email protected]>
test_groups, test_send_recv and test_all_gather_vjp had no Swift equivalent, and the reductions and gathers covered seven of the ten dtypes the Python tests use. int16, uint16 and complex64 come from the ring specific extras. - Every rank sends to its right neighbor and receives from its left one, even ranks sending first, as Python does, rather than one pair at a time. - The harness asserts the group has the size the test asked for. A fallback group of one would let every assertion about sharding pass without proving anything. - The reductions and the transfers report how many dtype and shape combinations they ran, so the log shows the matrix was really covered. Co-Authored-By: Claude Opus 5 <[email protected]>
Python's shard_inplace takes a callable that picks the axis for each parameter, while the Swift version only offered the two standard shardings, so the test could not be written at all. Add the general form and keep the simple one as a wrapper around it. The test shards a model of convolutions -- output channels in the even layers, input channels in the odd ones, which aggregate -- and compares against the unsharded model. The layer tests now live in DistributedNNTests, one file mirroring the Python one: a single process class that runs in ordinary CI and a four rank class behind MLX_TEST_DISTRIBUTED. Co-Authored-By: Claude Opus 5 <[email protected]>
test_average_gradients and test_clip_grad_norm_sharded had no Swift equivalent, and clip_grad_norm_sharded itself was never ported. It is ten lines over allSum, the sharded counterpart of clipGradNorm: no process holds the whole gradient, so the local squared norms are summed across the group before anything is rescaled. Python counts the all_sum calls by replacing mx.distributed.all_sum, which Swift cannot do, so the averaging test checks what that counting was there to protect: every rank contributes its own value, every batching threshold produces the same average, and arrays of mixed types keep their dtype. Writing it turned up a constraint worth stating: the collectives are lazy, so every process has to evaluate them in the same order or they exchange mismatched buffers and report nothing. Iterating a Dictionary does not guarantee that, since its order differs from process to process. MLXDistributed now documents it. Co-Authored-By: Claude Opus 5 <[email protected]>
- A sharded-to-all layer adds its bias after the reduction, so every process has to hold the same one. It was drawn at random, and nothing keeps the generators of separate processes in step, so the layer could quietly produce a different result in each. Use zeros, as Python's quantized flavor does; its float one has the same problem. - A dimension can divide by the group size while one of its segments does not. split(parts:) calls fatalError in that case, so a throwing API could kill the process; check each segment and throw instead. - A quantized layer packs its inputs in the weight and groups them in the scales, so one logical segment index lands at a different position in each. Express the segments as fractions of the logical dimension when sharding the input of a quantized layer. The regression test for the bias seeds each process differently on purpose. With the same seed everywhere every process draws the same "random" bias and the test cannot fail -- which is exactly how the first version of it passed against the bug. Co-Authored-By: Claude Opus 5 <[email protected]>
Comparing the ports assertion by assertion turned up three ways they were weaker than the tests they came from: - The comparisons used rtol 1e-2, where the Python ring suite uses atol 1e-6 and rtol 1e-4, and compares a rank's own slice with plain allclose. A sharded layer could have been noticeably wrong and still passed. - test_shard_linear also covers a non affine mode: it checks that mxfp8 survives sharding and carries no quantization biases. That half was missing. - test_quantized_sharded_linear_construction, in the Python nn tests, sweeps bit widths 2 to 8, which pack different numbers of values per word. Only the default 4 was covered here. The averaging test now uses a different shape and value per gradient. Python asserts how many all_sum calls the batching makes, which Swift cannot observe; ten identical arrays made the concatenate, reduce and split round trip untestable, and reversing the split in it went unnoticed. Co-Authored-By: Claude Opus 5 <[email protected]>
Nothing was missing to do this: GPU.resetPeakMemory() already wraps mlx_reset_peak_memory. The test had simply not been ported. It runs only across ranks. In a group of one MLX returns the input unchanged, so there is no collective result to donate and the input is still live, which is why Python only ever runs it under a launcher. The port also has to release the first result before measuring the second, the way Python's rebinding of one name does. Holding it adds its buffer to the peak, and the comparison fails for a reason that has nothing to do with donation. Co-Authored-By: Claude Opus 5 <[email protected]>
Every Python distributed test that runs on the ring backend is ported, but none of them passes segments, gives a quantized layer to the float classes or checks an error, so these went unnoticed: - AllToShardedLinear and ShardedToAllLinear accept any Linear, and a QuantizedLinear is one. They kept its packed uint32 weight as a float weight, dropped the scales and failed in the first forward pass. Both initializers now throw ShardingError.quantizedLayer. shardLinear already picks the quantized layers. - .count(n) went straight to split(parts:), which calls fatalError when the dimension does not divide. Segments now works out its boundaries first and throws ShardingError.invalidSegments, in a group of one as well. - QuantizedShardedToAllLinear turned segment indices into Double fractions of the input dimension. 3840 of 5632 inputs came to 479.99999999999994 packed words and 59.99999999999999 groups, which truncate to the wrong positions, so a valid boundary was rejected. A boundary inside a quantization group, such as 272, was accepted and paired weights with the wrong scales. Boundaries now scale in integer arithmetic, and every segment has to hold whole quantization groups on every process. - The documentation of AllToShardedLinear.toQuantized linked quantize(model:groupSize:bits:predicate:), which only exists on QuantizedLinear, so DocC could not resolve it. The averageGradients test claimed that a limit of 4 * 50 bytes splits the gradients into batches, but gradients of 1 to 10 float32 values only reach 200 bytes at the last one, so every limit formed a single batch. It now uses ten gradients of 40 bytes each, as Python does, and checks the batches through groupBySize, the counterpart of Python's _group_by_size, where Python counts its all_sum calls. Run against the previous code, the new tests fail in a single process (the quantized layers, .count(3) and the boundary at 272) and across four ranks (the boundary at 3840 as well). Co-Authored-By: Claude Opus 5 <[email protected]>
A model's shard method replaces its Linear projections with sharded layers through update(modules:), the way quantization swaps in QuantizedLinear. That depends on the sharded layers being Linear subclasses, and nothing tested it. The new test installs an all-to-sharded and a sharded-to-all layer into a block that declares both projections as Linear, with verify: .all, for a float block and for one quantized first. The sharded block has to reproduce the unsharded output, in a single process and across four ranks. A control first checks that installing a module that is not a Linear is refused, so the check can fail. Co-Authored-By: Claude Opus 5 <[email protected]>
davidkoski
left a comment
There was a problem hiding this comment.
Thank you so much for this contribution! This is ready to go!
Will you file issues on mlx-c for the missing functionality?
|
@davidkoski Yes, I'll file those and at the same time open one or more draft PRs here for the remaining functionality. Even after mlx-c is updated, though, I won’t be able to test JACCL until my new hardware arrives. I saw in another thread that you’ll be out of the office started tomorrow. I should be ready to test everything end to end by the time you’re back, so we can pick this up then (unless someone else with Thunderbolt 5–equipped Mac Studios can help test and iterate in the meantime). |
* fix(Device): resolve initial default from the MLX C++ core, not hard-coded GPU (ml-explore#422) Closes ml-explore#395. `_resolveGlobalDefaultDevice()` returned `.gpu` whenever no explicit `setDefault(...)` had been called, so on a CPU-only host (Linux with no Metal / no CUDA) `Device.defaultDevice()` and `StreamOrDevice.default` both returned a device that simply doesn't exist, causing every subsequent op routed to the default stream to fail. The deprecated `Device.init()` already shows the right pattern: call `mlx_get_default_device()` and let the C++ core pick the device its build supports. Use that path instead of the hard-coded `.gpu`. * Allowing SPM to compile on Linux with CUDA (ml-explore#413) * Support CUDA compilation with SPM * Enable CUDA by default on Linux * Add code generation capabilities in CudaBuild plugin * Use `tools/update-mlx.sh` to generate `cuda_jit_sources.h` * Add MultiOptimizer (port from Python mlx.optimizers) (ml-explore#431) Port `mlx.optimizers.MultiOptimizer` to Swift: a meta-optimizer that routes each model parameter to the first sub-optimizer whose filter predicate matches its flattened key path, with the last optimizer acting as the unconditioned fallback. This allows using different optimizers or hyperparameters for different subsets of a model's weights. `update(model:gradients:)` partitions the flattened gradient tree by first-matching filter and delegates each subset to the corresponding child optimizer; `innerState()` surfaces the children's state. It conforms to the `Optimizer` protocol directly since it holds no per-parameter state of its own. Closes ml-explore#228 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * Add MLXArray and DType extensions (ml-explore#429) * Add MLXArray and DType extensions * Simplify magic numbers * Return MLXArray instead of Double * Add Muon optimizer (port from Python mlx.optimizers) (ml-explore#432) Port `mlx.optimizers.Muon` (MomentUm Orthogonalized by Newton-Schulz): a momentum optimizer that orthogonalizes the update for >=2D parameters via a 5-step quintic Newton-Schulz iteration, scaling the learning rate by sqrt(max(1, rows/cols)). 0D/1D parameters fall back to a plain momentum/Nesterov update. Mirrors the reference (weight decay, Nesterov default on, ns_steps=5). Tests pin the 1D momentum/Nesterov math exactly and exercise the 2D orthogonalization path (shape preserved, finite, parameter moved). Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * Add learning-rate schedules (port from Python mlx.optimizers.schedulers) (ml-explore#433) Port the mlx.optimizers schedule functions to Swift: exponentialDecay, stepDecay, cosineDecay, linearSchedule, and joinSchedules. Each returns a (Int) -> Float mapping a step to a learning rate, composing with the mutable `learningRate` exposed by the optimizers (assign optimizer.learningRate = schedule(step) each step). mlx-swift previously had no LR schedules. Tests pin exact values against the reference docstring examples. Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * Move .complex64 to .float32 (ml-explore#434) * guard use of Process (ml-explore#437) - does not build on iOS, etc. - fix ml-explore#436 * Add fp8 conversion utilities (ml-explore#435) * Add FP8 conversion utilities. * build iOS in CI (ml-explore#440) - add an iOS build in CI to catch iOS-only build breaks - move the docs build into the same macOS runner * Add global scale support to quantized layers (ml-explore#426) * Add global scale support to quantized layers Store optional globalScale on QuantizedLinear and QuantizedEmbedding so nvfp4 weights can preserve the scale needed by lower-level MLX quantize/dequantize operations. Forward the scale when creating or dequantizing weights, add a direct pre-quantized QuantizedEmbedding initializer to match QuantizedLinear, and guard global-scale execution paths on Metal because MLX does not support globalScale dequantization there. Add focused tests for the new layer state and parameter exposure without broadening the generic quantization API surface. * Keep nvfp4 global scale on the quantized path for Metal Since MLX encodes nvfp4 group scales pre-multiplied by (448 * 6) / globalScale, the global scale factors out of dequantization linearly. Exploit this by always running quantizedMM (supported on Metal without globalScale) and applying globalScale / (448 * 6) to the output, instead of dequantizing the full weight and falling back to a plain matmul. This keeps weights quantized end-to-end on all backends, removes the dequantizedWeight fallback from QuantizedLinear and QuantizedEmbedding, and applies the scale before the bias add so the bias is unaffected. Add Metal tests that validate the GPU quantized path against CPU dequantized(globalScale:) references for QuantizedLinear (matmul + bias) and QuantizedEmbedding (asLinear and index lookup). * Fix FinalizerCaptureState leak in MLXArray(rawPointer:_:dtype:finalizer:) (ml-explore#448) The initializer retains a box holding the finalizer closure and hands it to mlx as an opaque payload, but `finalizerTrampoline` read it back with `takeUnretainedValue`, which never consumes the `passRetained` +1. The local `free(ptr:)` that would have balanced it was never passed anywhere — only the trampoline is — so it was dead code and the box leaked. The box owns the closure, so the closure's captures leak with it. The initializer's own documented example captures an `IOSurface` and comments that it "implicitly releases it when it returns"; it did not, and the surface was pinned for the lifetime of the process. `testIOSurface` covers the path but only prints, so nothing caught it. `takeRetainedValue` consumes the +1 exactly once. mlx-c documents the dtor as "Callback for when the buffer is no longer needed" and calls it once per buffer, and the trampoline has exactly one caller, so a single consume is correct. Removes the dead `free(ptr:)`. Adds a differential regression test: with the bug the finalizer runs but its captures are never released (witness releases 0); with the fix they are (1). The test drains mlx's allocator cache first, since a freed buffer's dtor is not guaranteed to have run at scope exit, and uses lock-guarded counters because mlx may invoke the dtor from its own thread. Full suite: 534 tests, 0 failures. Co-authored-by: Fred Jura <[email protected]> * Derive the jit-source lists in update-mlx.sh instead of hand-listing them (ml-explore#445) `tools/update-mlx.sh` hand-tracked two lists that mlx's own CMake derives, so each one silently went stale whenever the vendored mlx submodule gained a jit source. The CUDA `MLX_JIT_SOURCES` argument named 16 `device/` headers explicitly, where `mlx/backend/cuda/CMakeLists.txt` uses `file(GLOB)` over `device/*.h` and `device/*.cuh`. A bump that adds one regenerated a `cuda_jit_sources.h` missing its array, failing later as `use of undeclared identifier 'jit_source_*'`: mlx v0.31.2 needs 17 and v0.32.0 needs 22, against the 16 the frozen list produced. The Metal step named 46 `make` targets explicitly, where `mlx/backend/metal/CMakeLists.txt` declares them via `make_jit_source()`. A bump that adds one left `jit/includes.h` declaring a `mlx::core::metal::<name>()` that no generated source defined, i.e. an undefined symbol at link time on macOS and iOS: v0.31.2 declares 47 and v0.32.0 declares 48, against the same 46. Both lists are now derived from the vendored tree at run time. Against the currently pinned mlx (v0.31.1) the derived values are identical to the removed literals, and the regenerated `cuda_jit_sources.h` is byte-for-byte identical to the committed one, so this is a no-op at the current pin. Each derivation is guarded: with `set -e` an empty result would not fail on its own, and bare `make` with no targets would quietly build `all` instead. * Improve CUDA NVCC spawn performance (on Linux) (ml-explore#451) * Reap encuda's child processes with waitpid instead of polling isRunning `waitUntilExitWorkaround()` polled `Process.isRunning` in a 50ms sleep loop, added because `waitUntilExit()` "never returns" on aarch64 Linux. It did not fix that hang -- `isRunning` reads the same Foundation bookkeeping that stalls, so the workaround only changed a blocked call into an infinite sleep loop. Observed during a parallel SwiftPM build of the CUDA backend for linux/arm64 (aarch64-unknown-linux-gnu, CUDA 13, sm_121): `nvcc` finishes and writes its output in full, then becomes a zombie that is never reaped, while `encuda-tool` spins in `hrtimer_nanosleep` holding a completed 15MB transpiled .cpp on disk. Invoking encuda directly on the same file with identical arguments completes in 2-3 seconds, so the work itself is fine -- the process simply never notices the child finished. It is load-dependent: `--jobs 2` transpiled all 96 .cu files without incident, while an unconstrained build (SwiftPM defaults to every core) deadlocked. That is consistent with pipe file descriptors leaking between concurrently spawned siblings -- the hung `encuda-tool` held both the read and the write end of the same pipes, so no reader could ever see EOF. `waitpid` answers the only question this code has: did the child exit, and with what status. It does not depend on Foundation's reaper, and it collects the zombie. On ECHILD -- Foundation's own reaper winning the race -- it falls back to `terminationStatus`, which is authoritative in exactly that case. Exit status is decoded without the C macros, which Swift does not import: the low 7 bits carry the terminating signal and the next 8 the exit code, an encoding shared by Linux and Darwin. Signals are reported as `128 + signal`, following the shell convention, so a killed compiler is still a non-zero failure rather than a silent success. Verified on macOS: exit codes 0, 7 and 42 round-trip exactly; SIGKILL and SIGTERM report 137 and 143; no reapable child remains afterwards. The aarch64 Linux deadlock itself has not been reproduced locally -- it needs a CUDA toolchain and a parallel build to trigger -- so this is a fix for a diagnosed root cause rather than one observed to clear the symptom. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01K1rzxACJqmxVqgRsa4xj3R * Don't read terminationStatus before Foundation has published it The waitpid change cleared the deadlock it was written for -- an unconstrained SwiftPM build of mlx's CUDA backend for aarch64 Linux (CUDA 13.2, sm_121, 16 jobs) now runs through the transpile step at full speed instead of stalling forever on a zombie nvcc. But it replaced the hang with a crash. `waitpid` and Foundation's own reaper thread race for every child. When Foundation wins, our waitpid returns ECHILD and the fallback read `terminationStatus` immediately. That is not safe: Foundation publishes the result in two steps, and reading the status inside the window before `isRunning` goes false traps the process. *** Program crashed: System trap at 0x0000ffff90b6fb50 *** Thread 0 "encuda-tool" crashed: 0 Process.terminationStatus.getter + 80 in libFoundation.so 1 Process.waitForExitStatus() + 107 in encuda-tool at Source/Encuda/encuda-utils.swift:73:24 2 Encuda.Compile.run() + 1883 in encuda-tool Roughly one transpile in 250 died this way, at a different .cu file each run. The build failure it produces is unusually opaque: the crash report goes to the transpiler's own output, so `swift build` exits 1 with no diagnostic at all, and the last thing in the log is an ordinary "Compiling scan.cu to scan.cpp" progress line. So wait for `isRunning` to clear before reading the status -- but on a deadline, since an unbounded wait is the hang this function exists to avoid. On expiry it reports 254 rather than trapping or spinning: the caller turns any non-zero status into a build error, which is diagnosable, and neither a trap nor a hang is. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RdegWrNm5PKBqeXdkgmn9Q --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> * Condition CUDA build plugin on Linux host (ml-explore#447) * Nested initializers (ml-explore#456) * nested initializers * [CUDA] Build the CUDA argument lists in steps (ml-explore#442) Three argument lists in the CUDA build are assembled as long `+` chains that the type checker struggles with. On a Swift 6.2 toolchain they exceed its budget outright: encuda-compile.swift:66:17: error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions plugin.swift:172:13: error: the compiler is unable to type-check this expression in reasonable time; ... Appends into local arrays instead, which is behaviourally identical and is what the diagnostic suggests. The plugin's two chains move into `compileArguments` and `linkArguments` helpers to keep `createBuildCommands` readable, and adding a further argument to either list no longer risks tipping the type checker over. Note this does *not* make the package buildable on Swift 6.2: SwiftPM 6.2 ignores non-Swift files produced by a build-tool plugin ("Only Swift is supported for generated plugin source files at this time"), so every generated .cpp is dropped and the CUDA symbols go undefined at link time. The 6.3 floor is load-bearing. This is purely a type-check-cost and readability change. Co-authored-by: Claude Opus 5 <[email protected]> * Fix a deadlock between `CompiledFunction.lock` and `evalLock`, and a data race on the compiler cache (ml-explore#461) * add a deterministic repro for the compile/eval lock-order inversion CompiledFunction.call takes the per-instance lock (ml-explore#226) and then, in innerCall, the process-global evalLock (ml-explore#339), holding it across mlx_closure_apply. On a cold cache entry that runs compile_trace, which calls back into the Swift body being compiled; if that body calls another compiled function -- every MLXNN activation does, e.g. silu calls the file-scope compiledSilu -- the nested call takes a second per-instance lock while evalLock is held. thread H: L_cf(outer) -> evalLock -> wants L_cf(shared) thread W: L_cf(shared) -> wants evalLock The orders are inverted and the two threads deadlock permanently. CompileLockRepro owns its threads, uses fresh compile() results per round so the compiler cache is cold, signals from inside the traced body so W is ordered after H enters the trace, and holds the window open with a usleep in that body. A per-round deadline turns the hang into a hard failure. It is its own executable because a wedged round cannot be recovered and would take a shared test process down with it. Co-Authored-By: Claude Fable 5 <[email protected]> * take evalLock outermost in CompiledFunction.call Establishes one global lock order, evalLock -> CompiledFunction.lock, so the inversion described in the previous commit cannot form. The reverse order is not avoidable on its own: the trace has to run under evalLock (the compiler cache is an unguarded global and the tracing flag is a plain static, not thread_local), the trace calls back into Swift, and the traced body calls other compiled functions -- every MLXNN activation is a file-scope CompiledFunction. So evalLock -> lock happens regardless. The only fix available is to make it the *only* order, which is what taking evalLock at the top of call(_:) does. evalLock is recursive, so the nested acquisition from inside a trace is free. innerCall already took evalLock before doing any real work and held it through mlx_closure_apply, so this widens the held region only by the state gathering and closure creation at the top of innerCall. lock becomes an NSRecursiveLock so that a compiled function whose body re-enters that same compiled function on one thread no longer self- deadlocks on a non-recursive NSLock. CompileLockRepro: 20/20 rounds pass; without this it wedges on round 1. Co-Authored-By: Claude Fable 5 <[email protected]> * skip the per-instance lock when a compiled function has no state ml-explore#226 added CompiledFunction.lock to guard the observed state. The _updateInternal swaps in innerCall are the only mutation of anything reachable from self -- every other stored property is let, and id is written once at init -- so when inputs and outputs are both empty the lock has nothing to guard. With the previous commit evalLock is held for the whole call, which already serializes the compiler cache and every other caller, so dropping the acquisition changes nothing observable. Optional on top of the previous commit; the deadlock is fixed without it. It removes a mutex round-trip from the hot path of the common case: every compiled function in MLXNN is stateless. Co-Authored-By: Claude Fable 5 <[email protected]> * check the evalLock -> CompiledFunction.lock ordering in debug builds A passing CompileLockRepro only shows that the race did not fire, so assert the ordering itself. evalLock is recursive, and a successful try() on a recursive lock cannot distinguish 'this thread owns it' from 'nobody owns it', so ownership has to be recorded explicitly. withEvalLock is now the single choke point for evalLock; in debug builds it keeps a per-thread depth (pthread-specific, so the bookkeeping itself needs no lock -- it runs while holding evalLock). CompiledFunction acquires its per-instance lock through withInstanceLock, which requires that depth to be non-zero. Moving the per-instance lock back outside evalLock -- the shape that deadlocks -- trips it on the first compiled call, with no race to lose. All of it compiles out of release builds. CompileLockOrderingTests covers: that the bookkeeping can report 'not held' and is per thread (otherwise a violation count of zero would prove nothing), that a stateful compiled function really reaches the checked acquisition, and the nested case where one compiled function is called from inside another's trace. Verified by inverting the order locally: the assertion fires immediately with 'CompiledFunction.lock was acquired without holding evalLock'. Co-Authored-By: Claude Fable 5 <[email protected]> * erase the compiler cache under evalLock in CompiledFunction.deinit `mlx_detail_compile_erase` is `compiler_cache().erase(fun_id)` on the process-global `mlx::core::detail::CompilerCache`, which has no synchronization of its own. `CompiledFunction.deinit` called it with no lock held, so it could run concurrently with another thread's `CompilerCache::find` -- `cache_[fun_id]`, which can itself insert and rehash, followed by `entries.push_back` -- and with the whole trace that fills in the entry `find` returned a reference to. Unlike the lock-order inversion fixed in the preceding commits, this is a data race rather than a deadlock, and it predates them. Every other use of that cache already happens under `evalLock`, so the erase takes it too. `evalLock` is recursive, so a deinit that fires on a thread already inside a compiled call or an `eval` -- a traced body dropping the last reference to some other compiled function, for instance -- re-enters for free, and a thread holding a `CompiledFunction.lock` holds `evalLock` already, so no new edge is added to the lock graph. A deinit on a thread with no MLX lock simply waits for the call in flight. Nothing in the library hands a `CompiledFunction` reference to a back-end worker thread, so this erase can never be what an `evalLock` holder is waiting for. The erase stays synchronous rather than deferred: `id` is the object's own address, so a later `CompiledFunction` can be allocated at the same address and receive the same id, and a deferred erase could delete that new function's entries. Two tests. The first is the interleaving itself: one thread is parked inside `compile_trace` holding `evalLock` (it signals a semaphore from inside the traced body), the other drops the last reference to a warmed compiled function at that instant, and the erase is required to complete only after the first thread has left the traced body -- which is what serialization against `find` means. The second runs a stream of erases against a stream of cold compiles, covering the insert-and-rehash window too, and checks the results are still correct. Both assert the debug counters so a pass cannot be vacuous. * Fix StreamOrDevice.stream(_:) ignoring its argument (ml-explore#463) StreamOrDevice.stream(_:) discarded the stream it was given and returned the default stream of the default device instead, so operations that passed an explicit stream silently ran somewhere else. Return the given stream and add a regression test. * test Module parameters and compile (ml-explore#465) * test Module parameters and compile * update for mlx v0.32.2 (ml-explore#450) * update for mlx v0.32.0 mlx v0.32.2 - carry `Source/Cmlx/mlx.patch` for mlx's `Device::operator<` / `Stream::operator<`, which are not strict weak orderings and now run on every `eval()` via `std::set<Stream>`. libc++ aborts on them under the Xcode 27 SDK. Still broken upstream in v0.32.0 and on main, no issue filed. Applied by `tools/patch-mlx.sh` from `update-mlx.sh` and CI, since `git submodule update` restores a pristine checkout. - streams became thread affine in v0.31.2, which broke the multi-threaded tests. Adopt mlx's `new_thread_unsafe_stream` (added upstream for language bindings that lock themselves -- mlx-swift serializes on `evalLock`) via a small C shim, as mlx-c does not bind it. - FFT ops gained a `norm` parameter: add `FFTNorm` and thread it through, plus `fftfreq`/`rfftfreq`. - wrap the new reducing slice-updates in `ArrayAtIndices` and add `exportToDot`/`graphDescription`/`NodeNamer`. - fix `SEEK_END` in the in-memory IO stream -- it computed from the read position rather than the end of the buffer, which v0.32.0's `load_safetensors` size check exposed. - route `cpu/jit_compiler.cpp` through `mlx-conditional`: it shells out via `std::system()`, unavailable on iOS. - `gemv` is JIT compiled as of v0.32.0, so drop `gemv.metal` from the metallib in `fix-metal-includes.sh`. The jit source lists themselves no longer need touching -- ml-explore#445 derives them from the vendored tree, and the derived sets match what a hand-bump would have produced here (48 Metal targets, 22 CUDA sources). * disable cuda runs for now -- need clear_streams exposed in mlx-c --------- Co-authored-by: David Koski <[email protected]> * Fix wired-memory ticket lifecycle during cancellation (ml-explore#471) * Fix condition typo (ml-explore#473) * fix(ops): fix convolve padRight for even-sized kernels in same mode (ml-explore#466) (ml-explore#467) * Add countNonzero to the Swift API (ml-explore#479) * Add countNonzero + docs * Add tests * Distributed support (ml-explore#482) Add distributed communication and sharded neural network layers Port mlx.core.distributed and distributed layer primitives to Swift: - Backend & Primitives: - Enable the ring distributed backend (CPU socket-based communication). - Add MLXDistributed.Group with rank/size/split and 8 communication primitives (allSum, allGather, send, recv, etc.). - Default distributed operations to the CPU stream. - Make initialize and split throw on failure. - Layers & Optimization: - Add AllToShardedLinear, ShardedToAllLinear, and quantized counterparts (subclassing Linear / QuantizedLinear for seamless model replacement). - Implement shardLinear, shardInPlace (supporting predicate sharding), sumGradients, averageGradients, and clipGradNormSharded. - Ensure correct boundary checks and integer scaling for quantized layers. - Testing & Infrastructure: - Add a reusable multi-process test harness (DistributedHarness) for spawning local ranks via loopback sockets. - Port Python ring tests (collectives, dtypes, donation, send/recv). - Port layer, predicate sharding, and gradient tests; enable in CI. * add thin logging shim (ml-explore#484) * add thin logging shim * patch for Cuda builds (ml-explore#478) * patch for Cuda builds - local apply of ml-explore/mlx#4480 + other shutdown items from ml-explore/mlx#4506 - fixes crash on exit for cuda builds when using cmake * pool Streams, fix Device inheritance (ml-explore#472) * pool Streams, fix Device inheritance - see ml-explore/mlx#2118 - Streams are finite and seem to leak OS/Metal resources - implements a pool to reuse Streams -- withNewDefaultStream is fully usable - much more care is taken with GPU devices - using index != 0 now works in all cases - and inherits properly when creating new streams Co-authored-by: Nick Henderson <[email protected]> * replace and improve integration tests (ml-explore#477) * replace and improve integration tests - previously we used a python script to generate swift code and check output against known values from mlx (python) - this is replaced with a new and more powerful script (claude rewrite) - much more integration test coverage and tools to examine that - fixes per problems found by new integration tests - linspace output type, add dtype override - linspace default output type is float32 (matches python) - convolve .same padding side matches python (padRight) - nanToNum default for +/- infinity honors optionals (mlx defaults) - tensorDot axes default 1 -> 2 (matches python) - MLXNN Pooling padWidths matches python - MLXNN Alibi slop function matches python - MLXNN GRU apply bias to match python - MLXNN Lion optimizer default beta matches python - MLXNN Adafactor moving average matches python - MLXNN Muon zero power newton shulz matches python * fix linspace disambiguation * split integration tests into their own test target -- we need to run them with TF32 disabled so we can guarantee consistent results on NAX vs non NAX hardware Co-authored-by: Nick Henderson <[email protected]> * Adapt data stream callbacks to the updated C binding contract --------- Co-authored-by: tsushanth <[email protected]> Co-authored-by: Gabriele Mondada <[email protected]> Co-authored-by: GoodOlClint <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Ronald Mannak <[email protected]> Co-authored-by: David Koski <[email protected]> Co-authored-by: Lucas Newman <[email protected]> Co-authored-by: Alessio Pollero <[email protected]> Co-authored-by: agerjura <[email protected]> Co-authored-by: Fred Jura <[email protected]> Co-authored-by: Joannis Orlandos <[email protected]> Co-authored-by: Dr. Thorsten Fuchs <[email protected]> Co-authored-by: Valentin Roussellet <[email protected]> Co-authored-by: DanielMercado60660 <[email protected]> Co-authored-by: Alessio Pollero <[email protected]> Co-authored-by: Charlie Le <[email protected]> Co-authored-by: David Koski <[email protected]> Co-authored-by: Lukas Zima <[email protected]> Co-authored-by: Shubhransh Gupta <[email protected]> Co-authored-by: Nick Henderson <[email protected]>
Proposed changes
Ports
mlx.core.distributedandmlx.nn.layers.distributedto Swift and enables the ring backend. Supersedes #371.MLXDistributed:initialize,Group(rank,size,split), the collectives, andsend/recv.initializeandsplitthrow. The collectives are lazy, so their errors surface throughcheckedEvalorwithError.AllToShardedLinear,ShardedToAllLinearand their quantized variants subclassLinearandQuantizedLinear, so a model can swap them in the way quantization does. AlsoshardLinear,shardInPlace,averageGradientsandclipGradNormSharded.Package.swiftand the Xcode project both build the ring backend.Not included: JACCL,
fully_shard, and adoption in mlx-swift-lm.Notes
stream: .gpu. mlx-c also lacks the JACCLall_gather_factoryinit andclear_backends().ReduceScatter::eval_cpuassertsinputs.size() == 0, so evaluatingsumScatteron the CPU stream aborts builds with assertions enabled. Reported upstream:Tests
The Python distributed tests that can run on the ring backend are ported.
DistributedTestsandDistributedNNTestsrun in a single process.DistributedRingTests(3 ranks) andDistributedNNRingTests(4 ranks) run over loopback whenMLX_TEST_DISTRIBUTED=1is set, each in its ownxctestrun:Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes