Repository navigation
Add MLX backend support for CLI unsloth train - #6709
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces comprehensive support for the MLX training backend on Apple Silicon, adapting the legacy UnslothTrainer API and providing compatibility shims for TRL, SFTTrainer, and PyTorch CUDA memory APIs. Key feedback focuses on thread safety and robust error handling: changing the synchronization lock to threading.RLock to prevent deadlocks, protecting shared state variables and progress reporting with locks to avoid data races, ensuring the active trainer is properly registered in the stop poller to enable early stopping, handling integer device targets in the CUDA compatibility shim, and replacing None placeholders for optional PyTorch tensor types with dummy classes to prevent runtime TypeError crashes.
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.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 67cb90d2c8
ℹ️ 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.
Pull request overview
This PR extends the existing training stack to support running unsloth train on Apple Silicon via the MLX backend by reusing Studio’s MLX worker subprocess and making the Studio UnslothTrainer dispatch backend-aware.
Changes:
- Add MLX-aware dispatch/activation in the CLI
unsloth traincommand and route through the Studio backend trainer. - Introduce MLX public trainer API shims and compatibility helpers (training args normalization, TRL shims, torch.cuda-shaped helpers) for MLX imports.
- Expand Studio MLX worker behavior (stop/cancel polling, output dir resolution, Xet stall retry, progress/event handling) and add focused test coverage.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
unsloth/chat_templates.py |
Makes imports more MLX/torch-free friendly and adds MLX tokenizer wrapper handling in get_chat_template. |
unsloth/__init__.py |
Adds MLX public trainer/arguments shims, CUDA-shaped memory helpers, and MLX compatibility patches. |
unsloth_cli/commands/train.py |
Adds MLX backend selection + Transformers sidecar activation before trainer import; improves CLI wait/join behavior. |
tests/python/test_mlx_public_trainer_api.py |
New tests validating the MLX public trainer API surface, shims, and compatibility behavior. |
studio/backend/tests/test_training_preflight.py |
Adds coverage for CLI activation order, MLX adapter behavior (progress, retry/cancel), and worker side effects. |
studio/backend/tests/test_mlx_training_worker_config.py |
Updates optimizer validation expectation to match new messaging/normalization path. |
studio/backend/core/training/worker.py |
Refactors/extends MLX worker lifecycle: stop polling, output dir handling, Xet stall watchdog, attempt IDs, and shared entrypoint. |
studio/backend/core/training/training.py |
Introduces shared MLX backend detection + shared worker config builder; adds an MLX trainer adapter. |
studio/backend/core/training/trainer.py |
Makes UnslothTrainer backend-aware via __new__ dispatch to the MLX adapter and reuses shared progress type. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
68e324b to
acee331
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: acee331e55
ℹ️ 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".
acee331 to
79f2c12
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 79f2c12b88
ℹ️ 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".
79f2c12 to
2e50d99
Compare
Route the MLX backend through create_mlx_trainer_adapter so the torch-free Apple Silicon path never imports trainer.py (torch/unsloth/trl). Replace from __future__ import annotations with typing.Optional/Union so the CLI annotations stay Python 3.9 compatible without the unused-import lint hit.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: accd1c9901
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| output_dir = config.get("output_dir", "") | ||
| if not output_dir: | ||
| output_dir = f"{default_run_dir_name(model_name)}_{int(time.time())}" |
There was a problem hiding this comment.
Preserve project names in MLX output dirs
For Studio MLX jobs that set project_name but leave output_dir empty, _build_training_worker_config now carries config["project_name"], but this new helper still builds the default folder only from model_name. Fresh evidence relative to the earlier project-name comment is that the field is preserved in config now, but dropped here, regressing the previous build_default_output_dir_name(model_name, config.get("project_name")) behavior so saved MLX runs lose the project suffix and project-aware checkpoint/history matching won't find the expected default path.
Useful? React with 👍 / 👎.
| def _skip_internal_final_save(*args, **kwargs): | ||
| raise ValueError("worker owns final save") | ||
|
|
||
| trainer.save_model = _skip_internal_final_save |
There was a problem hiding this comment.
Allow MLX checkpoint saves during training
When an MLX run sets save_steps > 0, that value is passed into MLXTrainingConfig, but trainer.save_model is replaced with a function that always raises for the entire trainer.train() call. Any scheduled checkpoint save that goes through save_model will therefore abort the run instead of writing a checkpoint; if the goal is only to avoid a duplicate final save, suppress just that final save path rather than every save during training.
Useful? React with 👍 / 👎.
| def should_use_mlx_training_backend(*, device: Optional[Any] = None) -> bool: | ||
| if device is not None: | ||
| return is_mlx_training_device(device) | ||
| return is_apple_silicon_training_platform() |
There was a problem hiding this comment.
Honor forced GPU path in MLX dispatch
On Apple Silicon with UNSLOTH_FORCE_GPU_PATH=1, the package-level MLX gate is intentionally disabled, but this shared training dispatch ignores that override and returns the MLX backend solely from the platform check. Because the CLI and UnslothTrainer.__new__ now call this helper before choosing the torch trainer, forced-GPU/torch-path runs on Apple Silicon are still routed to the MLX adapter despite the explicit environment override.
Useful? React with 👍 / 👎.
| if callable(wrapped): | ||
| return wrapped(text, *args, **kwargs) |
There was a problem hiding this comment.
Strip PyTorch tensor requests from MLX raw-text tokenization
For MLX raw-text runs on a torch-free install, RawTextDataLoader still calls the tokenizer with return_tensors="pt"; when the MLX wrapper exposes a callable _tokenizer, this proxy forwards that request directly to the underlying HF tokenizer, which then tries to create PyTorch tensors and fails before training starts. The MLX path should remove or override return_tensors here and return plain token IDs, matching the non-callable fallback below.
Useful? React with 👍 / 👎.
On a torch-free MLX install, RawTextDataLoader calls the tokenizer with return_tensors='pt'; the callable proxy forwarded that to the HF tokenizer, which tried to build torch tensors and failed before training. Drop return_tensors so the MLX path returns plain token ids.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…thai#15775) The legacy `unsloth-cli.py` documents `--dtype None` (its own usage example, and the help says "None for auto detection"), but on every non-MLX backend it crashes: `FastLanguageModel.from_pretrained` asserts `dtype` is `None` or a torch dtype, and the CLI passes the string `"None"`. **Cause:** `_normalize_dtype` (added in unslothai#6709) only mapped `"None"` to `None` when `is_mlx` was true. **Fix:** map `""`, `none` and `auto` (any case) to `None` on every backend, and drop the unused `is_mlx` parameter. **Test:** `unsloth_cli/tests/test_legacy_cli_dtype.py` runs `run(args)` with stubbed `unsloth`, `datasets`, `transformers` and `trl` and checks the `dtype` that reaches `from_pretrained`. It fails before (4 failed, `assert '' == None` and the other spellings) and passes after (5 passed). `ruff check` is clean. I did not run the real loader (no accelerator here). --------- Co-authored-by: Daniel Han <[email protected]>
Summary
This adds MLX backend support for the CLI training paths while keeping CUDA behavior on the existing torch/TRL trainer path.
UnslothTrainerbackend-aware sounsloth traincan dispatch to the shared MLX worker path on Apple Silicon / MLX.unsloth-cli.pyscript for MLX by skipping CUDA device-map setup, normalizing MLX dtype auto values, adapting raw-text loading for MLX tokenizers, filtering unsupported MLX SFT config args, and using the MLX merged-save API.unsloth trainandunsloth-cli.py; CUDA still uses the existing trainer, tokenized raw-text loading, DDP device-map setup, and save/push flow.Scope
In scope:
unsloth train.unsloth-cli.pyMLX compatibility for one-process local training.Out of scope:
unsloth-cli.pyscript; this path was validated with a real MLX smoke instead.Validation
Merged latest
origin/maininto this branch, then ran:Result:
14 passedfor the focused preflight test file.Real Apple Silicon
unsloth trainsmoke:PYTHONPATH=$PWD unsloth train \ --model mlx-community/SmolLM-135M-Instruct-4bit \ --local-dataset /tmp/unsloth-cli-mlx-smoke/train.jsonl \ --format-type alpaca \ --output-dir /tmp/unsloth-cli-mlx-smoke/out \ --max-steps 1 \ --num-epochs 1 \ --batch-size 1 \ --gradient-accumulation-steps 1 \ --warmup-steps 0 \ --save-steps 0 \ --max-seq-length 128 \ --lora-r 4 \ --lora-alpha 8 \ --target-modules q_proj,v_projResult: completed one MLX LoRA step and saved adapters plus tokenizer/config files to
/tmp/unsloth-cli-mlx-smoke/out.Real Apple Silicon legacy
unsloth-cli.pysmoke:Result: completed one MLX LoRA step and saved adapter/tokenizer artifacts to
/tmp/unsloth-merged-cli-mlx-smoke/model.Note: the
unsloth trainsmoke usesPYTHONPATH=$PWDonly to force this worktree in the shared development venv, whose console script otherwise imports the editable package fromsite-packages. A release install of this branch should not need that workaround.