Skip to content

Add MLX backend support for CLI unsloth train - #6709

Merged
danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:feat/cli-mlx-backend-aware
Jul 8, 2026
Merged

danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:feat/cli-mlx-backend-aware

Conversation

@Lyxot

@Lyxot Lyxot commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This adds MLX backend support for the CLI training paths while keeping CUDA behavior on the existing torch/TRL trainer path.

  • Makes Studio's existing UnslothTrainer backend-aware so unsloth train can dispatch to the shared MLX worker path on Apple Silicon / MLX.
  • Reuses the Studio MLX worker configuration, progress payload, lifecycle handling, and Transformers sidecar activation for CLI runs.
  • Supports CLI local dataset paths and external output directories in the MLX worker path.
  • Extends the legacy unsloth-cli.py script 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.
  • Preserves CUDA behavior for unsloth train and unsloth-cli.py; CUDA still uses the existing trainer, tokenized raw-text loading, DDP device-map setup, and save/push flow.

Scope

In scope:

  • MLX dispatch for CLI unsloth train.
  • Shared Studio/CLI MLX worker configuration.
  • MLX worker lifecycle behavior needed by CLI training.
  • CLI local dataset and output directory handling for MLX runs.
  • Legacy unsloth-cli.py MLX compatibility for one-process local training.

Out of scope:

  • CUDA multi-GPU behavior.
  • Dependency version checks or dependency existence gates.
  • A new CLI-only trainer class.
  • Broad Studio training behavior unrelated to CLI MLX training.
  • New unit tests for the legacy unsloth-cli.py script; this path was validated with a real MLX smoke instead.

Validation

Merged latest origin/main into this branch, then ran:

python -m py_compile unsloth-cli.py
python unsloth-cli.py --help
unsloth train --help
pytest studio/backend/tests/test_training_preflight.py -q

Result: 14 passed for the focused preflight test file.

Real Apple Silicon unsloth train smoke:

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_proj

Result: 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.py smoke:

python unsloth-cli.py \
  --model_name mlx-community/Qwen3-0.6B-4bit \
  --raw_text_file /tmp/unsloth-merged-cli-mlx-smoke/train.txt \
  --max_seq_length 128 \
  --per_device_train_batch_size 1 \
  --gradient_accumulation_steps 1 \
  --max_steps 1 \
  --logging_steps 1 \
  --output_dir /tmp/unsloth-merged-cli-mlx-smoke/out \
  --save_model \
  --save_method lora \
  --save_path /tmp/unsloth-merged-cli-mlx-smoke/model

Result: completed one MLX LoRA step and saved adapter/tokenizer artifacts to /tmp/unsloth-merged-cli-mlx-smoke/model.

Note: the unsloth train smoke uses PYTHONPATH=$PWD only to force this worktree in the shared development venv, whose console script otherwise imports the editable package from site-packages. A release install of this branch should not need that workaround.

@Lyxot
Lyxot requested a review from danielhanchen as a code owner June 26, 2026 20:25
Copilot AI review requested due to automatic review settings June 26, 2026 20:25

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

Comment thread studio/backend/core/training/worker.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/chat_templates.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: 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".

Comment thread unsloth/__init__.py Resolved
Comment thread studio/backend/core/training/trainer.py Resolved
Comment thread unsloth/chat_templates.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

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 train command 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.

Comment thread unsloth/chat_templates.py Resolved
Comment thread studio/backend/core/training/worker.py Resolved
Comment thread unsloth_cli/commands/train.py Resolved
@Lyxot
Lyxot force-pushed the feat/cli-mlx-backend-aware branch 2 times, most recently from 68e324b to acee331 Compare July 2, 2026 09:18

@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: 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".

Comment thread unsloth/chat_templates.py Resolved
Comment thread unsloth_cli/commands/train.py Resolved
@Lyxot
Lyxot force-pushed the feat/cli-mlx-backend-aware branch from acee331 to 79f2c12 Compare July 2, 2026 09:38

@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: 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".

@Lyxot
Lyxot force-pushed the feat/cli-mlx-backend-aware branch from 79f2c12 to 2e50d99 Compare July 3, 2026 14:32
Lyxot and others added 8 commits July 3, 2026 22:42
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@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: 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())}"

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

Comment on lines +2073 to +2076
def _skip_internal_final_save(*args, **kwargs):
raise ValueError("worker owns final save")

trainer.save_model = _skip_internal_final_save

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

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

Comment thread unsloth-cli.py
Comment on lines +52 to +53
if callable(wrapped):
return wrapped(text, *args, **kwargs)

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

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 117b504dfc

ℹ️ 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 38dacb8 into unslothai:main Jul 8, 2026
42 of 44 checks passed
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 6, 2026
…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]>
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.

3 participants