Skip to content

Add MLX-aware public Unsloth trainer API - #6462

Merged
Imagineer99 merged 58 commits into
unslothai:mainfrom
Lyxot:mlx/trainer-api
Jul 2, 2026
Merged

Imagineer99 merged 58 commits into
unslothai:mainfrom
Lyxot:mlx/trainer-api

Conversation

@Lyxot

@Lyxot Lyxot commented Jun 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This is the main PR in the MLX notebook-compatibility series. It adds a backend-aware public UnslothTrainer / UnslothTrainingArguments API so supported Unsloth notebooks can import trainer objects from unsloth and run unchanged by the end user on Apple Silicon MLX, while preserving the existing CUDA/ROCm/XPU path.

The intended notebook contract is:

  • CUDA, ROCm, XPU, and existing GPU users keep the established Unsloth + TRL behavior.
  • MLX users get the MLX trainer route behind the same public Unsloth trainer/config names.
  • Notebooks do not need user-side edits to swap SFTTrainer / SFTConfig manually.
  • Unsupported task surfaces remain unsupported on MLX instead of being silently approximated.

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:

  • Adds UnslothTrainer and UnslothTrainingArguments as public imports from unsloth on MLX.
  • On MLX, UnslothTrainer subclasses the existing unsloth_zoo.mlx.trainer.MLXTrainer and normalizes common TRL SFTTrainer constructor shapes into MLX trainer arguments.
  • On CUDA/ROCm/XPU, the existing unsloth.trainer.UnslothTrainer remains an SFTTrainer subclass, so replacing notebook imports does not change the GPU backend trainer semantics.
  • Installs an MLX-only TRL SFT shim after import unsloth so old notebooks that still import SFTTrainer / SFTConfig from trl can be routed to the MLX-compatible public trainer objects.

Training argument compatibility:

  • Accepts notebook-style SFTConfig / TrainingArguments kwargs through UnslothTrainingArguments on MLX.
  • Normalizes max_length into max_seq_length and mirrors CUDA context-length behavior when the notebook leaves the trainer max length implicit.
  • Preserves num_train_epochs-driven runs by not forcing max_steps when a notebook explicitly chooses epochs.
  • Preserves save_strategy="no" by mapping it to the MLX save_steps=0 behavior.
  • Resolves warmup_ratio through the zoo trainer after total steps are known, matching HF/CUDA semantics.
  • Uses dataset_order="torch_randperm" only for the public UnslothTrainer route when the user did not explicitly request a dataset order, so direct MLX trainer defaults remain available.
  • Uses append_eos=False only for the public UnslothTrainer route when the user did not explicitly request an EOS policy, matching CUDA notebook behavior where the chat template owns EOS.
  • Applies CUDA-style max_grad_norm=1.0 only for the public UnslothTrainer route when no MLX grad clipping knob was explicitly supplied.
  • Normalizes CUDA/Studio optimizer aliases like adamw_8bit through the shared zoo _normalize_mlx_optimizer_name helper, so notebook defaults continue to work on MLX without duplicating alias maps in this repo.

Import and helper behavior:

  • Keeps MLX import startup light by lazy-importing chat-template and dataset helpers instead of eagerly importing the CUDA/Torch-heavy path.
  • Exposes get_gpu_memory_stats() and clear_gpu_memory() as backend-safe notebook helpers.
  • Keeps CUDA/ROCm/XPU memory helpers backed by torch.cuda / torch.xpu where available.
  • Keeps MLX memory helpers backed by mlx.core peak/cache APIs.
  • Keeps chat_templates.py import-light by importing tokenizer utilities only at call sites that need them.

Studio touch point:

  • Reuses the zoo MLX optimizer normalizer in Studio's MLX training worker instead of maintaining a separate Studio-only optimizer alias map.

Non-Goals / Deferred Work

  • Custom data_collator support on MLX remains deferred. MLX raises instead of silently accepting unsupported custom collators.
  • This does not attempt to support every TRL task. Unsupported task-specific args still fail explicitly on MLX.
  • This does not change CUDA/ROCm trainer internals beyond exposing and using the public UnslothTrainer API.

Real Gemma3 Notebook Parity Run

I ran a real supported Gemma3 SFT notebook path from nb/Gemma3_(270M).ipynb on three variants. The runner follows the notebook cells for model load, LoRA setup, Gemma3 chat template, Thytu/ChessInstruct formatting, and train_on_responses_only; the only training change is max_steps=100 -> 10 so the PR can record a short curve. No model weights over 5GB were downloaded.

Run configuration:

  • Model: unsloth/gemma-3-270m-it
  • Dataset: Thytu/ChessInstruct, train[:10000]
  • Filtering after response masking: 665 all-masked rows removed on both CUDA and MLX, leaving 9,335 usable examples
  • Sequence length: 2048
  • LoRA: r=128, lora_alpha=128, target modules q_proj/k_proj/v_proj/o_proj/gate_proj/up_proj/down_proj
  • Batch: per_device_train_batch_size=4, gradient_accumulation_steps=1, effective batch size 4
  • Scheduler: warmup_steps=5, learning_rate=5e-5, lr_scheduler_type="linear"
  • Optimizer argument: optim="adamw_8bit"
  • Seed: 3407
  • CUDA hardware: RTX 4070 SUPER, Torch 2.11.0+cu128, Transformers 5.5.0, TRL 0.24.0
  • MLX hardware: Apple Silicon / MLX, mlx-lm 0.31.3, Transformers 5.5.0, TRL 0.24.0

Variant commits:

  • CUDA main reference: unslothai/unsloth@45f060899e56d8a8d218529733075814148f6b19 + unslothai/unsloth-zoo@28063c2a28b148b32390476dc86d2940395416af, using notebook-main trl.SFTTrainer / SFTConfig
  • CUDA branch: Lyxot/unsloth@60385efb06d236202a8adc2540a0210935f94511 + Lyxot/unsloth-zoo@6685266e567511fd2e582ab677834dc0345a62b7, using branch UnslothTrainer / UnslothTrainingArguments
  • MLX branch retest: Lyxot/unsloth@1040ccccf0905df2ae4f237fb6953bfad1715827 + Lyxot/unsloth-zoo@6685266e567511fd2e582ab677834dc0345a62b7, using branch UnslothTrainer / UnslothTrainingArguments

Results:

Step CUDA main loss CUDA main grad CUDA branch loss CUDA branch grad MLX branch loss MLX branch grad
1 4.1118 97.9610 4.1118 97.9610 4.0985 91.4525
2 3.9207 95.0271 3.9207 95.0271 3.9070 91.9407
3 3.3180 78.2600 3.3180 78.2600 3.3060 77.0045
4 1.9192 53.1489 1.9192 53.1489 1.8891 52.4635
5 1.2203 23.5901 1.2203 23.5901 1.1846 25.1157
6 0.8083 9.4253 0.8083 9.4253 0.8041 9.2907
7 0.6018 7.3403 0.6018 7.3403 0.5780 6.5590
8 0.6660 7.1101 0.6660 7.1101 0.6714 6.1685
9 0.5907 6.9775 0.5907 6.9775 0.5859 6.7463
10 0.8521 8.8184 0.8521 8.8184 0.8565 8.8934

Curve summary:

  • CUDA branch vs CUDA main: max absolute loss delta 0.0; max absolute grad-norm delta 0.0.
  • MLX branch vs CUDA main: same curve shape with max absolute loss delta 0.0357; mean absolute loss delta 0.0147; final loss 0.8565 vs CUDA 0.8521; final grad norm 8.8934 vs CUDA 8.8184.
  • MLX retest trained tokens: 481, matching the previous 30-step parity run's first 10 steps after removing the extra EOS token.
  • Average train loss: CUDA main 1.8009, CUDA branch 1.8009, MLX branch 1.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 -q
    • 35 passed, 1 skipped
  • PYTHONPATH=<unsloth branch>:<zoo branch>:<studio backend> python -m pytest studio/backend/tests/test_mlx_training_worker_config.py -q
    • 14 passed
  • Zoo shared optimizer alias smoke:
    • adamw_8bit -> adamw
    • paged_adamw_8bit -> adamw
    • adamw_torch_fused -> adamw
    • native adamw, sgd, lion remain unchanged
  • git diff --check passed 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.

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

@Lyxot
Lyxot force-pushed the mlx/trainer-api branch from 1d5d88d to 67e0dd7 Compare June 19, 2026 07:26
@Lyxot
Lyxot marked this pull request as ready for review June 19, 2026 07:59
@Lyxot
Lyxot requested a review from danielhanchen as a code owner June 19, 2026 07:59
Copilot AI review requested due to automatic review settings June 19, 2026 07:59
@Lyxot

Lyxot commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

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 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.SFTConfig and unsloth.trainer when 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.

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

Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.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: 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".

Comment thread studio/backend/core/training/worker.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: 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".

Comment thread unsloth/chat_templates.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen

Copy link
Copy Markdown
Member

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

  • Avoid importing lazy TRL trainers while installing stubs (ae5d6b705). The stub installer no longer probes getattr(trl, "GRPOTrainer"), which triggers trl's lazy trainer import and pulls torch on a torch-free MLX install (crashing import unsloth just to check existence). It now decides what to replace from trl.__all__ plus already-materialized attributes (vars(trl)) and never resolves the real class. All six unsupported trainers are declared in trl.__all__, so they are still stubbed even torch-free. Covered by test_mlx_rl_trainer_stub_is_lazy_import_safe, which asserts trl.__getattr__ is never triggered.
  • Return current memory for allocation shims (ae5d6b705). torch.cuda.memory_reserved / memory_allocated now report current active MLX memory (mx.get_active_memory, with an mx.metal fallback), while max_memory_reserved / max_memory_allocated keep the peak high-water mark. mem_get_info also uses current active memory for the free figure, so a capacity check stays accurate after a transient spike. The test now asserts 0 <= memory_reserved() <= max_memory_reserved().
  • Preserve HF epoch defaults in the SFTConfig shim (757d136e0). trl.SFTConfig now aliases a thin subclass that seeds TRL's default num_train_epochs=3 (which disables the step cap) only when neither max_steps nor num_train_epochs is given, so an unmigrated SFTConfig(output_dir=...) runs TRL's default epochs instead of the native MLX 60-step default. Explicit max_steps / num_train_epochs pass through untouched, and the native UnslothTrainingArguments keeps its MLX default. Epoch mode is supported by the MLX trainer (unsloth_zoo/mlx/trainer.py:1480). Covered by test_mlx_sftconfig_alias_keeps_trl_epoch_default.

Already handled

  • Apply vision collator resizing before MLX batching. The recorded value is not a no-op. image_size is a real MLXTrainingConfig field (unsloth_zoo/mlx/trainer.py:661), so copying UnslothVisionDataCollator(resize=...) into args.image_size routes it into the config, and the MLX VLM path consumes it when building batches (unsloth_zoo/mlx/trainer.py:1867, :2305, :2320 all read getattr(args, "image_size", None)). So the requested max dimension is enforced by the MLX batcher, not dropped. test_mlx_trainer_forwards_vision_collator_resize_max covers the forwarding. Resizing at collation time for closer parity with the CUDA collator is a reasonable follow-up, but the current path does apply the resize.

CI (MLX CI on Mac M1 / dispatch) (8e0af3c0d)

The failing step was MLX export round-trip - RELOAD GGUF via llama-cli (fresh process), not a trainer path. reload_lora, generate_lora, reload_merged, generate_merged all pass and the BF16 GGUF exports fine; the failure was llama-cli ... gemma-3-270m-it.BF16.gguf -n 24 ... timing out after 300s (run_real_mlx_smoke.py, TimeoutExpired elapsed=330.95s). llama-cli is found (the #6777 path fix works) and the GGUF is valid; BF16 decode is CPU-bound on the runner at roughly 10s or more per token, so 24 tokens sat right on the 300s cliff. Since that step is a save/reload integrity smoke (it only needs a few chars of output), I cut generation to 8 tokens with explicit threads and a small headroom on the subprocess timeout, all env-tunable (UNSLOTH_GGUF_RELOAD_N / _THREADS / _TIMEOUT). That keeps the reload well under the 25 minute job budget.

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

Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
danielhanchen and others added 2 commits July 1, 2026 12:38
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.

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

Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
@Imagineer99

Copy link
Copy Markdown
Member

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.

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

Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.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: 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".

Comment thread unsloth/chat_templates.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
Comment thread unsloth/__init__.py Resolved
@Lyxot
Lyxot force-pushed the mlx/trainer-api branch from 87fc3c5 to 0dceea5 Compare July 1, 2026 16:53

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

Comment thread unsloth/chat_templates.py
Comment on lines +48 to 49
train_on_responses_only = standardize_data_formats = None
standardize_sharegpt = standardize_data_formats

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

@Lyxot

Lyxot commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

One packaging note for the MLX review thread: the current macOS release environment is not torch-free. On Apple Silicon, install.sh keeps SKIP_TORCH=false unless the user explicitly passes --no-torch / UNSLOTH_NO_TORCH=1 or hits the Intel Mac path, and macOS resolves to the PyTorch CPU wheel index before installing torch, torchvision, and torchaudio.

So for the current release-style macOS env, having torch and peft available is expected. Making utility imports fully torch-free is still a good hardening direction, but I think we can keep that as a future plan rather than treating it as a blocker for this PR.

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

Copy link
Copy Markdown
Member

@codex review

danielhanchen and others added 4 commits July 2, 2026 06:38
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.
@Imagineer99

Copy link
Copy Markdown
Member

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:

  • test_mlx_trl_shim_installs_real_trl_or_stub failed because trl.__version__ was the MLX fallback stub, 0.0.0+unsloth-mlx, while the test expected real TRL. I think this is probably a test/detection issue rather than a trainer failure.
  • GGUF reload timed out after 420s. The log says --no-conversation is not supported by llama-cli and suggests llama-completion, then it hangs.

Overall, MLX training looks healthy here, the remaining seem like follow-ups for the TRL shim test and GGUF reload smoke test.

@Imagineer99

Copy link
Copy Markdown
Member
image

Passes CI on fork, test issues correctly addressed, merging.

@Imagineer99
Imagineer99 merged commit d918245 into unslothai:main Jul 2, 2026
47 checks passed
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 3, 2026
…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.
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