Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Avoid 8-bit training optimizer on XPU (#10213)
Ben Younes070f29261736
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex f6c349c6da3..f8fa252bc4a 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -46,6 +46,7 @@ from core.training.diffusion_train_common import (EventCb,LATENT_CACHE_OVER_BUDGET,StopCb,+ bitsandbytes_optimizer_supported,_apply_perf_flags,_assert_trusted_base_model,_emit,@@ -2406,11 +2407,14 @@ def _make_optimizer(params, lr):if os.environ.get("UNSLOTH_DIFFUSION_FP32_OPTIM", "") in ("1", "true"):return torch.optim.AdamW(params, lr = lr)- try:- import bitsandbytes as bnb- return bnb.optim.AdamW8bit(params, lr = lr)- except Exception: # noqa: BLE001 -- bnb missing / no CUDA: fall back to torch AdamW- pass+ # Checked before construction, not around it: on XPU the 8-bit optimizer builds fine and+ # only dies at the first step(), which the except below would never see.+ if bitsandbytes_optimizer_supported():+ try:+ import bitsandbytes as bnb+ return bnb.optim.AdamW8bit(params, lr = lr)+ except Exception: # noqa: BLE001 -- bnb missing / no CUDA: fall back to torch AdamW+ passif torch.cuda.is_available():try:return torch.optim.AdamW(params, lr = lr, fused = True)diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.pyindex fcaa525d697..885aba8901e 100644--- a/studio/backend/core/training/diffusion_lora_trainer.py+++ b/studio/backend/core/training/diffusion_lora_trainer.py@@ -45,6 +45,7 @@ from core.training.diffusion_train_common import ( # noqa: F401StopCb,DiffusionLoraConfig,LATENT_CACHE_OVER_BUDGET,+ bitsandbytes_optimizer_supported,native_bf16_supported,_apply_perf_flags,_assert_trusted_base_model,@@ -758,11 +759,14 @@ def _make_lora_optimizer(params: list, lr: float) -> Any:if os.environ.get("UNSLOTH_DIFFUSION_FP32_OPTIM", "") in ("1", "true"):return torch.optim.AdamW(params, lr = lr)- try:- import bitsandbytes as bnb- return bnb.optim.AdamW8bit(params, lr = lr)- except Exception: # noqa: BLE001 -- bnb missing / no CUDA: fall back to torch AdamW- pass+ # Checked before construction, not around it: on XPU the 8-bit optimizer builds fine and+ # only dies at the first step(), which the except below would never see.+ if bitsandbytes_optimizer_supported():+ try:+ import bitsandbytes as bnb+ return bnb.optim.AdamW8bit(params, lr = lr)+ except Exception: # noqa: BLE001 -- bnb missing / no CUDA: fall back to torch AdamW+ passif torch.cuda.is_available():try:return torch.optim.AdamW(params, lr = lr, fused = True)diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex 372fe49fc19..c68b0f018d0 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -768,6 +768,27 @@ def dit_accelerator_missing_reason(resolved_family: str) -> Optional[str]:)+def bitsandbytes_optimizer_supported() -> bool:+ """Whether a bitsandbytes optimizer can complete an update on the SELECTED backend.++ False only when training actually runs on Intel XPU: bitsandbytes registers+ optimizer_update_8bit_blockwise (and optimizer_update_32bit) to Triton in every branch of+ backends/xpu/ops.py, and Intel's Triton backend asserts on a SYCL toolchain we do not ship.+ Construction still succeeds, so the trainers' try/except around the constructor never sees+ it -- the run dies at the first optimizer.step(). Mirrors core/training/training.py.++ Keyed on get_device(), NOT torch.xpu.is_available(): a hybrid host with an Intel iGPU beside+ an NVIDIA card reports both and detection prefers CUDA. Answering the presence question there+ would drop 8-bit on a CUDA run, and worse, change optimizer_key() so restore_resume_state+ refuses every existing AdamW8bit checkpoint with a ResumeError.+ """+ try:+ from utils.hardware import DeviceType, get_device+ return get_device() != DeviceType.XPU+ except Exception: # noqa: BLE001 -- a probe failure must not block a start+ return True++def training_precision_preflight_error(resolved_family: str, base_precision: str) -> Optional[str]:"""Reason the requested DiT precision cannot run on this host, else None -- checked by the startroute BEFORE evicting resident GPU workloads (the trainer's own checks fire only in thediff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 4442ecf098c..703e9e1cf2b 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -83,6 +83,22 @@ _MAX_TRACKED_START_REQUESTS = 64_MAX_START_CANCEL_TOMBSTONES = 1024_START_CANCEL_TOMBSTONE_TTL_S = 300.0_START_CANCELLED_ERROR_CODE = "training_start_cancelled"+DEFAULT_TRAINING_OPTIMIZER = "adamw_8bit"+XPU_SAFE_TRAINING_OPTIMIZER = "adamw_torch"+XPU_DEVICE_BACKEND = "xpu"+PAGED_BITSANDBYTES_TRAINING_OPTIMIZER = "paged_adamw_8bit"+ADAMW_BITSANDBYTES_TRAINING_OPTIMIZER = "adamw_bnb_8bit"+PAGED_32BIT_BITSANDBYTES_TRAINING_OPTIMIZER = "paged_adamw_32bit"+# Not a bit-width question: XPU routes optimizer_update_32bit to Triton too+# (bitsandbytes backends/xpu/ops.py), which asserts on a SYCL toolchain we do not ship.+XPU_UNSUPPORTED_BITSANDBYTES_OPTIMIZERS = frozenset(+ (+ DEFAULT_TRAINING_OPTIMIZER,+ PAGED_BITSANDBYTES_TRAINING_OPTIMIZER,+ ADAMW_BITSANDBYTES_TRAINING_OPTIMIZER,+ PAGED_32BIT_BITSANDBYTES_TRAINING_OPTIMIZER,+ )+)_pyplot = None_pyplot_failed = False@@ -198,8 +214,25 @@ def should_use_mlx_training_backend(*, device: Optional[Any] = None) -> bool:return is_apple_silicon_training_platform()+def normalize_training_optimizer_for_device(optimizer: Any, *, device_backend: str) -> Any:+ if not isinstance(optimizer, str):+ return optimizer+ optimizer_key = optimizer.strip().lower().replace("-", "_")+ if (+ device_backend == XPU_DEVICE_BACKEND+ and optimizer_key in XPU_UNSUPPORTED_BITSANDBYTES_OPTIMIZERS+ ):+ return XPU_SAFE_TRAINING_OPTIMIZER+ return optimizer++def _build_training_worker_config(values: dict[str, Any]) -> dict[str, Any]:"""Build the normalized worker config shared by Unsloth and the CLI adapter."""+ device_backend = get_device().value+ optimizer = normalize_training_optimizer_for_device(+ values.get("optim", DEFAULT_TRAINING_OPTIMIZER),+ device_backend = device_backend,+ )config = {"model_name": values["model_name"],"project_name": values.get("project_name"),@@ -258,7 +291,7 @@ def _build_training_worker_config(values: dict[str, Any]) -> dict[str, Any]:),"random_seed": _coerce_seed(values.get("random_seed")),"packing": values.get("packing", False),- "optim": values.get("optim", "adamw_8bit"),+ "optim": optimizer,"lr_scheduler_type": values.get("lr_scheduler_type", "linear"),"use_lora": values.get("use_lora", True),"lora_r": values.get("lora_r", 16),@@ -298,7 +331,7 @@ def _build_training_worker_config(values: dict[str, Any]) -> dict[str, Any]:if config["training_type"] == "Full Finetuning":config["load_in_4bit"] = False# The parent's detected backend: the worker's apply_gpu_ids() uses it without probing torch.- config["device_backend"] = get_device().value+ config["device_backend"] = device_backendreturn config@@ -1729,7 +1762,7 @@ class TrainingBackend:lora_rank = config.get("lora_r", 16),target_modules = config.get("target_modules"),gradient_checkpointing = config.get("gradient_checkpointing", "unsloth"),- optimizer = config.get("optim", "adamw_8bit"),+ optimizer = config.get("optim", DEFAULT_TRAINING_OPTIMIZER),)defer_auto_selection = Falsediff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex a2774bcebe1..92d25e8ee30 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -52,6 +52,7 @@ try:from core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,+ normalize_training_optimizer_for_device,)from core.training.resume import (can_resume_run,@@ -73,6 +74,7 @@ except ImportError:from core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,+ normalize_training_optimizer_for_device,)from core.training.resume import (can_resume_run,@@ -1720,6 +1722,12 @@ async def start_training(if not request.dataset_streaming and _hf_dataset_is_the_source(request):await asyncio.to_thread(_refuse_unauthorized_cached_dataset, request, hf_token)+ device_backend = getattr(_hw.DEVICE, "value", "") or ""+ training_optimizer = normalize_training_optimizer_for_device(+ request.optim,+ device_backend = device_backend,+ )+training_kwargs = {"model_name": model_preflight.model_name,"project_name": request.project_name,@@ -1766,7 +1774,7 @@ async def start_training("cast_norm_output_to_input_dtype": request.cast_norm_output_to_input_dtype,"random_seed": request.random_seed,"packing": request.packing,- "optim": request.optim,+ "optim": training_optimizer,"lr_scheduler_type": request.lr_scheduler_type,"use_lora": request.use_lora,"lora_r": request.lora_r,diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.pyindex e8b89330d10..fdb0ed1831e 100644--- a/studio/backend/tests/test_gpu_selection.py+++ b/studio/backend/tests/test_gpu_selection.py@@ -36,6 +36,11 @@ from utils.hardware import (import utils.hardware.hardware as _hw_module_BACKEND_ROOT = Path(__file__).resolve().parent.parent+DEFAULT_BITSANDBYTES_OPTIMIZER = "adamw_8bit"+PAGED_BITSANDBYTES_OPTIMIZER = "paged-adamw-8bit"+ADAMW_BITSANDBYTES_OPTIMIZER = "adamw_bnb_8bit"+PAGED_32BIT_BITSANDBYTES_OPTIMIZER = "paged_adamw_32bit"+XPU_SAFE_OPTIMIZER = "adamw_torch"async def _inline_to_thread(func, /, *args, **kwargs):@@ -979,6 +984,58 @@ class TestPreSpawnGpuResolution(_GpuCacheResetMixin, unittest.TestCase):self.assertEqual(config["resolved_gpu_ids"], [0, 1])self.assertEqual(config["gpu_selection"]["selection_mode"], "auto")+ def test_training_backend_swaps_bitsandbytes_optimizers_on_xpu(self):+ class DummyProcess:+ pid = 12345++ def start(self):+ return None++ class DummyThread:+ def start(self):+ return None++ dummy_queue = object()++ for optimizer in (+ DEFAULT_BITSANDBYTES_OPTIMIZER,+ PAGED_BITSANDBYTES_OPTIMIZER,+ ADAMW_BITSANDBYTES_OPTIMIZER,+ PAGED_32BIT_BITSANDBYTES_OPTIMIZER,+ ):+ with self.subTest(optimizer = optimizer):+ backend = TrainingBackend()+ with (+ patch("core.training.training.get_device", return_value = DeviceType.XPU),+ patch(+ "core.training.training.prepare_gpu_selection",+ return_value = ([0], {"selection_mode": "auto"}),+ ) as mock_prepare_gpu_selection,+ patch(+ "core.training.training._CTX.Queue",+ side_effect = [dummy_queue, dummy_queue],+ ),+ patch(+ "core.training.training._CTX.Process", return_value = DummyProcess()+ ) as mock_process,+ patch("core.training.training.threading.Thread", return_value = DummyThread()),+ ):+ backend.start_training(+ job_id = "test-job-xpu-optimizer",+ model_name = "unsloth/test",+ training_type = "LoRA/QLoRA",+ optim = optimizer,+ gpu_ids = None,+ )++ config = mock_process.call_args.kwargs["kwargs"]["config"]+ self.assertEqual(config["device_backend"], DeviceType.XPU.value)+ self.assertEqual(config["optim"], XPU_SAFE_OPTIMIZER)+ self.assertEqual(+ mock_prepare_gpu_selection.call_args.kwargs["optimizer"],+ XPU_SAFE_OPTIMIZER,+ )+def test_training_backend_preserves_uuid_parent_visibility_in_auto_mode(self):backend = TrainingBackend()@@ -1534,6 +1591,92 @@ class TestRouteErrors(unittest.TestCase):self.assertEqual(exc_info.exception.status_code, 400)self.assertIn("gpu_ids [99]", exc_info.exception.detail)+ def test_training_route_uses_xpu_safe_optimizer_for_vram_coordination(self):+ training_route = _load_route_module(+ "training_route_module_for_xpu_optimizer_test",+ "routes/training.py",+ )+ request = TrainingStartRequest(+ model_name = "unsloth/test",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ optim = DEFAULT_BITSANDBYTES_OPTIMIZER,+ gpu_ids = None,+ )+ seen = {}++ class DummyBackend:+ current_job_id = None++ def is_training_active(self):+ return False++ def start_training(self, **kwargs):+ seen["backend_optimizer"] = kwargs["optim"]+ kwargs["before_spawn"]()+ return True++ def _capture_training_vram_optimizer(**kwargs):+ seen["vram_optimizer"] = kwargs["optimizer"]+ return True, {"usable_gb": 24.0, "required_gb": 12.0}++ def _run_can_keep(can_keep):+ can_keep()+ return []++ with (+ patch.object(training_route, "get_training_backend", return_value = DummyBackend()),+ patch.object(training_route, "_diffusion_training_active", return_value = False),+ patch.object(training_route, "_diffusion_gpu_admission", return_value = nullcontext()),+ patch.object(+ training_route,+ "_reject_untrainable_model_request",+ return_value = SimpleNamespace(+ model_name = "unsloth/test",+ model_local_path = None,+ cached_model_pin = None,+ ),+ ),+ patch.object(training_route, "load_model_defaults", return_value = {"training": {}}),+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),+ patch.object(_hw_module, "DEVICE", DeviceType.XPU),+ patch("utils.hardware.ensure_hardware_detected", return_value = DeviceType.XPU),+ patch(+ "routes.training_vram.can_keep_chat_during_training",+ side_effect = _capture_training_vram_optimizer,+ ),+ patch(+ "routes.training_vram.coordinate_models_for_training",+ side_effect = _run_can_keep,+ ),+ patch(+ "core.export.get_export_backend",+ return_value = SimpleNamespace(+ current_checkpoint = None,+ is_export_active = lambda: False,+ ),+ ),+ patch(+ "core.inference.diffusion_engine_router.get_active_diffusion_engine",+ return_value = SimpleNamespace(is_loaded = False, unload = lambda: None),+ ),+ patch("core.inference.gpu_arbiter.release", lambda *_args, **_kwargs: None),+ patch(+ "core.inference.video.get_video_backend",+ return_value = SimpleNamespace(+ status = lambda: {"loaded": False},+ unload = lambda: None,+ ),+ ),+ ):+ response = asyncio.run(+ training_route.start_training(request, current_subject = "test-user")+ )++ self.assertEqual(response.status, "queued")+ self.assertEqual(seen["backend_optimizer"], XPU_SAFE_OPTIMIZER)+ self.assertEqual(seen["vram_optimizer"], XPU_SAFE_OPTIMIZER)+def test_training_route_returns_400_for_uuid_parent_visibility_gpu_ids(self):training_route = _load_route_module("training_route_module_for_uuid_parent_visibility_test",@@ -2352,3 +2495,131 @@ class TestTheFallbackNameIsOneUnslothResolves(unittest.TestCase):answer = get_device_map([0, 1])self.assertIn(answer, planned)self.assertEqual(planned[answer], "balanced")+++class TestXpuBitsandbytesOptimizerGate(unittest.TestCase):+ """The diffusion trainers pick their optimizer themselves, outside the request model the+ route normalizes, so they need the same XPU policy applied before construction."""++ def _probe(self):+ from core.training.diffusion_train_common import bitsandbytes_optimizer_supported+ return bitsandbytes_optimizer_supported++ def test_xpu_host_refuses_bitsandbytes_optimizers(self):+ with patch("utils.hardware.get_device", return_value = DeviceType.XPU):+ self.assertFalse(self._probe()())++ def test_selected_backends_other_than_xpu_keep_bitsandbytes(self):+ for device in (DeviceType.CUDA, DeviceType.CPU, DeviceType.MLX):+ with self.subTest(device = device):+ with patch("utils.hardware.get_device", return_value = device):+ self.assertTrue(self._probe()())++ def test_a_hybrid_host_that_selected_cuda_keeps_bitsandbytes(self):+ """An Intel iGPU beside an NVIDIA card reports torch.xpu.is_available() True while+ detection selects CUDA. Keying on presence would drop 8-bit on a CUDA run and make+ restore_resume_state refuse every existing AdamW8bit checkpoint."""+ import torch+ with (+ patch.object(torch, "xpu", SimpleNamespace(is_available = lambda: True)),+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),+ ):+ self.assertTrue(self._probe()())++ def test_a_raising_probe_fails_open(self):+ def _boom():+ raise RuntimeError("driver exploded")++ with patch("utils.hardware.get_device", side_effect = _boom):+ self.assertTrue(self._probe()())++ def test_diffusion_factories_skip_bnb_on_xpu_and_keep_it_elsewhere(self):+ import torch++ import core.training.diffusion_dit_trainer as dit_mod+ import core.training.diffusion_lora_trainer as lora_mod++ class _Bnb8bitMarker(torch.optim.AdamW):+ """Stands in for bnb.optim.AdamW8bit: constructs fine, dies at the first step+ exactly as the Intel Triton SYCL assertion does."""++ def step(self, *args, **kwargs):+ raise AssertionError("sycl headers not found")++ fake_bnb = ModuleType("bitsandbytes")+ fake_optim = ModuleType("bitsandbytes.optim")+ fake_optim.AdamW8bit = _Bnb8bitMarker+ fake_bnb.optim = fake_optim++ cases = (+ ("sdxl_lora", lora_mod, "_make_lora_optimizer"),+ ("dit", dit_mod, "_make_optimizer"),+ )+ for label, module, factory_name in cases:+ factory = getattr(module, factory_name)+ for on_xpu in (True, False):+ with self.subTest(trainer = label, xpu = on_xpu):+ param = torch.nn.Parameter(torch.zeros(2, 2))+ param.grad = torch.ones(2, 2)+ with (+ patch.dict(+ sys.modules,+ {"bitsandbytes": fake_bnb, "bitsandbytes.optim": fake_optim},+ ),+ patch.object(+ module,+ "bitsandbytes_optimizer_supported",+ lambda supported = not on_xpu: supported,+ ),+ ):+ optimizer = factory([param], 1e-4)++ if on_xpu:+ # Must not be the bnb optimizer, and must survive an actual step.+ self.assertNotIsInstance(optimizer, _Bnb8bitMarker)+ optimizer.step()+ else:+ # Unchanged off XPU: still the 8-bit optimizer, not a blanket disable.+ self.assertIsInstance(optimizer, _Bnb8bitMarker)+++class TestCliDefaultOptimizerFollowsTheDevicePolicy(unittest.TestCase):+ """`unsloth train` exposes no --optim, so without this the CLI falls through to+ trainer.py's own `adamw_8bit` literal and reproduces issue #10021 off the Studio path."""++ def _resolve(self, device: DeviceType) -> str:+ from core.training.training import (+ DEFAULT_TRAINING_OPTIMIZER,+ normalize_training_optimizer_for_device,+ )+ return normalize_training_optimizer_for_device(+ DEFAULT_TRAINING_OPTIMIZER,+ device_backend = device.value,+ )++ def test_xpu_cli_default_is_the_safe_optimizer(self):+ self.assertEqual(self._resolve(DeviceType.XPU), XPU_SAFE_OPTIMIZER)++ def test_other_backends_keep_the_historical_cli_default(self):+ from core.training.training import DEFAULT_TRAINING_OPTIMIZER+ for device in (DeviceType.CUDA, DeviceType.CPU):+ with self.subTest(device = device):+ self.assertEqual(self._resolve(device), DEFAULT_TRAINING_OPTIMIZER)++ def test_the_cli_sets_optim_from_the_host_policy(self):+ """The wiring, not just the helper: train.py must stamp `optim` into training_kwargs."""+ source = (_BACKEND_ROOT.parent.parent / "unsloth_cli" / "commands" / "train.py").read_text(+ encoding = "utf-8"+ )+ self.assertIn("_optimizer_for_host", source)+ self.assertIn(+ 'training_kwargs["optim"] = _optimizer_for_host(training_kwargs.get("optim"))', source+ )++ def test_an_undetectable_host_keeps_the_historical_default(self):+ """The CLI helper must fail open: a device lookup that raises cannot stop a run."""+ cli = _BACKEND_ROOT.parent.parent / "unsloth_cli" / "commands" / "train.py"+ source = cli.read_text(encoding = "utf-8")+ self.assertIn("except Exception:", source)+ # The fallback returns the requested/default optimizer rather than propagating.+ self.assertIn("return optimizer", source)diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.pyindex 2acf6d11206..10fb40239e4 100644--- a/unsloth_cli/commands/train.py+++ b/unsloth_cli/commands/train.py@@ -47,6 +47,31 @@ def _create_cli_trainer(model_name: str, hf_token: Optional[str]):return UnslothTrainer()+def _optimizer_for_host(requested: Optional[str] = None) -> str:+ """The CLI exposes no --optim, so trainer.py would fall back to its own `adamw_8bit`+ literal, which cannot complete a step on Intel XPU. Resolve the same device policy the+ Studio route and worker config use, so `unsloth train` lands on the same optimizer a+ Studio run on this host would. Non-XPU hosts keep `adamw_8bit` exactly as before.++ Takes `requested` rather than only filling a default, so a future --optim carrying a+ bitsandbytes name is normalized too instead of reaching the trainer unchanged.+ """+ ensure_studio_backend_path()+ with studio_backend_imports("unsloth train"):+ from studio.backend.core.training.training import (+ DEFAULT_TRAINING_OPTIMIZER,+ normalize_training_optimizer_for_device,+ )+ from studio.backend.utils.hardware import get_device++ optimizer = requested or DEFAULT_TRAINING_OPTIMIZER+ try:+ device_backend = get_device().value+ except Exception: # noqa: BLE001 -- an undetectable host keeps the historical default+ return optimizer+ return normalize_training_optimizer_for_device(optimizer, device_backend = device_backend)++@add_options_from_config(Config)def train(config: Optional[Path] = typer.Option(@@ -156,6 +181,7 @@ def train(training_kwargs = cfg.training_kwargs()training_kwargs["wandb_token"] = wandb_token+ training_kwargs["optim"] = _optimizer_for_host(training_kwargs.get("optim"))started = trainer.start_training(dataset = ds, eval_dataset = eval_ds, **training_kwargs)if not started: