Repository navigation
Add MLX-aware public Unsloth trainer API - #6462
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a comprehensive compatibility layer and public trainer API for the MLX backend in Unsloth, allowing SFT notebooks designed for CUDA/TRL to run seamlessly on Apple Silicon. Key changes include the implementation of UnslothTrainingArguments and UnslothTrainer which map TRL-style arguments to MLX-native configurations, automatic shimming of the trl module, and portable GPU/device memory statistics helpers (get_gpu_memory_stats and clear_gpu_memory) for both MLX and CUDA/ROCm/XPU backends. Additionally, get_chat_template was updated to avoid importing CUDA-heavy saving functions when on MLX, and a robust suite of unit tests was added to verify these compatibility surfaces. No review comments were provided, so there is no additional feedback to address.
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.
|
@codex review |
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds a backend-aware public UnslothTrainer / UnslothTrainingArguments API that routes supported notebooks to an MLX implementation on Apple Silicon while preserving existing GPU behavior, plus lightweight notebook helper utilities and compatibility shims.
Changes:
- Introduces MLX-specific public trainer/config implementations and installs shims for
trl.SFTTrainer/trl.SFTConfigandunsloth.trainerwhen running on MLX. - Makes chat template utilities more MLX-friendly via lazy imports and MLX-specific routing behavior.
- Reuses the shared zoo MLX optimizer normalizer in Studio’s MLX worker instead of maintaining a separate optimizer map.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| unsloth/chat_templates.py | Adds MLX-aware routing for tokenizer patching and avoids Torch/CUDA-heavy imports until needed. |
| unsloth/init.py | Implements MLX public trainer/config surface, notebook helper APIs, and runtime shims for TRL + unsloth.trainer. |
| tests/python/test_mlx_public_trainer_api.py | Adds extensive tests validating the MLX public trainer API behavior and shims. |
| studio/backend/core/training/worker.py | Switches Studio MLX optimizer normalization to the zoo shared helper. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3d2358580e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 967cff58fc
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60385efb06
ℹ️ 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".
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Thanks for the review. Two fixed in code, one fixed by scoping the alias, one already handled by the current path, plus the CI failure. Fixed
Already handled
CI ( The failing step was |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 757d136e0e
ℹ️ 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".
Address review on the MLX public API: - The SFTConfig identity tests asserted trl.SFTConfig is UnslothTrainingArguments, but the alias now points at the _MLXSFTConfig subclass that preserves TRL's epoch default, so the MLX suite failed before testing the shim. Assert issubclass instead. - torch.cuda.reset_peak_memory_stats was a no-op, so max_memory_reserved kept earlier model-load peaks across a scoped run. Wire it to mx.reset_peak_memory with the same core/metal fallback used for the reads. - The unsupported-trainer stubs were a fixed list, so trainers outside it (a newer RLOOTrainer) still routed to the real torch trainer. Derive the set from trl.__all__ (every non-SFT *Trainer) so all non-SFT surfaces fail with a clear MLX message; names come from __all__ so trl is never resolved. - The non-MLX export smoke skipped only on missing bitsandbytes/triton; other absent GPU deps (numpy/torch/unsloth-zoo, or _gpu_init re-raising ImportError) made it fail on CPU hosts. Skip on any ImportError.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dba9c311ca
ℹ️ 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".
|
I still see a few unresolved review items that should be fixed before merge. Please address them or explain why they’re safe to resolve as-is. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 67e449b44c
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 87fc3c5291
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0dceea5ecd
ℹ️ 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".
| train_on_responses_only = standardize_data_formats = None | ||
| standardize_sharegpt = standardize_data_formats |
There was a problem hiding this comment.
Return lazy helper functions instead of None
When unsloth_zoo.dataset_utils raises ImportError (the torch-free MLX path this guard is meant to support), these public helpers are bound to None while still being exported from unsloth.chat_templates. A caller doing from unsloth.chat_templates import train_on_responses_only or standardize_sharegpt now gets a successful import followed by a NoneType call failure instead of a usable lazy wrapper or a clear call-time error; define small wrappers that import the zoo helper when called.
Useful? React with 👍 / 👎.
|
One packaging note for the MLX review thread: the current macOS release environment is not torch-free. On Apple Silicon, So for the current release-style macOS env, having |
The RELOAD-GGUF-via-llama-cli step timed out even at 8 tokens (>420s), so it is a fixed hang, not per-token cost: on the paravirtual macOS runner GPU llama.cpp's Metal backend stalls, and the gemma3 GGUF advertises a 32768 context that llama-cli would otherwise fully allocate. Run llama-cli CPU-only (-ngl 0) with a small context (-c 256); keep generation short. All env-tunable (UNSLOTH_GGUF_RELOAD_NGL / _CTX / _N / _THREADS / _TIMEOUT). Also print llama.cpp's partial stdout/stderr on timeout so a future hang is diagnosable instead of an opaque TimeoutExpired.
|
@codex review |
The GGUF reload via llama-cli timed out on the runner even CPU-only with a tiny context and 8 tokens. Root cause is the format, not the flags: the smoke exported quantization_method='not_quantized', which maps to a bf16 GGUF, and llama.cpp's bf16 CPU decode is unusably slow on the paravirtual macOS runner. Export q8_0 (fast_quantized, the exporter default and what users deploy) instead -- llama.cpp has optimized q8_0 CPU kernels, so the fresh-process reload loads and generates in seconds. The reload stays CPU-only (-ngl 0) with a small context.
|
I ran focused MLX-only fork check on this PR: https://github.com/Imagineer99/unsloth/actions/runs/28590005316 Main MLX path looks good, apple silicon MLX detection passed, dispatch tests passed, real MLX train passed, and both LoRA + merged_16bit reloads matched the in-memory generation. Only two things stood out:
Overall, MLX training looks healthy here, the remaining seem like follow-ups for the TRL shim test and GGUF reload smoke test. |
# Conflicts: # tests/studio/run_real_mlx_smoke.py
…hai#6462/#790 merged Point the unmigrated-notebook macos-14 matrix at unslothai/unsloth@main and unslothai/unsloth-zoo@main (the merged MLX shims) instead of the Lyxot fork branches. Proves stock notebooks from unslothai/notebooks@main run end-to-end on Apple Silicon MLX with the shipped packages, no per-notebook changes.

Summary
This is the main PR in the MLX notebook-compatibility series. It adds a backend-aware public
UnslothTrainer/UnslothTrainingArgumentsAPI so supported Unsloth notebooks can import trainer objects fromunslothand run unchanged by the end user on Apple Silicon MLX, while preserving the existing CUDA/ROCm/XPU path.The intended notebook contract is:
SFTTrainer/SFTConfigmanually.Companion PRs
These three PRs are designed to land together. This PR provides the public API and backend routing, the zoo PR provides the shared MLX trainer internals needed by that route, and the notebooks PR points supported notebooks at the new public API.
Implementation Details
Public trainer API:
UnslothTrainerandUnslothTrainingArgumentsas public imports fromunslothon MLX.UnslothTrainersubclasses the existingunsloth_zoo.mlx.trainer.MLXTrainerand normalizes common TRLSFTTrainerconstructor shapes into MLX trainer arguments.unsloth.trainer.UnslothTrainerremains anSFTTrainersubclass, so replacing notebook imports does not change the GPU backend trainer semantics.import unslothso old notebooks that still importSFTTrainer/SFTConfigfromtrlcan be routed to the MLX-compatible public trainer objects.Training argument compatibility:
SFTConfig/TrainingArgumentskwargs throughUnslothTrainingArgumentson MLX.max_lengthintomax_seq_lengthand mirrors CUDA context-length behavior when the notebook leaves the trainer max length implicit.num_train_epochs-driven runs by not forcingmax_stepswhen a notebook explicitly chooses epochs.save_strategy="no"by mapping it to the MLXsave_steps=0behavior.warmup_ratiothrough the zoo trainer after total steps are known, matching HF/CUDA semantics.dataset_order="torch_randperm"only for the publicUnslothTrainerroute when the user did not explicitly request a dataset order, so direct MLX trainer defaults remain available.append_eos=Falseonly for the publicUnslothTrainerroute when the user did not explicitly request an EOS policy, matching CUDA notebook behavior where the chat template owns EOS.max_grad_norm=1.0only for the publicUnslothTrainerroute when no MLX grad clipping knob was explicitly supplied.adamw_8bitthrough the shared zoo_normalize_mlx_optimizer_namehelper, so notebook defaults continue to work on MLX without duplicating alias maps in this repo.Import and helper behavior:
get_gpu_memory_stats()andclear_gpu_memory()as backend-safe notebook helpers.torch.cuda/torch.xpuwhere available.mlx.corepeak/cache APIs.chat_templates.pyimport-light by importing tokenizer utilities only at call sites that need them.Studio touch point:
Non-Goals / Deferred Work
data_collatorsupport on MLX remains deferred. MLX raises instead of silently accepting unsupported custom collators.UnslothTrainerAPI.Real Gemma3 Notebook Parity Run
I ran a real supported Gemma3 SFT notebook path from
nb/Gemma3_(270M).ipynbon three variants. The runner follows the notebook cells for model load, LoRA setup, Gemma3 chat template,Thytu/ChessInstructformatting, andtrain_on_responses_only; the only training change ismax_steps=100 -> 10so the PR can record a short curve. No model weights over 5GB were downloaded.Run configuration:
unsloth/gemma-3-270m-itThytu/ChessInstruct,train[:10000]2048r=128,lora_alpha=128, target modulesq_proj/k_proj/v_proj/o_proj/gate_proj/up_proj/down_projper_device_train_batch_size=4,gradient_accumulation_steps=1, effective batch size 4warmup_steps=5,learning_rate=5e-5,lr_scheduler_type="linear"optim="adamw_8bit"34072.11.0+cu128, Transformers5.5.0, TRL0.24.0mlx-lm 0.31.3, Transformers5.5.0, TRL0.24.0Variant commits:
unslothai/unsloth@45f060899e56d8a8d218529733075814148f6b19+unslothai/unsloth-zoo@28063c2a28b148b32390476dc86d2940395416af, using notebook-maintrl.SFTTrainer/SFTConfigLyxot/unsloth@60385efb06d236202a8adc2540a0210935f94511+Lyxot/unsloth-zoo@6685266e567511fd2e582ab677834dc0345a62b7, using branchUnslothTrainer/UnslothTrainingArgumentsLyxot/unsloth@1040ccccf0905df2ae4f237fb6953bfad1715827+Lyxot/unsloth-zoo@6685266e567511fd2e582ab677834dc0345a62b7, using branchUnslothTrainer/UnslothTrainingArgumentsResults:
Curve summary:
0.0; max absolute grad-norm delta0.0.0.0357; mean absolute loss delta0.0147; final loss0.8565vs CUDA0.8521; final grad norm8.8934vs CUDA8.8184.481, matching the previous 30-step parity run's first 10 steps after removing the extra EOS token.1.8009, CUDA branch1.8009, MLX branch1.7881.Validation
Focused local validation on the current PR heads:
PYTHONPATH=<unsloth branch>:<zoo branch> python -m pytest tests/python/test_mlx_public_trainer_api.py -q35 passed, 1 skippedPYTHONPATH=<unsloth branch>:<zoo branch>:<studio backend> python -m pytest studio/backend/tests/test_mlx_training_worker_config.py -q14 passedadamw_8bit -> adamwpaged_adamw_8bit -> adamwadamw_torch_fused -> adamwadamw,sgd,lionremain unchangedgit diff --checkpassed in both unsloth and unsloth-zoo worktrees after the final optimizer-normalization refactor.The visible unrelated CI failures observed before the latest push were in Studio/backend and unrelated zoo-main merge tests, not in this MLX trainer API surface. The latest CI for this PR was still running when this description was rewritten.