Repository navigation
Train on CPU when no GPU is found, instead of refusing to import - #14717
Conversation
|
@codex review |
|
@codex security review |
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
…tes training and export itself
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cdb00fbfc2
ℹ️ 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".
| if _zoo_cpu_backend("cpu_backend_allowed"): | ||
| return "cpu" |
There was a problem hiding this comment.
Add CPU handling to the public device helpers
Once this branch returns "cpu", importing unsloth.device_type sets _DEVICE_MODULE to torch.cpu, but the public get_device_stats() still unconditionally calls _DEVICE_MODULE.get_device_properties(0) and then falls through to the NVIDIA/CUDA formatting arm. On PyTorch builds without that CPU method it raises immediately, and otherwise it reports CPU execution as an NVIDIA CUDA device; add an explicit CPU implementation or mark the device module unavailable for these GPU-only helpers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable: on the CPU backend _gpu_init stops right after import unsloth_zoo, so unsloth.device_type and its stats helpers are never imported or called; the only caller of get_device_stats is the GPU loader.
…earning_rate gets its own optimizer group [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 51f352fb72
ℹ️ 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".
| # No accelerator at all: zoo chose its CPU backend and skipped every GPU patch. Stop here, before | ||
| # any CUDA/Triton work, and let __init__ load the CPU backend instead (as the MLX branch does). | ||
| if unsloth_zoo.__dict__.get("_IS_CPU_BACKEND", False): | ||
| from . import _CPUBackendSelected | ||
| raise _CPUBackendSelected() |
There was a problem hiding this comment.
Select the CPU backend before running GPU bootstrap checks
On a CPU-only host with a stable but mismatched torchvision, import unsloth never reaches this handoff because _gpu_init.py already calls torchvision_compatibility_check() at line 117, which raises for that mismatch; the Triton, vLLM, FBGEMM, and other GPU bootstrap work also runs first. This makes the new CPU fallback depend on otherwise irrelevant GPU companion packages, while the AST test only compares this handoff with the later explicit import torch and therefore misses the earlier work. Detect the zoo CPU selection before the GPU bootstrap, or bypass those checks when the CPU backend was selected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping it: the bootstrap prefix before import unsloth_zoo is shared on purpose so GPU import order stays byte-identical (same 8173 modules before and after). A mismatched torchvision raises the same actionable error on every host, CPU included, and transformers would trip over it anyway.
| except _CPUBackendSelected: | ||
| _IS_CPU_BACKEND = True | ||
| _sys_mod = __import__("sys").modules | ||
| _sys_mod.pop(f"{__name__}._gpu_init", None) | ||
| del _sys_mod | ||
| from ._cpu_init import * |
There was a problem hiding this comment.
Let FORCE_CPU override MLX detection
On Apple Silicon with MLX installed, setting UNSLOTH_FORCE_CPU=1 cannot select the new CPU backend because _IS_MLX is evaluated first and this handoff exists only inside the non-MLX branch. The CPU module explicitly documents UNSLOTH_FORCE_CPU=1 as an entry path, so the force flag should suppress MLX detection or be handled before branching; otherwise the process silently loads the MLX backend despite the explicit request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intended: UNSLOTH_FORCE_CPU is the opt-in for CUDA / ROCm / XPU / NPU hosts. Apple Silicon with MLX keeps the MLX backend, which is the supported trainer there.
…on the package, fallback test stays off MLX / XPU / NPU
…ore-style optimizers with embedding_learning_rate [skip ci]
…embeddings, then embeddings; decay first) [skip ci]
…for embedding lr [skip ci]
…porting it Importing unsloth_zoo.device_type from unsloth.device_type reordered zoo's own initialisation under harnesses that preload device_type on its own (the test suite's CUDA spoof), which sent Qwen3.5's linear attention down the Triton path on CPU runners. import unsloth always imports unsloth_zoo first, so the check only needs sys.modules. [skip ci]
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…lothai#1970) ## Summary Unsloth currently refuses to import on a machine with no GPU (`NotImplementedError: Unsloth cannot find any torch accelerator? You need a GPU.`). This adds a CPU training backend that is only selected when torch finds no accelerator at all, in the same way the MLX backend is layered on for Apple Silicon. GPU hosts (NVIDIA, AMD, Intel XPU, Ascend NPU) and MLX never import or execute any of it. Companion PR unslothai/unsloth#14717 wires `import unsloth` to it. ## When the CPU backend is chosen `unsloth_zoo.device_type` keeps every existing branch in the same order. Only the terminal "no accelerator" error changes, and only when: * `UNSLOTH_DISABLE_CPU_FALLBACK` is not `1` (set it to keep the old hard error), and * no GPU is present that this torch build cannot drive. An NVIDIA driver (`/proc/driver/nvidia/version` or `nvidia-smi`) or a ROCm runtime with a CPU torch wheel still raises the existing install error, so a wrong wheel never silently trains on CPU. GPUs hidden on purpose with `CUDA_VISIBLE_DEVICES=""` or `-1` do allow it. `UNSLOTH_FORCE_CPU=1` opts in on a GPU host. `UNSLOTH_ALLOW_CPU=1` (the CPU CI spoof that reports `cuda`) keeps its exact current meaning and wins over all of this. ## What runs on CPU (`unsloth_zoo/cpu/`) * `FastCPUModel`: `from_pretrained`, `get_peft_model`, `for_training`, `for_inference`, `save_pretrained_merged` (`lora` / `merged_16bit`), `push_to_hub_merged`, `save_pretrained_gguf`. Stock transformers + PEFT on CPU, SDPA attention. `generate(input_ids = tokenizer.apply_chat_template(..., return_tensors = "pt"))` works as in the notebooks (the BatchEncoding is unpacked like the GPU path does). * Mixed precision: bf16 autocast only where the CPU has bf16 in hardware (AMX, AVX512-BF16, Arm BF16), otherwise float32. Where `/proc/cpuinfo` is missing (Windows), a 512x512 bf16 autocast matmul is timed against fp32 instead. `fp16=True` maps to bf16 when that is native. On a CPU with AMX-FP16 and no native bf16, it runs real fp16 autocast with `torch.amp.GradScaler("cpu")`; accelerate otherwise turns fp16 on CPU into a silent fp32 run. `UNSLOTH_CPU_BF16=0/1` and `UNSLOTH_CPU_FP16=0/1` override. Measured on a LoRA-shaped MLP forward + backward, speedup over fp32 (fp32 = 1.0x): | CPU | bf16 autocast | fp16 autocast | |---|---|---| | Xeon 8559C (AMX-BF16, AVX512-FP16, Linux) | 1.9x to 2.7x (AMX) | 1.1x to 1.2x (no AMX-FP16) | | Neoverse N2 (Arm BF16 + FP16, Linux) | 3.0x | 0.9x | | EPYC 9V74 (AVX512-BF16 exposed, Linux) | 2.1x | about 100x slower | | Zen 4 runner (Windows, AVX512-BF16) | 2.0x | about 120x slower | | Another windows-latest runner (no native bf16) | about 100x slower | about 100x slower | | EPYC 7763 / 9V74 with AVX512 masked (AVX2 only, Linux) | about 180x slower | about 180x slower | | Neoverse N2 (Windows on Arm) | about 37x slower | about 76x slower | The slow cells are why bf16 and fp16 stay off unless a native kernel exists. The same runner label can land on either kind of host, so on Windows the choice comes from the timing probe, not a fixed guess. Staging: on the AVX512-BF16 Linux host the probe and the flags both pick bf16; on the Windows host without native bf16 the probe picks fp32. * `load_in_4bit=True` (the notebook default) uses the bitsandbytes CPU backend only when a real NF4 forward + backward probe passes, otherwise loads 16-bit with a message. Pre-quantized `*-bnb-4bit` repos load with their own config, or map to the base repo for 16-bit. * Chunked linear cross entropy: the SFT loss never materialises the full `(tokens, vocab)` logits. Same shift and `num_items_in_batch` normalisation as transformers' `ForCausalLMLoss`. Only used inside `SFTTrainer` steps with the default NLL loss, on an allowlist of plain-CE architectures (llama, mistral, qwen2, qwen3, phi3, gemma, olmo2, smollm3) whose head is a plain Linear; DPO / KTO / ORPO, other SFT losses, MoE heads and LoRA on `lm_head` keep the stock forward. `UNSLOTH_CPU_CHUNKED_CE=0` disables it. * Trainer defaults, patched only on the CPU backend: `use_cpu=True`, the mixed-precision mapping above, bitsandbytes / paged / fused / NPU / XLA optimizers mapped to `adamw_torch`, no pinned memory, no padding-free or packing. `SFTTrainer` also accepts the legacy `tokenizer=`, `dataset_text_field=`, `max_seq_length=` and `packing=` arguments notebooks still pass, including with a plain `TrainingArguments`. * `use_gradient_checkpointing="unsloth"` becomes plain non-reentrant recomputation (activations already live in host RAM). * `UNSLOTH_CPU_COMPILE=1` opt-in `torch.compile` (Inductor C++) per decoder layer. * The datasets folder-metadata path guard is installed on the CPU backend too (it lives with the GPU patches otherwise). ## bitsandbytes 0.50 CPU QLoRA workaround On AVX512-BF16 CPUs, `Linear4bit` repacks its weight in place on the first forward without grad (any eval or `generate()`), and never unpacks it. Backward through the packed weight is then wrong, so QLoRA silently stops learning after the first evaluation. The loader sets `support_avx512bf16_for_cpu = False` on every 4-bit layer. A test covers it and fails without the fix. ## Results (CPU only, `CUDA_VISIBLE_DEVICES=""`, no `UNSLOTH_ALLOW_CPU`) * Tiny Llama / Qwen3, LoRA r=8, 60 steps fp32: loss and eval match plain transformers + PEFT + TRL to 5 decimals at every step. * Chunked cross entropy matches HF exactly (SmolLM2-135M 0.36512 -> 0.20385 in both arms) with 24% to 38% lower peak RSS. * `import unsloth` on CPU takes about 11 s and loads no `unsloth.models`, `unsloth.kernels` or `unsloth_zoo.temporary_patches` modules. * On a CUDA host, the set of modules loaded by `import unsloth` is identical before and after this change (8172 modules), and `unsloth_zoo.cpu` is never imported. Not supported on CPU yet: vision / audio models and vLLM `fast_inference` raise before any download, 8-bit loading falls back to 16-bit with a message, and merging LoRA into a 4-bit model raises with a hint.
…processor (#15501) On a host without an accelerator, `import unsloth` hands off to the CPU backend (`unsloth/_cpu_init.py`, #14717). The GPU backend exports the dataprep helpers from `unsloth` (`_gpu_init.py`), but the CPU backend did not. So the documented `from unsloth import load_ebook_dataset` (#14453) raises `ImportError: cannot import name 'load_ebook_dataset'` on CPU-only hosts, and so do `RawTextDataLoader` and `TextPreprocessor`. The CPU backend now exports all three. It loads `dataprep/raw_text.py` and `dataprep/ebooks.py` by file, the way the MLX backend already does, because `dataprep/__init__` also imports `synthetic.py`, which needs a GPU device type. Neither file has relative imports. `test_cpu_backend_init.py::test_no_accelerator_loads_the_cpu_backend` now also checks the three names in its no-accelerator subprocess probe. The GPU-only module list it asserts against is unchanged. | | main | this PR | |---|---|---| | `test_cpu_backend_init.py` (CUDA hidden) | 1 failed, 6 passed, 1 skipped | 7 passed, 1 skipped |
… on GPU-less Chat only installs (unslothai#16175) ## Problem On a host without a GPU, Studio greys out Train with "Training needs an NVIDIA or AMD GPU.", although unslothai#14717 added CPU training. - **Full install** (the default; the installers put CPU PyTorch on such a host): the verdict is `no_gpu`. Even past the gate, the training worker's `import unsloth` refuses with "Unsloth cannot find any torch accelerator? You need a GPU." - **Desktop Chat only install:** the verdict is also `no_gpu`, not `no_torch`, so Install Training (unslothai#14861) and the Settings upgrade row (unslothai#14593) are not offered. ## Cause Both gates predate CPU training. unslothai#14593 reports `no_torch` off Mac only when `_a_gpu_build_would_train_here()` finds a card, since a full install on a GPU-less host could not train then. unslothai#14717 kept Studio out of CPU training by setting `UNSLOTH_DISABLE_CPU_FALLBACK=1` in `main.py` and `run.py`, which the training worker inherits. unsloth-zoo#2162 has since made Studio's training worker run on the CPU backend, and 2026.10.11 ships both. ## Fix - `hardware.py`: `trains_on_cpu(reason)` is true for `no_gpu` with PyTorch installed and for `no_torch` without a usable GPU. `/api/health` reports it as `cpu_training`. `chat_only` stays true, so Chat, Export and Video are unchanged. - Every off-Mac `--no-torch` install reports `no_torch`, so Install Training is offered there too. - The training worker sets `UNSLOTH_FORCE_CPU=1` when `trains_on_cpu()` holds, before importing unsloth. Every other Studio process keeps the opt-out. - `/api/train/start` refuses vision and audio datasets, embedding, decision and drafter training on CPU with a 400, since the CPU backend trains text models with SFTTrainer only. - Frontend: Train, `/studio` and its shortcuts follow a new `isTrainUnavailable()` instead of `isChatOnly()`. The Train page notes that training runs on the CPU and, as on MLX, hides the drafter section and leaves a saved or imported drafter out of the request. On a GPU-less Chat only install the upgrade dialog and Settings row promise CPU training only, not export or video. ## Behavior boundaries - A host whose GPU this PyTorch cannot use keeps its repair message instead of falling back to CPU. - CPU training is on by default, as `import unsloth` has been since unslothai#14717. - A vision model with a text dataset is not refused up front; the CPU backend's own error surfaces at model load. ## Verification Live A/B on Linux with `CUDA_VISIBLE_DEVICES=""`, `trl-internal-testing/tiny-Qwen3ForCausalLM` and a 64-row JSONL, through `/api/train/start` with Studio defaults: | | main | this PR | |---|---|---| | `/api/health` | `chat_only`, `no_gpu` | `chat_only`, `no_gpu`, `cpu_training: true` | | LoRA, 6 steps | "Unsloth cannot find any torch accelerator? You need a GPU." | completes, adapter saved | | Full finetuning, 4 steps | not run | completes | | Image dataset | not run | 400 | New backend tests cover the verdicts, the health field, the start route refusals and the worker environment; they fail on main. Backend files touching these paths: 8,726 passed, with one failure that also fails on main. The full frontend suite has no failures beyond main's. Typecheck, i18n parity and the bundle budget pass, and lint has no new findings. Not tested: the Desktop Install Training flow end to end on a GPU-less host, Windows or macOS, and models larger than the tiny test model. ## Screenshots `main` (`4d28d72802`) and this PR, two isolated installs with every GPU hidden, fresh en-US browser profile. Sidebar with the Train row hovered: <img width="2424" height="846" alt="cpu_training_train_row" src="https://github.com/user-attachments/assets/5a954770-3bc7-4c83-ba28-fe0d1df87509" /> `/studio` opened directly. On `main` it redirects to Chat: <img width="4424" height="936" alt="cpu_training_train_page" src="https://github.com/user-attachments/assets/9bf247f3-76b5-4e8c-bcb7-a877086ae330" /> ### Before / after on a GPU-less host Two isolated installs (merge base `c510fc1ca` vs this PR), both launched with `CUDA_VISIBLE_DEVICES=""`, `/studio` opened directly. Before: the route redirects to Chat and Train is greyed out. After: the Train page stays open with the CPU training notice.  --------- Co-authored-by: Daniel Han <[email protected]>
Summary
import unslothraises on any machine without a GPU. With the companion unsloth-zoo PR, a host where torch finds no accelerator now loads a CPU training backend instead, the same way Apple Silicon loads the MLX backend. Nothing changes on NVIDIA, AMD, Intel XPU, Ascend NPU or MLX hosts.Requires unslothai/unsloth-zoo#1970. With an older unsloth-zoo the behaviour is unchanged (the old error).
How it is wired
unsloth/_gpu_init.py: right afterimport unsloth_zoo, if zoo selected its CPU backend, raise_CPUBackendSelectedbefore any CUDA / Triton work. On GPU hosts this is one dict lookup.unsloth/__init__.py: the GPU branch catches it and loadsunsloth/_cpu_init.pyinstead, mirroring the MLX branch. The FSDP2 hook is skipped on CPU.unsloth/_cpu_init.py(new): exportsFastLanguageModel/FastModel(backed byunsloth_zoo.cpu.FastCPUModel),FastVisionModel(raises, not supported on CPU yet),is_bfloat16_supported, chat template helpers,train_on_responses_only,UnslothTrainer/UnslothTrainingArguments, and installs CPU trainer defaults. A banner says training is on CPU and how to turn the fallback off.unsloth/device_type.py: returns"cpu"at the terminal no-accelerator branch when zoo allows it (same rules as zoo), andDEVICE_COUNT = 0on CPU.unsloth/chat_templates.py:get_chat_templatetreats the CPU backend like MLX and skips the GPU save patching import.Selection rules
UNSLOTH_DISABLE_CPU_FALLBACK=1restores the hard error.UNSLOTH_FORCE_CPU=1opts in on a GPU host.UNSLOTH_ALLOW_CPU=1(the CPU CI spoof) keeps its exact current meaning.Notebook flow on a CPU machine
Unchanged user code:
FastLanguageModel.from_pretrained(..., load_in_4bit = True),get_peft_model,SFTTrainer(..., SFTConfig(optim = "adamw_8bit", fp16 = not is_bfloat16_supported(), ...))all work. 4-bit uses bitsandbytes' CPU backend when it works on that CPU, the 8-bit optimizer maps toadamw_torch, fp16 maps to bf16 where the CPU has it in hardware or fp32 otherwise.Studio / Desktop
No change. Studio decides chat-only vs training vs export from its own hardware detection, and its backend now sets
UNSLOTH_DISABLE_CPU_FALLBACK=1(setdefault, instudio/backend/run.pyandmain.py), so every Studio process keeps the old import refusal on a GPU-less host. Studio helpers that import Unsloth withUNSLOTH_ALLOW_CPU=1keep the spoof path.Related: #5091 (training on a machine where Unsloth finds no usable GPU; the Steam Deck GPU itself is not covered here).
Testing
CUDA_VISIBLE_DEVICES="", no spoof):import unslothin about 11 s, tiny Llama LoRA SFT withoptim="adamw_8bit", fp16=Truetrains (loss 10.38 -> 10.07 over 40 steps), all 28 LoRA tensors update, base weights stay frozen. Nounsloth.models/unsloth.kernelsmodule is imported.import unslothbefore and after (8172 modules), no CPU module imported.