Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

feat(mlx): support DDP in CLI training (#7166)

Long Yixing5d5bc8d4ec22
diff --git a/.github/workflows/mlx-ci.yml b/.github/workflows/mlx-ci.yml
index d82ef651d82..604091d3914 100644
--- a/.github/workflows/mlx-ci.yml
+++ b/.github/workflows/mlx-ci.yml
@@ -79,6 +79,10 @@ on:
- 'studio/backend/utils/hardware/**'
- 'studio/backend/core/training/worker.py'
- 'studio/backend/core/inference/mlx_inference.py'
+ - 'unsloth-cli.py'
+ - 'unsloth_cli/_inference.py'
+ - 'unsloth_cli/commands/train.py'
+ - 'unsloth_cli/tests/test_train_mlx_ddp_launch.py'
# The capability verdict is decided across these three: hardware/** measures it,
# mlx_repair.py says whether a self-heal can still overturn it, and main.py holds
# it back while one can. main.py is the studio's front door and is edited often,
@@ -135,6 +139,10 @@ on:
- 'studio/backend/utils/hardware/**'
- 'studio/backend/core/training/worker.py'
- 'studio/backend/core/inference/mlx_inference.py'
+ - 'unsloth-cli.py'
+ - 'unsloth_cli/_inference.py'
+ - 'unsloth_cli/commands/train.py'
+ - 'unsloth_cli/tests/test_train_mlx_ddp_launch.py'
- 'studio/backend/main.py'
- 'studio/backend/utils/mlx_repair.py'
- 'studio/backend/tests/test_mlx_inference_backend.py'
@@ -375,6 +383,14 @@ jobs:
python -m pytest -v --tb=short \
tests/studio/test_mlx_training_worker_behaviors.py
+ - name: MLX CLI DDP tests
+ env:
+ PYTHONPATH: ${{ github.workspace }}/studio/backend
+ UNSLOTH_COMPILE_DISABLE: '1'
+ run: |
+ python -m pytest -v --tb=short \
+ unsloth_cli/tests/test_train_mlx_ddp_launch.py
+
# The inference backend's numerical tests importorskip mlx, so they skip on
# studio-backend-ci.yml's ubuntu runner and only ever execute here. Run from
# studio/backend: its conftest puts that directory on sys.path.
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 1366efd469d..e7833636a52 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -2394,6 +2394,234 @@ def _resolve_mlx_output_dir(config, model_name):
return str(resolve_output_dir(output_dir))
+def _resolve_mlx_training_steps(
+ requested_max_steps,
+ dataset_size,
+ batch_size,
+ gradient_accumulation_steps,
+ num_epochs,
+ world_size,
+):
+ if requested_max_steps > 0:
+ return requested_max_steps
+ global_batch_size = batch_size * world_size
+ return max(
+ 1,
+ math.ceil(dataset_size / global_batch_size / gradient_accumulation_steps) * num_epochs,
+ )
+
+
+def _configure_mlx_training_schedule(
+ trainer,
+ requested_max_steps,
+ dataset_size,
+ batch_size,
+ gradient_accumulation_steps,
+ num_epochs,
+ warmup_ratio = None,
+ eval_steps_ratio = None,
+):
+ max_steps = _resolve_mlx_training_steps(
+ requested_max_steps,
+ dataset_size,
+ batch_size,
+ gradient_accumulation_steps,
+ num_epochs,
+ trainer.distributed_world_size,
+ )
+ trainer.args.max_steps = max_steps
+ if warmup_ratio is not None:
+ trainer.args.warmup_steps = int(round(warmup_ratio * max_steps))
+ if eval_steps_ratio is not None:
+ trainer.args.eval_steps = max(1, int(eval_steps_ratio * max_steps))
+ return max_steps, int(trainer.args.eval_steps)
+
+
+def _run_mlx_main_process_action(trainer, action, context):
+ world_size = int(trainer.distributed_world_size)
+ if world_size <= 1:
+ return action()
+
+ raise_distributed_failure = getattr(trainer, "_raise_distributed_failure", None)
+ if not callable(raise_distributed_failure):
+ raise RuntimeError(
+ "Unsloth MLX DDP CLI requires MLXTrainer failure coordination. "
+ "Upgrade unsloth-zoo to a compatible version."
+ )
+
+ result = None
+ error = None
+ if bool(trainer.is_main_process):
+ try:
+ result = action()
+ except BaseException as exc:
+ error = exc
+ raise_distributed_failure(error is not None, context, error)
+ return result
+
+
+def _prepare_mlx_output_dir(
+ trainer,
+ output_dir,
+ ensure_dir,
+ event_queue = None,
+):
+ def _prepare():
+ result = ensure_dir(Path(output_dir))
+ if event_queue is not None:
+ _emit_output_dir(event_queue, output_dir)
+ return result
+
+ return _run_mlx_main_process_action(
+ trainer,
+ _prepare,
+ "output directory setup",
+ )
+
+
+def _setup_mlx_tracking(trainer, config, output_dir, send):
+ wandb_run = None
+ tb_writer = None
+ if config.get("enable_wandb", False):
+
+ def _setup_wandb():
+ try:
+ import wandb as _wandb
+
+ wandb_token = config.get("wandb_token")
+ if wandb_token:
+ os.environ["WANDB_API_KEY"] = wandb_token
+ # Keep the authenticated subject out of W&B run config (mirrors _sanitize_db_config).
+ _wandb_sensitive = {"hf_token", "wandb_token", "s3_config", "subject"}
+ return _wandb.init(
+ project = config.get("wandb_project") or "unsloth-mlx",
+ config = {k: v for k, v in config.items() if k not in _wandb_sensitive},
+ reinit = True,
+ )
+ except Exception as e:
+ send("status", status_message = f"wandb init failed: {e}")
+ return None
+
+ wandb_run = _run_mlx_main_process_action(trainer, _setup_wandb, "Weights & Biases setup")
+ if config.get("enable_tensorboard", False):
+
+ def _setup_tensorboard():
+ try:
+ from tensorboardX import SummaryWriter
+ except ImportError:
+ try:
+ from torch.utils.tensorboard import SummaryWriter
+ except ImportError:
+ SummaryWriter = None
+ if SummaryWriter is None:
+ send(
+ "status",
+ status_message = "tensorboard unavailable (install tensorboardX)",
+ )
+ return None
+ try:
+ tb_dir = config.get("tensorboard_dir") or f"{output_dir}/runs"
+ return SummaryWriter(log_dir = tb_dir)
+ except Exception as e:
+ send("status", status_message = f"tensorboard init failed: {e}")
+ return None
+
+ tb_writer = _run_mlx_main_process_action(trainer, _setup_tensorboard, "TensorBoard setup")
+ return wandb_run, tb_writer
+
+
+def _mlx_worker_finalization_state(trainer, snapshot_stop):
+ trainer_stopped = bool(trainer.stop_requested)
+ local_stop_requested, stop_save = snapshot_stop()
+ stopped = trainer_stopped or bool(local_stop_requested)
+ cancelled = bool(local_stop_requested and not stop_save)
+ if int(trainer.distributed_world_size) > 1:
+ any_flag = getattr(trainer, "_distributed_any_flag", None)
+ if not callable(any_flag):
+ raise RuntimeError(
+ "Unsloth MLX DDP CLI requires MLXTrainer stop coordination. "
+ "Upgrade unsloth-zoo to a compatible version."
+ )
+ stopped = bool(any_flag(stopped))
+ cancelled = bool(any_flag(cancelled))
+ if stopped:
+ trainer.stop_requested = True
+ return stopped, cancelled
+
+
+def _synchronize_mlx_before_final_save(trainer, synchronize):
+ error = None
+ try:
+ synchronize()
+ except BaseException as exc:
+ error = exc
+ if int(trainer.distributed_world_size) <= 1:
+ if error is not None:
+ raise error
+ return
+ raise_distributed_failure = getattr(trainer, "_raise_distributed_failure", None)
+ if not callable(raise_distributed_failure):
+ raise RuntimeError(
+ "Unsloth MLX DDP CLI requires MLXTrainer failure coordination. "
+ "Upgrade unsloth-zoo to a compatible version."
+ )
+ raise_distributed_failure(error is not None, "final synchronization", error)
+
+
+def _finalize_mlx_training(
+ trainer, snapshot_stop, output_dir, synchronize, send, write_stop_checkpoint
+):
+ stopped, cancelled = _mlx_worker_finalization_state(trainer, snapshot_stop)
+ if cancelled:
+ send("complete", output_dir = None, status_message = "Training cancelled")
+ return
+
+ if stopped:
+ saving_message = "Saving stopped model..."
+ completion_message = "Training stopped"
+ else:
+ saving_message = "Saving model..."
+ completion_message = "Training completed"
+ send("status", status_message = saving_message)
+ _synchronize_mlx_before_final_save(trainer, synchronize)
+ _run_mlx_main_process_action(
+ trainer,
+ lambda: trainer.save_model(output_dir),
+ "final model save",
+ )
+ stopped_after_save, cancelled_after_save = _mlx_worker_finalization_state(
+ trainer, snapshot_stop
+ )
+ if cancelled_after_save:
+ send("complete", output_dir = None, status_message = "Training cancelled")
+ return
+ if stopped_after_save:
+ completion_message = "Training stopped"
+ checkpoint_ok = _run_mlx_main_process_action(
+ trainer,
+ write_stop_checkpoint,
+ "stop checkpoint save",
+ )
+ if int(trainer.distributed_world_size) > 1:
+ checkpoint_ok = trainer._distributed_any_flag(bool(checkpoint_ok))
+ if not checkpoint_ok:
+ send(
+ "error",
+ error = (
+ "Failed to save a resumable checkpoint after stop. "
+ "Model files were saved, but this run cannot be resumed."
+ ),
+ keep_error_status = True,
+ resume_blocked = True,
+ )
+ return
+ send(
+ "complete",
+ output_dir = output_dir if bool(trainer.is_main_process) else None,
+ status_message = completion_message,
+ )
+
+
def _resolve_mlx_max_grad_norm(value):
"""Global-norm clip threshold for MLX runs; None keeps the trainer's default. The worker used to
hardcode 0.0 and drop the requested value, so an API caller asking for a threshold got none.
@@ -2435,6 +2663,9 @@ def _run_mlx_training(event_queue, stop_queue, config):
_start_mlx_stop_poller(stop_queue)
)
+ def _snapshot_stop():
+ return _stop_requested[0], _stop_save[0]
+
_send("status", status_message = "Loading MLX libraries...")
import mlx.core as mx
@@ -2893,27 +3124,20 @@ def _run_mlx_training(event_queue, stop_queue, config):
else:
dataset, eval_dataset = split_result
- max_steps = config.get("max_steps", 0) or 0
+ requested_max_steps = config.get("max_steps", 0) or 0
num_epochs = config.get("num_epochs", 3)
max_seq_length = config.get("max_seq_length", 2048)
batch_size = config.get("batch_size", 4)
grad_accum = config.get("gradient_accumulation_steps", 4)
- if max_steps <= 0:
- max_steps = max(
- 1,
- math.ceil(len(dataset) / batch_size / grad_accum) * num_epochs,
- )
-
lr_value = float(config.get("learning_rate", "2e-4"))
# Warmup: prefer warmup_steps; fall back to warmup_ratio
warmup_steps = config.get("warmup_steps")
warmup_ratio = config.get("warmup_ratio")
- if warmup_steps is None and warmup_ratio is not None:
- warmup_steps = int(round(warmup_ratio * max_steps))
+ warmup_uses_ratio = warmup_steps is None and warmup_ratio is not None
if warmup_steps is None:
- warmup_steps = 5
+ warmup_steps = 0 if warmup_uses_ratio else 5
# Resolve to ~/.unsloth/studio/outputs/ so the export page finds it
from utils.paths import ensure_dir
@@ -2925,29 +3149,13 @@ def _run_mlx_training(event_queue, stop_queue, config):
output_dir = _resolve_mlx_output_dir(
{**config, "output_dir": resume_dir} if resume_dir else config, model_name
)
- ensure_dir(Path(output_dir))
- _emit_output_dir(event_queue, output_dir)
- # Pin the subset before any checkpoint lands here; a resume reads it back.
- if not record_row_bound(output_dir, mlx_max_train_rows, mlx_max_train_rows_seed) and (
- mlx_max_train_rows
- ):
- _send(
- "warning",
- message = (
- f"Could not record the max_steps row bound in {output_dir}: "
- "resuming this run later will read it as unbounded"
- ),
- )
-
raw_eval_steps = config.get("eval_steps", 0)
if evaluation_enabled(raw_eval_steps):
eval_steps_value = float(raw_eval_steps)
else:
eval_steps_value = 0.0
- if 0 < eval_steps_value < 1:
- eval_steps_val = max(1, int(eval_steps_value * max_steps))
- else:
- eval_steps_val = int(eval_steps_value)
+ eval_steps_ratio = eval_steps_value if 0 < eval_steps_value < 1 else None
+ eval_steps_val = 0 if eval_steps_ratio is not None else int(eval_steps_value)
# Re-validate for direct worker callers; training.py normalizes the main path.
max_grad_norm = _resolve_mlx_max_grad_norm(config.get("max_grad_norm"))
@@ -2974,7 +3182,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
mlx_config_kwargs = dict(
per_device_train_batch_size = batch_size,
gradient_accumulation_steps = grad_accum,
- max_steps = max_steps,
+ max_steps = requested_max_steps,
learning_rate = lr_value,
warmup_steps = warmup_steps,
lr_scheduler_type = lr_scheduler_type,
@@ -3024,8 +3232,34 @@ def _run_mlx_training(event_queue, stop_queue, config):
eval_dataset = eval_dataset,
args = MLXTrainingConfig(**mlx_config_kwargs),
)
+ max_steps, eval_steps_val = _configure_mlx_training_schedule(
+ trainer,
+ requested_max_steps,
+ len(dataset),
+ batch_size,
+ grad_accum,
+ num_epochs,
+ warmup_ratio = warmup_ratio if warmup_uses_ratio else None,
+ eval_steps_ratio = eval_steps_ratio,
+ )
+ _prepare_mlx_output_dir(trainer, output_dir, ensure_dir, event_queue)
+
+ def _record_mlx_row_bound():
+ # Pin the subset before any checkpoint lands here; a resume reads it back.
+ if not record_row_bound(output_dir, mlx_max_train_rows, mlx_max_train_rows_seed) and (
+ mlx_max_train_rows
+ ):
+ _send(
+ "warning",
+ message = (
+ f"Could not record the max_steps row bound in {output_dir}: "
+ "resuming this run later will read it as unbounded"
+ ),
+ )
+
+ _run_mlx_main_process_action(trainer, _record_mlx_row_bound, "max_steps row bound setup")
_trainer_ref[0] = trainer
- if _stop_requested[0]:
+ if _is_stop_requested():
trainer.stop_requested = True
# Tell the parent eval is configured so the frontend shows the eval chart
@@ -3064,43 +3298,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
),
)
- wandb_run = None
- tb_writer = None
- if config.get("enable_wandb", False):
- try:
- import wandb as _wandb
-
- wandb_token = config.get("wandb_token")
- if wandb_token:
- os.environ["WANDB_API_KEY"] = wandb_token
- # Keep the authenticated subject out of W&B run config (mirrors _sanitize_db_config).
- _wandb_sensitive = {"hf_token", "wandb_token", "s3_config", "subject"}
- wandb_run = _wandb.init(
- project = config.get("wandb_project") or "unsloth-mlx",
- config = {k: v for k, v in config.items() if k not in _wandb_sensitive},
- reinit = True,
- )
- except Exception as e:
- _send("status", status_message = f"wandb init failed: {e}")
- if config.get("enable_tensorboard", False):
- try:
- from tensorboardX import SummaryWriter
- except ImportError:
- try:
- from torch.utils.tensorboard import SummaryWriter
- except ImportError:
- SummaryWriter = None
- if SummaryWriter is not None:
- try:
- tb_dir = config.get("tensorboard_dir") or f"{output_dir}/runs"
- tb_writer = SummaryWriter(log_dir = tb_dir)
- except Exception as e:
- _send("status", status_message = f"tensorboard init failed: {e}")
- else:
- _send(
- "status",
- status_message = "tensorboard unavailable (install tensorboardX)",
- )
+ wandb_run, tb_writer = _setup_mlx_tracking(trainer, config, output_dir, _send)
_send("status", status_message = f"Training {model_name}...")
@@ -3221,43 +3419,15 @@ def _run_mlx_training(event_queue, stop_queue, config):
except Exception:
pass
- def _stop_checkpoint_ok() -> bool:
- if _write_mlx_stop_checkpoint(trainer, _opt_ref[0], output_dir):
- return True
- _send(
- "error",
- error = (
- "Failed to save a resumable checkpoint after stop. "
- "Model files were saved, but this run cannot be resumed."
- ),
- # A user stop finalizes as 'stopped'; keep this failure's error status so history explains it.
- keep_error_status = True,
- # Older checkpoints are stale; resuming would roll back past this stop.
- resume_blocked = True,
- )
- return False
-
try:
- if trainer.stop_requested:
- if not _stop_save[0]:
- # Cancel (save=False): skip saving.
- _send("complete", output_dir = None, status_message = "Training cancelled")
- else:
- _send("status", status_message = "Saving stopped model...")
- mx.synchronize()
- trainer.save_model(output_dir)
- # Stop-and-save promises a resumable checkpoint, not just model files.
- if not _stop_checkpoint_ok():
- return
- _send("complete", output_dir = output_dir, status_message = "Training stopped")
- else:
- _send("status", status_message = "Saving model...")
- mx.synchronize()
- trainer.save_model(output_dir)
- # A save-stop can race the natural final save; it made the same promise.
- if trainer.stop_requested and _stop_save[0] and not _stop_checkpoint_ok():
- return
- _send("complete", output_dir = output_dir, status_message = "Training completed")
+ _finalize_mlx_training(
+ trainer,
+ _snapshot_stop,
+ output_dir,
+ mx.synchronize,
+ _send,
+ lambda: _write_mlx_stop_checkpoint(trainer, _opt_ref[0], output_dir),
+ )
finally:
_finish_tracking()
@@ -3330,11 +3500,11 @@ def run_mlx_training_process(
stop_queue.put({"type": _MLX_WORKER_COMPLETE})
except (EOFError, OSError, ValueError):
pass
- except Exception as exc:
+ except BaseException as exc:
event_queue.put(
{
"type": "error",
- "error": str(exc),
+ "error": str(exc) or type(exc).__name__,
"stack": traceback.format_exc(limit = 20),
"ts": time.time(),
}
diff --git a/studio/backend/tests/test_mlx_training_worker_config.py b/studio/backend/tests/test_mlx_training_worker_config.py
index 2af8e113518..55964cfae00 100644
--- a/studio/backend/tests/test_mlx_training_worker_config.py
+++ b/studio/backend/tests/test_mlx_training_worker_config.py
@@ -3,6 +3,7 @@
import ast
import importlib.util
import inspect
+import os
import sys
import textwrap
import types
@@ -12,8 +13,10 @@ import pytest
def _load_worker_module():
+ worker_path = Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py"
stub_names = (
- "structlog",
+ "core.training",
+ "core.training.dataset_bounds",
"loggers",
"utils",
"utils.child_stdio",
@@ -27,7 +30,9 @@ def _load_worker_module():
previous_modules = {name: sys.modules.get(name) for name in stub_names}
try:
- sys.modules["structlog"] = types.ModuleType("structlog")
+ core_training = types.ModuleType("core.training")
+ core_training.__path__ = [str(worker_path.parent)]
+ sys.modules["core.training"] = core_training
loggers = types.ModuleType("loggers")
loggers.get_logger = lambda *_args, **_kwargs: None
@@ -40,7 +45,13 @@ def _load_worker_module():
sys.modules["utils"] = utils
child_stdio = types.ModuleType("utils.child_stdio")
- child_stdio.utf8_child_env = lambda env = None: dict(env or {})
+
+ def utf8_child_env(env = None):
+ child = dict(os.environ if env is None else env)
+ child["PYTHONIOENCODING"] = "utf-8"
+ return child
+
+ child_stdio.utf8_child_env = utf8_child_env
sys.modules["utils.child_stdio"] = child_stdio
hardware = types.ModuleType("utils.hardware")
@@ -73,7 +84,6 @@ def _load_worker_module():
setattr(wheel_utils, name, lambda *_args, **_kwargs: None)
sys.modules["utils.wheel_utils"] = wheel_utils
- worker_path = Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py"
spec = importlib.util.spec_from_file_location("mlx_training_worker_under_test", worker_path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
@@ -98,7 +108,9 @@ _adapt_for_mlx_vlm = _worker._adapt_for_mlx_vlm
_mlx_dora_peft_kwargs = _worker._mlx_dora_peft_kwargs
-def test_mlx_studio_optimizer_aliases_are_explicit():
+def test_mlx_studio_optimizer_aliases_are_explicit(monkeypatch):
+ # Pin the local fallback: a zoo with the MLX normalizer keeps adamw_8bit (real 8-bit AdamW).
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.trainer", None)
assert _normalize_mlx_studio_optimizer("adamw_8bit") == "adamw"
assert _normalize_mlx_studio_optimizer("paged_adamw_8bit") == "adamw"
assert _normalize_mlx_studio_optimizer("adafactor") == "adafactor"
@@ -520,3 +532,84 @@ def test_odd_model_names_do_not_break_the_warning(model_name):
events, applied = _run_masking(model_name = model_name, detect = _detect_fails)
assert applied is False and len(_warnings(events)) == 1
+
+
+class _FakeRankTrainer:
+ def __init__(
+ self,
+ rank = 0,
+ world_size = 1,
+ save_error = None,
+ ):
+ self.distributed_world_size = world_size
+ self.is_main_process = rank == 0
+ self.stop_requested = False
+ self.saved = []
+ self._save_error = save_error
+
+ def save_model(self, path):
+ if self._save_error is not None:
+ raise self._save_error
+ self.saved.append(path)
+
+ def _distributed_any_flag(self, flag):
+ return bool(flag)
+
+ def _raise_distributed_failure(
+ self,
+ failed,
+ context,
+ exc = None,
+ ):
+ if failed:
+ raise RuntimeError(f"{context}: {exc}")
+
+
+def _finalize(
+ trainer,
+ stop = (False, True),
+ checkpoint_ok = True,
+):
+ events = []
+ _worker._finalize_mlx_training(
+ trainer,
+ lambda: stop,
+ "/out",
+ lambda: None,
+ lambda event_type, **payload: events.append((event_type, payload)),
+ lambda: checkpoint_ok,
+ )
+ return events
+
+
+def test_mlx_epoch_steps_divide_by_world_size_only_when_derived():
+ steps = _worker._resolve_mlx_training_steps
+ assert steps(0, 16, 2, 2, 3, 1) == 12
+ assert steps(0, 16, 2, 2, 3, 2) == 6
+ assert steps(7, 16, 2, 2, 3, 2) == 7
+
+
[email protected]("rank", [0, 1])
+def test_mlx_final_save_is_rank0_owned(rank):
+ trainer = _FakeRankTrainer(rank = rank, world_size = 2)
+ events = _finalize(trainer)
+ assert trainer.saved == (["/out"] if rank == 0 else [])
+ assert events[-1] == (
+ "complete",
+ {"output_dir": "/out" if rank == 0 else None, "status_message": "Training completed"},
+ )
+
+
+def test_mlx_rank0_save_failure_reaches_every_rank():
+ with pytest.raises(RuntimeError, match = "final model save"):
+ _finalize(_FakeRankTrainer(world_size = 2, save_error = OSError("disk full")))
+
+
+def test_mlx_single_process_finalization_keeps_prior_contract():
+ trainer = _FakeRankTrainer()
+ assert _finalize(trainer, stop = (True, False))[-1][1]["status_message"] == "Training cancelled"
+ assert trainer.saved == []
+
+ events = _finalize(trainer, stop = (True, True), checkpoint_ok = False)
+ assert trainer.saved == ["/out"]
+ assert events[-1][0] == "error" and events[-1][1]["resume_blocked"] is True
diff --git a/studio/backend/tests/test_training_stop_watchdog.py b/studio/backend/tests/test_training_stop_watchdog.py
index 78466234a1d..f4c4a78758b 100644
--- a/studio/backend/tests/test_training_stop_watchdog.py
+++ b/studio/backend/tests/test_training_stop_watchdog.py
@@ -1287,15 +1287,27 @@ def test_mlx_worker_never_withholds_a_terminal_send_behind_tracking_teardown():
if isinstance(n, ast.FunctionDef) and n.name == "_run_mlx_training"
)
- def _is_complete_send(node):
+ def _is_complete_send(node, sender = "_send"):
return (
isinstance(node, ast.Call)
- and getattr(node.func, "id", "") == "_send"
+ and getattr(node.func, "id", "") == sender
and node.args
and isinstance(node.args[0], ast.Constant)
and node.args[0].value == "complete"
)
+ finalize = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_finalize_mlx_training"
+ )
+ assert any(_is_complete_send(c, "send") for c in ast.walk(finalize))
+
+ def _is_terminal(node):
+ return _is_complete_send(node) or (
+ isinstance(node, ast.Call) and getattr(node.func, "id", "") == "_finalize_mlx_training"
+ )
+
def _teardown_lines(nodes):
return {
c.lineno
@@ -1308,7 +1320,7 @@ def test_mlx_worker_never_withholds_a_terminal_send_behind_tracking_teardown():
n
for n in ast.walk(fn)
if isinstance(n, ast.Try)
- and any(_is_complete_send(c) for stmt in n.body for c in ast.walk(stmt))
+ and any(_is_terminal(c) for stmt in n.body for c in ast.walk(stmt))
]
assert len(saves) == 1, "expected one save/finalize try block with the terminal sends"
everywhere = _teardown_lines([fn])
diff --git a/unsloth-cli.py b/unsloth-cli.py
index 0e1db20a287..87dc719cecf 100644
--- a/unsloth-cli.py
+++ b/unsloth-cli.py
@@ -146,6 +146,26 @@ def _save_or_push_model(model, tokenizer, args, is_mlx):
model.push_to_hub_merged(args.hub_path, tokenizer, args.save_method, token = args.hub_token)
+def _save_or_push_model_with_mlx_ddp(model, tokenizer, args, is_mlx, trainer):
+ if not is_mlx or int(trainer.distributed_world_size) <= 1:
+ return _save_or_push_model(model, tokenizer, args, is_mlx)
+
+ raise_distributed_failure = getattr(trainer, "_raise_distributed_failure", None)
+ if not callable(raise_distributed_failure):
+ raise RuntimeError(
+ "Unsloth MLX DDP CLI requires MLXTrainer failure coordination. "
+ "Upgrade unsloth-zoo to a compatible version."
+ )
+
+ error = None
+ if bool(trainer.is_main_process):
+ try:
+ _save_or_push_model(model, tokenizer, args, is_mlx)
+ except BaseException as exc:
+ error = exc
+ raise_distributed_failure(error is not None, "legacy CLI final save", error)
+
+
def _build_sft_config(SFTConfig, args, is_mlx, bf16_supported):
config_kwargs = dict(
per_device_train_batch_size = args.per_device_train_batch_size,
@@ -283,7 +303,7 @@ def run(args):
_train_with_legacy_save_control(trainer, is_mlx)
- _save_or_push_model(model, tokenizer, args, is_mlx)
+ _save_or_push_model_with_mlx_ddp(model, tokenizer, args, is_mlx, trainer)
if __name__ == "__main__":
diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.py
index 10fb40239e4..224c9ef6a2a 100644
--- a/unsloth_cli/commands/train.py
+++ b/unsloth_cli/commands/train.py
@@ -7,7 +7,7 @@ from typing import Optional
import typer
-from unsloth_cli._inference import ensure_studio_backend_path
+from unsloth_cli._inference import ensure_studio_backend_path, mlx_distributed_info
from unsloth_cli._studio_deps import studio_backend_imports
from unsloth_cli.config import Config, ConfigError, load_config
from unsloth_cli.options import add_options_from_config
@@ -23,10 +23,18 @@ def _should_use_mlx_backend_for_cli() -> bool:
def _activate_mlx_transformers(model_name: str, hf_token: Optional[str]) -> None:
# Activate before any transformers import: adapter model-type detection imports utils.models.
ensure_studio_backend_path()
+ from filelock import FileLock
+ from utils.paths.storage_roots import studio_root
from utils.transformers_version import activate_transformers_for_subprocess
+
try:
- activate_transformers_for_subprocess(model_name, hf_token)
+ root = studio_root()
+ root.mkdir(parents = True, exist_ok = True)
+ with FileLock(str(root / ".transformers-sidecar.lock")):
+ activate_transformers_for_subprocess(model_name, hf_token)
except Exception as exc:
+ if mlx_distributed_info()[0]:
+ raise
typer.echo(f"Warning: failed to activate Transformers sidecar: {exc}", err = True)
diff --git a/unsloth_cli/tests/test_train_mlx_ddp_launch.py b/unsloth_cli/tests/test_train_mlx_ddp_launch.py
new file mode 100644
index 00000000000..11530981c0e
--- /dev/null
+++ b/unsloth_cli/tests/test_train_mlx_ddp_launch.py
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+
+import importlib.util
+import os
+import platform
+import subprocess
+import sys
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _load_legacy_cli():
+ spec = importlib.util.spec_from_file_location(
+ "unsloth_legacy_cli", _REPO_ROOT / "unsloth-cli.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _run_collective_probe():
+ sys.path.insert(0, str(_REPO_ROOT / "studio" / "backend"))
+ import mlx.core as mx
+ from core.training.worker import _configure_mlx_training_schedule, _finalize_mlx_training
+ from unsloth_zoo.mlx.trainer import MLXTrainer
+
+ root = Path(os.environ["UNSLOTH_MLX_DDP_PROBE_DIR"])
+ trainer = object.__new__(MLXTrainer)
+ rank = trainer.distributed_rank
+ args = SimpleNamespace(max_steps = 0, warmup_steps = 0, eval_steps = 0)
+ schedule_trainer = SimpleNamespace(args = args, distributed_world_size = 2)
+ assert _configure_mlx_training_schedule(schedule_trainer, 0, 16, 2, 2, 3) == (6, 0)
+
+ import unsloth_cli.commands.train as train_cmd
+ import utils.transformers_version as transformers_version
+
+ active, contender = root / "sidecar-active", root / "sidecar-contender"
+
+ def activate_sidecar(*_args):
+ try:
+ active.touch(exist_ok = False)
+ if rank == 0:
+ deadline = time.monotonic() + 5
+ while not contender.exists() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert contender.exists()
+ time.sleep(0.1)
+ finally:
+ active.unlink(missing_ok = True)
+
+ transformers_version.activate_transformers_for_subprocess = activate_sidecar
+ if rank:
+ deadline = time.monotonic() + 5
+ while not active.exists() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert active.exists()
+ contender.touch()
+ train_cmd._activate_mlx_transformers("test/model", None)
+
+ trainer.stop_requested = False
+ trainer.save_model = lambda _path: (root / "worker-save").touch(exist_ok = False)
+ complete = {}
+ _finalize_mlx_training(
+ trainer,
+ lambda: (False, True),
+ str(root),
+ mx.synchronize,
+ lambda event_type, **payload: complete.update(type = event_type, **payload),
+ lambda: True,
+ )
+ assert complete["type"] == "complete"
+ assert complete["output_dir"] == (str(root) if rank == 0 else None)
+
+ legacy_cli = _load_legacy_cli()
+ legacy_cli._save_or_push_model = lambda *_args: (root / "legacy-save").touch(exist_ok = False)
+ legacy_cli._save_or_push_model_with_mlx_ddp(object(), object(), object(), True, trainer)
+
+ trainer.save_model = lambda _path: (_ for _ in ()).throw(KeyboardInterrupt("probe"))
+ with pytest.raises((KeyboardInterrupt, RuntimeError)):
+ _finalize_mlx_training(
+ trainer,
+ lambda: (False, True),
+ str(root),
+ mx.synchronize,
+ lambda *_args, **_kwargs: None,
+ lambda: True,
+ )
+ (root / f"passed-{rank}").touch()
+
+
+ platform.system() != "Darwin" or platform.machine() != "arm64",
+ reason = "real MLX collectives require Apple Silicon",
+)
+def test_mlx_launch_cli_ddp_contracts(tmp_path):
+ launcher = Path(sys.executable).with_name("mlx.launch")
+ env = os.environ.copy()
+ env["UNSLOTH_MLX_DDP_PROBE_DIR"] = str(tmp_path)
+ env["UNSLOTH_STUDIO_HOME"] = str(tmp_path / "studio")
+ env["PYTHONPATH"] = os.pathsep.join((str(_REPO_ROOT), str(_REPO_ROOT / "studio/backend")))
+ result = subprocess.run(
+ [launcher, "-n", "2", "--", sys.executable, str(Path(__file__).resolve())],
+ cwd = _REPO_ROOT,
+ env = env,
+ capture_output = True,
+ timeout = 60,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert len(list(tmp_path.glob("passed-*"))) == 2, result.stdout + result.stderr
+
+
+if __name__ == "__main__":
+ _run_collective_probe()