Skip to content

feat(cli): support MLX distributed inference - #6845

Merged
danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:feat/mlx-distributed-inference
Jul 8, 2026
Merged

danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:feat/mlx-distributed-inference

Conversation

@Lyxot

@Lyxot Lyxot commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds CLI support for MLX distributed inference through mlx.launch and 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 with mx.distributed.init(), and pass the resulting group to mlx-lm / mlx-vlm sharded loaders.

References

What changed

CLI launch detection

  • Detects mlx.launch context from MLX launcher env vars and known MPI launcher env pairs.
  • Silences nonzero ranks so only rank 0 owns user-facing terminal output.
  • Rejects MPI launcher mode for now because the current subprocess/backend layout is not enabled for it.
  • Rejects GGUF under MLX distributed launch; GGUF still runs through llama.cpp, not mlx-lm / mlx-vlm.

unsloth inference

  • Runs in-process under MLX distributed launch instead of connecting to Studio.
  • Forwards distributed mode into the MLX backend.
  • Uses --tensor-parallel under non-MPI mlx.launch to select tensor parallel; otherwise the distributed default is pipeline parallel.

unsloth chat

  • Supports interactive distributed chat turns by broadcasting rank-0 input to peer ranks through MLX collectives.
  • Keeps nonzero ranks alive for the full chat session and drains launcher stdin after shared turns.
  • Disables compare mode under distributed MLX chat because compare would need a second distributed worker group on the same ranks.
  • Keeps rank-0 terminal behavior consistent with non-distributed chat.

Studio / backend behavior

  • For CLI-launched distributed inference, the MLX backend initializes mx.distributed.init() and forwards the group as pipeline_group or tensor_group.
  • The backend records rank/world-size metadata and treats singleton initialization as non-distributed.
  • Studio HTTP inference rejects MLX distributed launch contexts clearly. Studio itself is not a distributed inference orchestrator in this PR.
  • Adds a small distributed object-share command for MLX worker processes, used by chat turn broadcast.

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:

  • Tensor parallel requires model.shard(group).
  • Pipeline parallel for mlx-lm requires model.model.pipeline(group).
  • Pipeline parallel for mlx-vlm requires the inner language model to expose pipeline(group).

Checked against local upstream sources:

mlx-lm tensor parallel

  • Llama-family models implemented through llama.py.
  • Qwen2 / Qwen3 / Qwen3.5 families.
  • DeepSeek V2 / V3 / V3.2 families.
  • Kimi K2.5 / DeepSeek-derived Kimi models.
  • GPT-OSS.
  • GLM4 MoE and GLM4 MoE Lite.
  • EXAONE MoE.
  • MiniMax.
  • Ministral 3.
  • LongCat Flash / LongCat Flash n-gram.
  • Step 3.5.
  • iQuestLoopCoder.

mlx-lm pipeline parallel

  • DeepSeek V3-derived models through PipelineMixin.
  • DeepSeek V3.2.
  • Ministral 3.
  • Other models using the upstream PipelineMixin surface.

mlx-vlm tensor parallel

  • Qwen3-VL MoE (qwen3_vl_moe).
  • Kimi K2.5 VLM.
  • DeepSeek V4 language-backed VLMs.
  • mlx-vlm text-only wrappers that forward to sharded language models.

mlx-vlm pipeline parallel

  • Only when the inner VLM language model exposes upstream pipeline support. This is narrower than tensor support; unsupported VLMs return a clear error.

What is not included

  • No Studio distributed UI/server support. Studio rejects mlx.launch contexts for MLX inference.
  • No GGUF distributed inference. llama.cpp Metal tensor parallel is not wired here.
  • No distributed LoRA adapter inference. Merge/export adapters into an MLX model first.
  • No runtime quantization while sharding. Use pre-quantized MLX repos for distributed quantized inference.
  • No automatic host discovery or network-interface management. Use mlx.launch / MLX hostfiles directly.
  • No attempt to improve upstream distributed performance; this PR routes Unsloth through upstream sharded inference behavior.

How to test / use

Focused local checks

.venv/bin/python -m pytest \
  studio/backend/tests/test_mlx_inference_backend.py \
  unsloth_cli/tests/test_inference_chat.py \
  -q
git diff --check main
.venv/bin/python -m py_compile \
  unsloth_cli/commands/chat.py \
  studio/backend/core/inference/mlx_inference.py \
  studio/backend/core/inference/worker.py \
  studio/backend/routes/inference.py \
  studio/backend/tests/test_mlx_inference_backend.py

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 2 means two local MLX ranks. Under mlx.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:

mlx.launch -n 2 unsloth chat mlx-community/Qwen3-0.6B-4bit \
  --tensor-parallel \
  --no-server

Pipeline parallel chat for a supported model:

mlx.launch -n 2 unsloth chat mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx \
  --no-server

--tensor-parallel selects 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:

mlx.launch --hosts node-a,node-b unsloth chat mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx --no-server

Each node must have:

  • the same branch checked out
  • the same Python environment
  • passwordless SSH from the launch machine
  • communication addresses reachable by all MLX ranks

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:

mlx.launch --hostfile /path/to/hosts_thunderbolt.json \
  unsloth chat mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx \
  --no-server

Example with a hostfile and tensor parallelism:

mlx.launch --hostfile /path/to/hosts_thunderbolt.json \
  unsloth chat mlx-community/Qwen3-0.6B-4bit \
  --tensor-parallel \
  --no-server

For Thunderbolt-connected Macs, use communication addresses from the Thunderbolt link rather than Wi-Fi. MLX's mlx.distributed_config can also discover/configure topology and write a hostfile for mlx.launch.

Paired zoo loader check

The paired zoo PR should also pass:

.venv/bin/python -m pytest tests/test_mlx_distributed_loader.py -q
git diff --check origin/pr/844
git diff --check origin/main
.venv/bin/python -m py_compile unsloth_zoo/mlx/loader.py tests/test_mlx_distributed_loader.py

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-vlm behavior 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:

  • Output length: 1024 tokens, EOS ignored.
  • Unsupported rows removed.
  • Single-node: 2 local ranks on one Apple Silicon Mac.
  • Multi-node: two Apple Silicon Macs over Thunderbolt; node A is M3 Max and node B is M3 Pro. Launcher SSH and MLX ring traffic both used the Thunderbolt link.
  • Packages: mlx==0.31.2, mlx-lm==0.31.3, mlx-vlm==0.5.0.
  • Upstream reference rows use mlx-lm for LLMs and mlx-vlm for VLMs. Unsloth rows use this branch plus the paired zoo branch.

LLM: Qwen3-0.6B-4bit, tensor parallel

Runner Topology Parallel World Tokens Tok/s Generate s Peak GB by rank Wall s
mlx-lm single process none 1 1024 391.00 2.62 0.53 6.51
mlx-lm single node tensor 2 1024 39.39 26.00 0.33/0.33 31.77
mlx-lm multi node tensor 2 1024 29.37 34.87 0.33/0.33 40.96
unsloth single process none 1 1024 375.24 2.73 0.53 7.18
unsloth single node tensor 2 1024 37.96 26.97 0.33/0.33 32.62
unsloth multi node tensor 2 1024 30.53 33.54 0.33/0.33 40.56

LLM: DeepSeek-V2-Lite-Chat-4bit, pipeline parallel

Runner Topology Parallel World Tokens Tok/s Generate s Peak GB by rank Wall s
mlx-lm single process none 1 1024 131.74 7.77 9.23 12.07
mlx-lm single node pipeline 2 1024 127.73 8.02 4.78/4.50 15.72
mlx-lm multi node pipeline 2 1024 72.09 14.20 4.78/4.51 19.29
unsloth single process none 1 1024 133.42 7.67 9.23 12.33
unsloth single node pipeline 2 1024 126.28 8.11 4.78/4.50 14.80
unsloth multi node pipeline 2 1024 71.47 14.33 4.78/4.51 19.74

VLM: Qwen3-VL-30B-A3B-3bit, tensor parallel

Runner Topology Parallel World Tokens Tok/s Generate s Peak GB by rank Wall s
mlx-vlm single process none 1 1024 73.65 13.90 14.72 19.36
mlx-vlm single node tensor 2 1024 15.82 64.74 8.19/8.19 71.99
mlx-vlm multi node tensor 2 1024 11.85 86.39 8.19/8.19 96.10
unsloth single process none 1 1024 69.98 14.63 14.72 21.35
unsloth single node tensor 2 1024 15.91 64.37 8.19/8.19 73.71
unsloth multi node tensor 2 1024 11.88 86.17 8.19/8.19 97.35

Notes:

  • Qwen3-0.6B tensor-parallel is much slower than single process in both mlx-lm and Unsloth. This is upstream behavior for small models where collective overhead dominates.
  • DeepSeek pipeline parallel improves memory split and matches mlx-lm distributed speed in Unsloth.
  • Qwen3-VL-30B-A3B tensor parallel matches mlx-vlm distributed behavior in Unsloth and reduces per-rank peak memory from about 14.7 GB to about 8.2 GB.
  • Distributed VLM support follows mlx-vlm model 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 passed
git diff --check main
.venv/bin/python -m py_compile \
  unsloth_cli/commands/chat.py \
  studio/backend/core/inference/mlx_inference.py \
  studio/backend/core/inference/worker.py \
  studio/backend/routes/inference.py \
  studio/backend/tests/test_mlx_inference_backend.py

Paired zoo branch validation:

.venv/bin/python -m pytest tests/test_mlx_distributed_loader.py -q
# 6 passed
git diff --check origin/pr/844
git diff --check origin/main
.venv/bin/python -m py_compile unsloth_zoo/mlx/loader.py tests/test_mlx_distributed_loader.py

Test-code ratios stayed under the 35% cap during review:

  • App: 314 / 899 = 34.93%
  • Zoo: 295 / 864 = 34.14%

Reviewer notes

  • This PR is intentionally a launch/CLI/backend integration PR. Architecture-specific tensor/pipeline implementation remains in upstream mlx-lm / mlx-vlm and the paired zoo loader PR.
  • The CLI does not choose MLX networking. Host selection, Thunderbolt addresses, and backend selection remain standard mlx.launch concerns.
  • Studio rejection is deliberate. Running Studio itself under mlx.launch creates multiple web servers/workers and is not the intended distributed control plane.
  • The nonzero-rank chat loop is intentionally kept alive after each turn so all ranks enter the same collectives.
  • The performance tables should be read as parity/context against upstream behavior, not as a claim that distributed inference is faster for every model.

@Lyxot
Lyxot requested a review from danielhanchen as a code owner July 3, 2026 15:13
Copilot AI review requested due to automatic review settings July 3, 2026 15:13

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread studio/backend/core/inference/worker.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_object worker 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.

Comment thread unsloth_cli/_inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/core/inference/worker.py Resolved
Comment thread studio/backend/core/inference/worker.py Resolved
Comment thread studio/backend/core/inference/worker.py Resolved
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/core/inference/worker.py Outdated
mx.eval(mx.distributed.all_sum(mx.array(0), group = group))
shared = None
else:
data = mx.array(_encode_share_object(obj), dtype = mx.uint8)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +797 to +800
if size <= 1:
logger.warning(
"MLX distributed launch requested but initialized singleton "
"group; continuing without distributed sharding"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

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:

  1. JACCL backend selection (mlx_inference.py _init_mlx_distributed): bare mx.distributed.init() uses the default backend="any", and per init(backend="any") selects ring singleton instead of JACCL when launched via mlx.launch --backend jaccl ml-explore/mlx#3442 that returns a size-1 ring singleton before trying JACCL when the ring env is set (MLX_RANK present, no MLX_HOSTFILE). Under mlx.launch --backend jaccl this silently degrades to a per-rank full-model load. Detect the JACCL launch env (MLX_JACCL_COORDINATOR + MLX_IBV_DEVICES) and pass backend="jaccl" explicitly, wrapped in try/except for older MLX that lacks the explicit-backend arg. Ring (hostfile) and MPI still initialize correctly under the default.

  2. Share-object encoding (worker.py _handle_share_object): mx.array(_encode_share_object(obj), dtype=mx.uint8) passes a Python bytes object, which mx.array does not accept as a uint8 sequence (it takes scalar/list/tuple/ndarray/array). Wrap it as an ndarray/memoryview, e.g. mx.array(np.frombuffer(payload, dtype=np.uint8)). This runs on every non-empty chat turn on rank 0, so distributed chat broadcast would fail on the first prompt on real MLX even though the mocked test passes.

The other Codex items on this PR are below the bar (handled in the inline reactions).

@Lyxot

Lyxot commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Status on the two maintainer-confirmed MLX distributed issues:

  1. JACCL backend selection is 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.

  2. Share-object bytes encoding is intentionally unchanged. I could not reproduce the claimed 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 existing bytes path unchanged to avoid adding an unnecessary workaround.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/core/inference/worker.py Resolved
Comment thread unsloth_cli/commands/chat.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth_cli/commands/chat.py Resolved
Comment thread unsloth_cli/commands/inference.py Resolved
Comment thread unsloth_cli/_inference.py Resolved
@Lyxot
Lyxot force-pushed the feat/mlx-distributed-inference branch from b7396d0 to 8f6d7fa Compare July 7, 2026 12:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth_cli/_inference.py Outdated
Comment on lines +237 to +238
if isinstance(chunk, str) and chunk.startswith(_STREAMED_ERROR_PREFIX):
raise RuntimeError(chunk[len(_STREAMED_ERROR_PREFIX) :].strip() or "Unknown error")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@danielhanchen

Copy link
Copy Markdown
Member

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth_cli/_inference.py Outdated
Comment on lines +237 to +238
if isinstance(chunk, str) and chunk.startswith(_STREAMED_ERROR_PREFIX):
raise RuntimeError(chunk[len(_STREAMED_ERROR_PREFIX) :].strip() or "Unknown error")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Genuine (same root as the paired item); fixed in cfdd571 via the GenStreamError type marker.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +809 to +813
if size <= 1:
logger.warning(
"MLX distributed launch requested but initialized singleton "
"group; continuing without distributed sharding"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +809 to +813
if size <= 1:
logger.warning(
"MLX distributed launch requested but initialized singleton "
"group; continuing without distributed sharding"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +927 to +929
"mlx_parallel_mode": ("tensor" if tensor_parallel else "pipeline")
if mlx_distributed
else None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: c5e02cfa2c

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 2a6abe2 into unslothai:main Jul 8, 2026
42 of 45 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants