Repository navigation
feat(cli): support MLX distributed inference - #6845
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for distributed MLX inference and chat across multiple ranks. It adds environment-based detection of distributed launches, initializes MLX distributed groups, and implements a mechanism to share Python objects (such as chat turns) across ranks using mlx.core.distributed.all_sum. Additionally, it updates the CLI commands (chat and inference) to handle distributed contexts, silences non-zero ranks, and adds corresponding unit tests. The review feedback highlights a critical runtime issue in worker.py where Python int scalars are passed directly to mx.distributed.all_sum, which expects an mx.array and would raise a TypeError. Code suggestions were provided to wrap these integers in mx.array() and to update the corresponding test mocks to prevent test failures.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
Note
Copilot couldn't run its full agentic review because no GitHub Actions runner was available. Make sure your repository has a runner available to run Copilot's review, or add a copilot-setup-steps.yml file specifying one with the runs-on attribute. See the docs for more details.
Adds CLI + backend plumbing to run Unsloth inference/chat under mlx.launch with MLX distributed initialization, rank-aware output, and a small distributed object-broadcast channel for interactive chat turns.
Changes:
- Detect MLX distributed launch context (including some MPI env pairs) and silence nonzero ranks in CLI commands.
- Forward MLX distributed parallel mode + group into the MLX backend / worker via the subprocess orchestrator.
- Add distributed chat turn broadcast via a new
share_objectworker command, plus integration tests.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
unsloth_cli/tests/test_inference_chat.py |
Adds tests for launch detection, rank-aware output/drain behavior, and forwarding distributed flags into loaders. |
unsloth_cli/commands/inference.py |
Runs locally under mlx.launch, rejects MPI mode, ensures only rank 0 prints while other ranks consume streams. |
unsloth_cli/commands/chat.py |
Implements rank-aware interactive chat with turn broadcast and stdin draining on nonzero ranks; blocks compare for distributed MLX. |
unsloth_cli/_inference.py |
Implements launch-context detection helpers and a context manager to silence output on nonzero ranks; forwards mlx_distributed to backend loads. |
studio/backend/tests/test_mlx_inference_backend.py |
Adds tests ensuring distributed groups are forwarded into FastMLX loaders and worker share-object path works. |
studio/backend/routes/inference.py |
Rejects Studio HTTP loads under distributed MLX launcher contexts. |
studio/backend/core/inference/worker.py |
Forwards MLX distributed args into MLX backend loads and adds share_object command handling. |
studio/backend/core/inference/orchestrator.py |
Adds share_distributed_object API and forwards MLX distributed parallel mode into subprocess config. |
studio/backend/core/inference/mlx_inference.py |
Initializes/records distributed rank/size, validates parallel mode, and forwards group into FastMLX sharded loaders. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e5fee55432
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| distributed = getattr(mx, "distributed", None) | ||
| init = getattr(distributed, "init", None) if distributed is not None else None | ||
| if callable(init): | ||
| group = init() |
There was a problem hiding this comment.
Select the MLX backend explicitly for JACCL
With mlx.launch --backend jaccl, the launcher sets MLX_RANK, MLX_JACCL_COORDINATOR, and MLX_IBV_DEVICES but no MLX_HOSTFILE. Calling bare mx.distributed.init() uses MLX's default backend="any"; upstream MLX issue ml-explore/mlx#3442 shows this path can return a size-1 ring singleton before trying JACCL. In that supported non-MPI/JACCL context the worker logs singleton, loads the full model on every rank, and chat sharing degenerates to local None on nonzero ranks, so distributed inference does not actually run. Please derive and pass backend="jaccl" (and similarly explicit backends for the other launch envs) instead of relying on the default.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 89e77d8f5: _init_mlx_distributed() now detects the JACCL launch env (MLX_JACCL_COORDINATOR + MLX_IBV_DEVICES) and calls mx.distributed.init(backend = "jaccl"), with a TypeError fallback to bare init() for older MLX.
Resolve studio/backend/core/inference/mlx_inference.py: keep the distributed helpers (_init_mlx_distributed / _mlx_distributed_rank_size) alongside main's _make_mlx_presence_penalty_processor logits processor.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 451f8a3709
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| mx.eval(mx.distributed.all_sum(mx.array(0), group = group)) | ||
| shared = None | ||
| else: | ||
| data = mx.array(_encode_share_object(obj), dtype = mx.uint8) |
There was a problem hiding this comment.
Encode shared objects as a uint8 sequence
In distributed unsloth chat, rank 0 reaches this path for every non-empty user turn, but _encode_share_object(obj) returns a Python bytes object and real MLX array initialization does not treat bytes as a numeric sequence. That makes the share_object command fail before rank 0 enters the payload collective while the peer ranks are already waiting for the matching all_sum, so chat turn broadcast errors or hangs as soon as the user sends a prompt; convert the bytes to a list/bytearray/memoryview-backed uint8 array before calling mx.array.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intentionally not changing this one: I could not reproduce the failure on MLX 0.31.2. mx.array(b"...", dtype = mx.uint8) works locally, and upstream MLX has coverage for mx.array(b"Hello") producing a uint8 array. Keeping the PR smaller and leaving the existing bytes path unchanged.
| if size <= 1: | ||
| logger.warning( | ||
| "MLX distributed launch requested but initialized singleton " | ||
| "group; continuing without distributed sharding" |
There was a problem hiding this comment.
Fail when requested MLX distributed initializes singleton
When mx.distributed.init() falls back to a singleton despite mlx_distributed being requested (for example a bad hostfile/backend setup), the parent CLI still uses distributed rank behavior while this worker records world_size=1. In chat, nonzero ranks then get None back from share_object and spin forever instead of receiving rank-0 turns, and one-shot inference silently runs an unsharded full model per rank; this should fail the load rather than continue without a distributed group.
Useful? React with 👍 / 👎.
|
Thanks for this. The distributed-inference merge conflicts are resolved (rebased on main). Two real issues to fix before merge, both only reachable on real multi-rank hardware so the mocked-mlx tests miss them:
The other Codex items on this PR are below the bar (handled in the inline reactions). |
|
Status on the two maintainer-confirmed MLX distributed issues:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89e77d8f59
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7396d09a9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
b7396d0 to
8f6d7fa
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8f6d7fa42c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if isinstance(chunk, str) and chunk.startswith(_STREAMED_ERROR_PREFIX): | ||
| raise RuntimeError(chunk[len(_STREAMED_ERROR_PREFIX) :].strip() or "Unknown error") |
There was a problem hiding this comment.
Avoid treating model text as worker failure
In distributed chat/inference this wrapper sees every cumulative string chunk produced by the model, not just worker status. If a legitimate completion starts with Error: —for example an eval prompt that asks the model to emit an error label or a log-triage answer—the CLI raises RuntimeError, exits with status 1, and lets the launcher tear down the other ranks even though no gen_error occurred. Use a structured error signal from the worker/orchestrator instead of prefix-matching model text.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine; fixed in cfdd571: real backend errors are now tagged with a GenStreamError marker and matched by type, so model output whose visible text starts with Error: no longer aborts the distributed run. Verified with the updated stream tests (typed error exits 1, plain model text exits 0).
|
Re-reviewed the follow-ups. JACCL selection (89e77d8) with the TypeError fallback to bare init() and the parametrized test is correct. On the bytes encoding: you are right and my flag was wrong. mx.array(b"...") is supported upstream (mlx python/tests/test_array.py::test_create_from_buffer builds mx.array(b"Hello") via the buffer protocol, yielding uint8), so the existing share-object path is fine as-is. Thanks for the repro. The distributed paths are only reachable on real multi-rank hardware, so single-node CI cannot exercise them, but the code reads correctly. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8f6d7fa42c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if isinstance(chunk, str) and chunk.startswith(_STREAMED_ERROR_PREFIX): | ||
| raise RuntimeError(chunk[len(_STREAMED_ERROR_PREFIX) :].strip() or "Unknown error") |
There was a problem hiding this comment.
Avoid treating model text as backend errors
In distributed chat/inference, this wrapper raises on any string chunk whose generated text starts with Error: . The backend streams cumulative model text as plain strings too, so a valid answer such as a requested error message (Error: invalid input) is indistinguishable here and will abort the CLI with exit code 1 instead of printing the response. Please only convert actual backend error events, or otherwise make the error sentinel unambiguous before applying it to model output.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine (same root as the paired item); fixed in cfdd571 via the GenStreamError type marker.
| if size <= 1: | ||
| logger.warning( | ||
| "MLX distributed launch requested but initialized singleton " | ||
| "group; continuing without distributed sharding" | ||
| ) |
There was a problem hiding this comment.
Fail instead of continuing with singleton distributed init
When mx.distributed.init() falls back to a singleton group despite the CLI having detected a distributed mlx.launch context, continuing leaves the parent ranks in distributed chat mode but the worker has no usable group. In that case rank 0's share_distributed_object() returns its local turn while nonzero ranks pass None and get None back, causing the chat loop to spin forever instead of surfacing the launch/backend misconfiguration. Please report the load as failed when distributed was requested and size <= 1.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This only triggers when the distributed backend fails to establish despite the launch (broken hostfile/backend), i.e. a misconfiguration rather than a legitimate multi-rank run where init succeeds with size greater than 1. Same family as the previously adjudicated singleton item; a hard failure here is optional hardening, not required.
There was a problem hiding this comment.
Following up on this: on re-review I agree it is a genuine issue, matching the follow-up comment above. Fixed by failing loud in c5e02cf.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d590d6b3c6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if size <= 1: | ||
| logger.warning( | ||
| "MLX distributed launch requested but initialized singleton " | ||
| "group; continuing without distributed sharding" | ||
| ) |
There was a problem hiding this comment.
Fail distributed loads when MLX initializes singleton
When config['mlx_distributed'] is true, the CLI has already put every rank into distributed-only control flow. If _init_mlx_distributed() returns a singleton group here (for example because the installed MLX lacks distributed support or the launch env/hostfile is invalid), the worker still loads as an independent rank. Subsequent share_distributed_object() calls then hit _handle_share_object's world_size <= 1 path and simply return each rank's local object; nonzero chat ranks pass None, receive None, and loop forever instead of receiving rank 0's prompt or /exit. This should fail the load (or use strict distributed init) instead of continuing without sharding.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reconsidered and agreed here. This block only runs when mlx_distributed was explicitly requested, so a size-1 group means the launch never formed a real group (MLX built without distributed support, or an invalid launch env/hostfile). Continuing silently leaves any nonzero ranks looping on share_distributed_object. It now raises, and the surrounding handler returns a clear load error, in c5e02cf.
| "mlx_parallel_mode": ("tensor" if tensor_parallel else "pipeline") | ||
| if mlx_distributed | ||
| else None, |
There was a problem hiding this comment.
Keep distributed MLX default on tensor mode
With the default CLI flags, tensor_parallel is false, so every mlx.launch ... unsloth chat/inference load is sent to MLX as parallel_mode='pipeline'. MLX-LM's distributed CLI treats tensor parallelism as the default and uses a separate --pipeline opt-in, so the default Unsloth distributed command now silently chooses a different sharding mode and can fail for models where pipeline sharding is unsupported or hits pipeline-specific limits unless the user discovers --tensor-parallel. Default the distributed path to tensor and make pipeline explicit instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
tensor_parallel is an explicit caller argument that defaults to False, and pipeline is a fully valid distributed mode (mlx_inference.py wires pipeline_group when parallel_mode == 'pipeline'). The mapping keeps sub_config['tensor_parallel'] and sub_config['mlx_parallel_mode'] mutually consistent, so pipeline is a deliberate default that the caller opts out of via tensor_parallel=True rather than incorrect behavior. Leaving the default as-is.
The worker only reaches this block when distributed was explicitly requested. A singleton (size 1) group means the launch failed to form a real group (MLX built without distributed support, or an invalid launch env/hostfile); silently continuing leaves nonzero ranks looping forever on share_distributed_object. Raise instead so the surrounding handler returns a clear load error.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
Adds CLI support for MLX distributed inference through
mlx.launchand the MLX backend.This is the main PR for the distributed inference feature. It wires launch-context detection, rank-aware CLI/chat behavior, distributed object sharing for interactive chat turns, and MLX backend group forwarding. The model-sharded loader implementation is in the paired zoo PR:
The implementation follows upstream MLX's distributed model: launch with
mlx.launch, initialize distributed state withmx.distributed.init(), and pass the resulting group tomlx-lm/mlx-vlmsharded loaders.References
mlx-lmsharded load / examples:mlx_lm.utils.sharded_load,mlx_lm.examples.sharded_generate,mlx_lm.chatmlx-vlmsharded load / examples:mlx_vlm.utils.sharded_load,mlx-vlm/examples/sharded_generate.pyWhat changed
CLI launch detection
mlx.launchcontext from MLX launcher env vars and known MPI launcher env pairs.mlx-lm/mlx-vlm.unsloth inference--tensor-parallelunder non-MPImlx.launchto select tensor parallel; otherwise the distributed default is pipeline parallel.unsloth chatStudio / backend behavior
mx.distributed.init()and forwards the group aspipeline_grouportensor_group.Supported model families
Support is delegated to upstream
mlx-lm/mlx-vlm. In practice, a family is supported when its upstream model exposes the required sharding hook:model.shard(group).mlx-lmrequiresmodel.model.pipeline(group).mlx-vlmrequires the inner language model to exposepipeline(group).Checked against local upstream sources:
mlx-lmtensor parallelllama.py.mlx-lmpipeline parallelPipelineMixin.PipelineMixinsurface.mlx-vlmtensor parallelqwen3_vl_moe).mlx-vlmtext-only wrappers that forward to sharded language models.mlx-vlmpipeline parallelWhat is not included
mlx.launchcontexts for MLX inference.mlx.launch/ MLX hostfiles directly.How to test / use
Focused local checks
Manual single-node one-shot launch
MLX's minimal single-node launch form is:
mlx.launch -n 2 unsloth inference mlx-community/Qwen3-0.6B-4bit \ --prompt "Hello" \ --max-new-tokens 128 \ --tensor-parallel \ --no-server-n 2means two local MLX ranks. Undermlx.launch, Unsloth bypasses any running Studio server so every rank loads the model in the same distributed process group.Manual single-node chat launch
Tensor parallel chat:
Pipeline parallel chat for a supported model:
--tensor-parallelselects tensor parallelism. Without it, non-MPI distributed MLX chat/inference uses pipeline mode.Manual multi-node launch
MLX's minimal multi-host launch form is:
Each node must have:
For more control, use an MLX hostfile. The hostfile can separate the SSH target from the communication IPs, which is useful when SSH and collectives should use different network interfaces:
{ "backend": "ring", "hosts": [ {"ssh": "node-a", "ips": ["<node-a-thunderbolt-address>"]}, {"ssh": "node-b", "ips": ["<node-b-thunderbolt-address>"]} ] }If SSH should also use the Thunderbolt link, use the Thunderbolt address as the SSH target:
{ "backend": "ring", "hosts": [ {"ssh": "node-a", "ips": ["<node-a-thunderbolt-address>"]}, {"ssh": "node-b-thunderbolt-ssh-target", "ips": ["<node-b-thunderbolt-address>"]} ] }Example with a hostfile and pipeline parallelism:
Example with a hostfile and tensor parallelism:
For Thunderbolt-connected Macs, use communication addresses from the Thunderbolt link rather than Wi-Fi. MLX's
mlx.distributed_configcan also discover/configure topology and write a hostfile formlx.launch.Paired zoo loader check
The paired zoo PR should also pass:
Performance reference
These are local reference measurements, not formal benchmark claims. They are included to show that Unsloth's distributed path tracks upstream
mlx-lm/mlx-vlmbehavior and to set reviewer expectations: distributed inference can reduce per-rank memory, but it is often slower for small models because communication overhead dominates.Setup:
mlx==0.31.2,mlx-lm==0.31.3,mlx-vlm==0.5.0.mlx-lmfor LLMs andmlx-vlmfor VLMs. Unsloth rows use this branch plus the paired zoo branch.LLM: Qwen3-0.6B-4bit, tensor parallel
LLM: DeepSeek-V2-Lite-Chat-4bit, pipeline parallel
VLM: Qwen3-VL-30B-A3B-3bit, tensor parallel
Notes:
mlx-lmand Unsloth. This is upstream behavior for small models where collective overhead dominates.mlx-lmdistributed speed in Unsloth.mlx-vlmdistributed behavior in Unsloth and reduces per-rank peak memory from about 14.7 GB to about 8.2 GB.mlx-vlmmodel hooks. Unsupported VLM rows are intentionally rejected with clear errors.Validation
App branch validation:
.venv/bin/python -m pytest studio/backend/tests/test_mlx_inference_backend.py unsloth_cli/tests/test_inference_chat.py -q # 41 passedPaired zoo branch validation:
.venv/bin/python -m pytest tests/test_mlx_distributed_loader.py -q # 6 passedTest-code ratios stayed under the 35% cap during review:
314 / 899 = 34.93%295 / 864 = 34.14%Reviewer notes
mlx-lm/mlx-vlmand the paired zoo loader PR.mlx.launchconcerns.mlx.launchcreates multiple web servers/workers and is not the intended distributed control plane.