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
Centralize device backend helpers (#4252)
Daniel Han8e1ea9ae5ad3
diff --git a/tests/test_device_helpers.py b/tests/test_device_helpers.pynew file mode 100644index 00000000000..fa0f21b6a39--- /dev/null+++ b/tests/test_device_helpers.py@@ -0,0 +1,170 @@+import importlib.util+import sys+import types+from pathlib import Path++from packaging.version import Version+++REPO_ROOT = Path(__file__).resolve().parents[1]+DEVICE_TYPE_PATH = REPO_ROOT / "unsloth" / "device_type.py"+CUDA_PROPERTIES = types.SimpleNamespace(+ name = "NVIDIA B200",+ total_memory = 16 * 1024**3,+ major = 10,+ minor = 0,+)+++def _load_device_type(+ monkeypatch,+ torch_module,+ mlx_available = False,+):+ package_name = "_device_helpers_test"+ package = types.ModuleType(package_name)+ package.__path__ = [str(DEVICE_TYPE_PATH.parent)]+ monkeypatch.setitem(sys.modules, package_name, package)++ bnb_availability = types.ModuleType(f"{package_name}.bnb_availability")+ bnb_availability.native_kernels_ready = lambda *_args, **_kwargs: True+ monkeypatch.setitem(sys.modules, bnb_availability.__name__, bnb_availability)++ zoo = types.ModuleType("unsloth_zoo")+ zoo.__path__ = []+ zoo_utils = types.ModuleType("unsloth_zoo.utils")+ zoo_utils.Version = Version+ zoo_mlx = types.ModuleType("unsloth_zoo.mlx")+ zoo_mlx.is_mlx_available = lambda: mlx_available+ monkeypatch.setitem(sys.modules, "unsloth_zoo", zoo)+ monkeypatch.setitem(sys.modules, "unsloth_zoo.utils", zoo_utils)+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx", zoo_mlx)++ bitsandbytes = types.ModuleType("bitsandbytes")+ bitsandbytes.__version__ = "0.49.2"+ monkeypatch.setitem(sys.modules, "bitsandbytes", bitsandbytes)++ if torch_module is None:+ monkeypatch.setitem(sys.modules, "torch", None)+ else:+ monkeypatch.setitem(sys.modules, "torch", torch_module)++ module_name = f"{package_name}.device_type"+ spec = importlib.util.spec_from_file_location(module_name, DEVICE_TYPE_PATH)+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, module_name, module)+ spec.loader.exec_module(module)+ return module+++def _fake_torch(+ *,+ properties,+ hip_version = None,+ xpu_backend = None,+ cuda_available = True,+):+ torch = types.ModuleType("torch")+ torch.cuda = types.SimpleNamespace(+ is_available = lambda: cuda_available,+ device_count = lambda: 1,+ get_device_properties = lambda _index: properties,+ get_device_name = lambda _index: "",+ empty_cache = lambda: None,+ current_device = lambda: 0,+ )+ torch.version = types.SimpleNamespace(+ cuda = "12.8",+ hip = hip_version,+ xpu = "2026.1",+ )+ if xpu_backend is not None:+ torch.xpu = xpu_backend+ return torch+++def test_cuda_import_does_not_require_torch_xpu(monkeypatch):+ torch = _fake_torch(properties = CUDA_PROPERTIES)++ device_type = _load_device_type(monkeypatch, torch)++ assert not hasattr(torch, "xpu")+ assert device_type._DEVICE_MODULE is torch.cuda+++def test_hip_stats_preserve_arch_name_fallback(monkeypatch):+ properties = types.SimpleNamespace(+ name = "AMD Radeon Graphics",+ total_memory = 8 * 1024**3,+ gcnArchName = "gfx1100:sramecc+:xnack-",+ )+ torch = _fake_torch(properties = properties, hip_version = "6.3")+ device_type = _load_device_type(monkeypatch, torch)++ name, snippet, max_memory = device_type.get_device_stats()++ assert name == "AMD gfx1100 GPU. "+ assert snippet == "ROCm Toolkit: 6.3."+ assert max_memory == 8.0+++def test_xpu_cache_and_current_device_dispatch(monkeypatch):+ xpu_calls = []+ xpu_backend = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ empty_cache = lambda: xpu_calls.append("empty_cache"),+ current_device = lambda: 3,+ get_device_properties = lambda _index: types.SimpleNamespace(+ name = "Intel Arc",+ total_memory = 8 * 1024**3,+ ),+ )+ torch = _fake_torch(+ properties = CUDA_PROPERTIES,+ xpu_backend = xpu_backend,+ cuda_available = False,+ )+ device_type = _load_device_type(monkeypatch, torch)++ device_type.clean_gpu_cache()+ name, snippet, max_memory = device_type.get_device_stats()++ assert xpu_calls == ["empty_cache"]+ assert device_type.get_current_device() == 3+ assert (name, snippet, max_memory) == ("Intel Arc. ", "Intel Toolkit: 2026.1.", 8.0)+++def test_mlx_helpers_do_not_require_torch(monkeypatch):+ device_type = _load_device_type(+ monkeypatch,+ torch_module = None,+ mlx_available = True,+ )+ device_type.clean_gpu_cache()++ assert device_type._DEVICE_MODULE is None+ assert device_type.get_current_device() == 0+++def test_model_call_sites_use_shared_cache_dispatch():+ llama_source = (REPO_ROOT / "unsloth" / "models" / "llama.py").read_text(encoding = "utf-8")+ vision_source = (REPO_ROOT / "unsloth" / "models" / "vision.py").read_text(encoding = "utf-8")+ gemma_source = (REPO_ROOT / "unsloth" / "models" / "gemma.py").read_text(encoding = "utf-8")+ gemma2_source = (REPO_ROOT / "unsloth" / "models" / "gemma2.py").read_text(encoding = "utf-8")+ granite_source = (REPO_ROOT / "unsloth" / "models" / "granite.py").read_text(encoding = "utf-8")++ assert "torch.xpu.empty_cache()" not in llama_source+ assert "torch.xpu.empty_cache()" not in vision_source+ assert "torch.cuda.empty_cache()" not in vision_source+ assert "device_context" not in llama_source+ assert "device_context" not in vision_source+ assert 'if DEVICE_TYPE == "xpu":\n vllm_version = ""' in vision_source+ assert "torch.cuda.current_device()" not in gemma_source+ assert gemma_source.count("get_current_device()") >= 3+ assert "torch.cuda.empty_cache()" not in gemma_source+ assert "clean_gpu_cache()" in gemma_source+ assert "torch.cuda.empty_cache()" not in gemma2_source+ assert "clean_gpu_cache()" in gemma2_source+ assert "torch.cuda.empty_cache()" not in granite_source+ assert "clean_gpu_cache()" in granite_sourcediff --git a/unsloth/device_type.py b/unsloth/device_type.pyindex 968062c7c15..81332acce82 100644--- a/unsloth/device_type.py+++ b/unsloth/device_type.py@@ -20,12 +20,17 @@ __all__ = ["DEVICE_COUNT","ALLOW_PREQUANTIZED_MODELS","ALLOW_BITSANDBYTES",+ "get_device_stats",+ "clean_gpu_cache",+ "get_current_device",+ "resolve_hip_gpu_stats_name","is_mlx_available",]import functoolsimport inspectimport os+import refrom unsloth_zoo.utils import Versionfrom .bnb_availability import native_kernels_ready@@ -179,3 +184,68 @@ if DEVICE_TYPE == "hip":from bitsandbytes.nn.modules import Params4bitif "blocksize = 64 if not HIP_ENVIRONMENT else 128" in inspect.getsource(Params4bit):ALLOW_PREQUANTIZED_MODELS = False+++def resolve_hip_gpu_stats_name(gpu_stats):+ name = str(getattr(gpu_stats, "name", "") or "").strip()+ name = re.sub(r"\s*\([^)]*\)\s*$", "", name).strip()+ normalized_name = name.lower().strip(". ")+ if normalized_name and normalized_name not in ("amd radeon graphics",):+ return name + ". "++ try:+ torch_name = str(torch.cuda.get_device_name(0) or "").strip()+ torch_name = re.sub(r"\s*\([^)]*\)\s*$", "", torch_name).strip()+ except Exception:+ torch_name = ""+ normalized_torch_name = torch_name.lower().strip(". ")+ if normalized_torch_name and normalized_torch_name not in ("amd radeon graphics",):+ return torch_name + ". "++ arch_name = ""+ for key in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):+ value = getattr(gpu_stats, key, None)+ if value is not None and str(value).strip():+ arch_name = str(value).strip()+ break++ if arch_name:+ match = re.search(r"(gfx[0-9a-z]+)", arch_name, flags = re.I)+ if match:+ return f"AMD {match.group(1).lower()} GPU. "+ return "AMD GPU. "+++_DEVICE_MODULE = None if _IS_MLX else getattr(torch, DEVICE_TYPE_TORCH, None)+if not _IS_MLX and _DEVICE_MODULE is None:+ raise RuntimeError(f"Unsloth: PyTorch does not provide the {DEVICE_TYPE_TORCH} backend.")+++def get_device_stats() -> tuple[str, str, float]:+ """Return (name, stats_snippet, max_memory_gb)."""+ if _DEVICE_MODULE is None:+ raise RuntimeError("Unsloth: GPU statistics are unavailable on the MLX runtime.")+ gpu_stats = _DEVICE_MODULE.get_device_properties(0)+ max_memory = round(gpu_stats.total_memory / 1024**3, 3)++ if DEVICE_TYPE == "hip":+ name = resolve_hip_gpu_stats_name(gpu_stats)+ snippet = f"ROCm Toolkit: {torch.version.hip}."+ elif DEVICE_TYPE == "xpu":+ name = gpu_stats.name + ". " if gpu_stats.name else "Intel XPU Device. "+ snippet = f"Intel Toolkit: {torch.version.xpu}."+ else:+ name = gpu_stats.name + ". " if gpu_stats.name else "NVIDIA GPU Device. "+ snippet = f"CUDA: {gpu_stats.major}.{gpu_stats.minor}. CUDA Toolkit: {torch.version.cuda}."+ return name, snippet, max_memory+++def clean_gpu_cache() -> None:+ """Clear GPU cache for current device type."""+ if _DEVICE_MODULE is not None:+ _DEVICE_MODULE.empty_cache()+++def get_current_device() -> int:+ """Get current device index."""+ return 0 if _DEVICE_MODULE is None else _DEVICE_MODULE.current_device()diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 5782763f27c..e629efd20b8 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -28,7 +28,6 @@ __all__ = ["HAS_FLASH_ATTENTION_SOFTCAPPING","USE_MODELSCOPE","platform_system",- "resolve_hip_gpu_stats_name","patch_tokenizer","get_statistics","Unsloth_Offloaded_Gradient_Checkpointer",@@ -245,37 +244,6 @@ def _mark_unsloth_disable_data_parallel(model, disable = True):return model-def resolve_hip_gpu_stats_name(gpu_stats):- name = str(getattr(gpu_stats, "name", "") or "").strip()- name = re.sub(r"\s*\([^)]*\)\s*$", "", name).strip()- normalized_name = name.lower().strip(". ")- if normalized_name and normalized_name not in ("amd radeon graphics",):- return name + ". "-- try:- torch_name = str(torch.cuda.get_device_name(0) or "").strip()- torch_name = re.sub(r"\s*\([^)]*\)\s*$", "", torch_name).strip()- except Exception:- torch_name = ""- normalized_torch_name = torch_name.lower().strip(". ")- if normalized_torch_name and normalized_torch_name not in ("amd radeon graphics",):- return torch_name + ". "-- arch_name = ""- for key in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):- value = getattr(gpu_stats, key, None)- if value is not None and str(value).strip():- arch_name = str(value).strip()- break-- if arch_name:- arch_name = arch_name.strip()- match = re.search(r"(gfx[0-9a-z]+)", arch_name, flags = re.I)- if match:- return f"AMD {match.group(1).lower()} GPU. "- return "AMD GPU. "--from unsloth_zoo.temporary_patches import (TEMPORARY_PATCHES,)diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.pyindex 452a12fa754..df05176e0ba 100644--- a/unsloth/models/gemma.py+++ b/unsloth/models/gemma.py@@ -290,10 +290,10 @@ class GemmaFixedRotaryEmbedding(torch.nn.Module):# dummy so that patch_utils doesn't fail for nowself.cos_cached = torch.empty(- 1, device = torch.cuda.current_device(), dtype = torch.get_default_dtype()+ 1, device = get_current_device(), dtype = torch.get_default_dtype())self.sin_cached = torch.empty(- 1, device = torch.cuda.current_device(), dtype = torch.get_default_dtype()+ 1, device = get_current_device(), dtype = torch.get_default_dtype())def _set_cos_sin_cache(self, seq_len, device, dtype):@@ -341,7 +341,7 @@ class GemmaFixedRotaryEmbedding(torch.nn.Module):device_index = None,):if device_index is None:- device_index = torch.cuda.current_device()+ device_index = get_current_device()return self.multi_gpu_cos_cached[device_index], self.multi_gpu_sin_cached[device_index]def extend_rope_embedding(self, x, seq_len):@@ -474,5 +474,5 @@ class FastGemmaModel(FastLlamaModel):for _ in range(3):gc.collect()- torch.cuda.empty_cache()+ clean_gpu_cache()return model, tokenizerdiff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 144fb6ed46c..00849b62afc 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -632,5 +632,5 @@ class FastGemma2Model(FastLlamaModel):for _ in range(3):gc.collect()- torch.cuda.empty_cache()+ clean_gpu_cache()return model, tokenizerdiff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex 382a9c33cd2..1f4afa37697 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -611,5 +611,5 @@ class FastGraniteModel(FastLlamaModel):for _ in range(3):gc.collect()- torch.cuda.empty_cache()+ clean_gpu_cache()return model, tokenizerdiff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 00cb2b92b33..4ae55d976b9 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -61,6 +61,9 @@ from ..device_type import (DEVICE_TYPE_TORCH,DEVICE_COUNT,ALLOW_PREQUANTIZED_MODELS,+ get_device_stats,+ clean_gpu_cache,+ get_current_device,)transformers_version = Version(transformers_version)@@ -127,13 +130,6 @@ from triton import __version__ as triton_versionHAS_XFORMERS = xformers is not NoneBlockDiagonalCausalMask = xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None-if DEVICE_TYPE == "xpu":- clean_gpu_cache = torch.xpu.empty_cache- get_current_device = torch.xpu.current_device-else:- clean_gpu_cache = torch.cuda.empty_cache- get_current_device = torch.cuda.current_device-def original_apply_qkv(self, X):Q = self.q_proj(X)@@ -2348,41 +2344,12 @@ class FastLlamaModel:model_patcher = FastLlamaModelSUPPORTS_BFLOAT16 = is_bfloat16_supported()- if DEVICE_TYPE == "cuda":- gpu_stats = torch.cuda.get_device_properties(0)- gpu_stats_name = (- gpu_stats.name + ". " if gpu_stats.name != "" else "NVIDIA GPU Device. "- )- gpu_version = torch.version.cuda- gpu_stats_snippet = (- f"CUDA: {gpu_stats.major}.{gpu_stats.minor}. CUDA Toolkit: {gpu_version}."- )- try:- vllm_version = f" vLLM: {importlib_version('vllm')}."- except:- vllm_version = ""- elif DEVICE_TYPE == "hip":- gpu_stats = torch.cuda.get_device_properties(0)- gpu_stats_name = resolve_hip_gpu_stats_name(gpu_stats)- gpu_version = torch.version.hip- gpu_stats_snippet = f"ROCm Toolkit: {gpu_version}."- try:- vllm_version = f" vLLM: {importlib_version('vllm')}."- except:- vllm_version = ""- elif DEVICE_TYPE == "xpu":- gpu_stats = torch.xpu.get_device_properties(0)- gpu_stats_name = gpu_stats.name + ". " if gpu_stats.name != "" else "Intel XPU Device. "- gpu_version = torch.version.xpu- gpu_stats_snippet = f"Intel Toolkit: {gpu_version}."- try:- vllm_version = f" vLLM: {importlib_version('vllm')}."- except:- vllm_version = ""- else:- raise ValueError(f"Unsloth: Unsupported device type: {DEVICE_TYPE}")+ gpu_stats_name, gpu_stats_snippet, max_memory = get_device_stats()- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)+ try:+ vllm_version = f" vLLM: {importlib_version('vllm')}."+ except:+ vllm_version = ""statistics = (f"==((====))== Unsloth {__version__}: Fast {model_patcher.__name__[4:-5]} patching. Transformers: {transformers_version}.{vllm_version}\n"@@ -2869,10 +2836,7 @@ class FastLlamaModel:import gcfor _ in range(3):gc.collect()- if DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()- else:- torch.cuda.empty_cache()"""+ clean_gpu_cache()"""debug_info = debug_info.split("\n")debug_info = "\n".join([debug_info[0]] + [spaces + x[8:] for x in debug_info[1:]])diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 0d55f272e33..13cd582437c 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -96,6 +96,8 @@ except:# Old HF Hub versions <= 0.0.25from huggingface_hub.utils._token import get_tokenfrom ..device_type import (+ get_device_stats,+ clean_gpu_cache,is_hip,get_device_type,DEVICE_TYPE,@@ -928,39 +930,14 @@ class FastBaseModel:token = hf_login(token)SUPPORTS_BFLOAT16 = is_bfloat16_supported()- if DEVICE_TYPE == "cuda":- gpu_stats = torch.cuda.get_device_properties(0)- gpu_stats_name = (- gpu_stats.name + ". " if gpu_stats.name != "" else "NVIDIA GPU Device. "- )- gpu_version = torch.version.cuda- gpu_stats_snippet = (- f"CUDA: {gpu_stats.major}.{gpu_stats.minor}. CUDA Toolkit: {gpu_version}."- )- try:- vllm_version = f" vLLM: {importlib_version('vllm')}."- except:- vllm_version = ""- elif DEVICE_TYPE == "hip":- gpu_stats = torch.cuda.get_device_properties(0)- gpu_stats_name = resolve_hip_gpu_stats_name(gpu_stats)- gpu_version = torch.version.hip- gpu_stats_snippet = f"ROCm Toolkit: {gpu_version}."+ gpu_stats_name, gpu_stats_snippet, max_memory = get_device_stats()+ if DEVICE_TYPE == "xpu":+ vllm_version = ""+ else:try:vllm_version = f" vLLM: {importlib_version('vllm')}."except:vllm_version = ""- elif DEVICE_TYPE == "xpu":- gpu_stats = torch.xpu.get_device_properties(0)- gpu_stats_name = gpu_stats.name + ". " if gpu_stats.name != "" else "Intel XPU Device. "- gpu_version = torch.version.xpu- gpu_stats_snippet = f"Intel Toolkit: {gpu_version}."- # [TODO] After adding vLLM support for XPU, change this- vllm_version = ""- else:- raise ValueError(f"Unsloth: Unsupported device type: {DEVICE_TYPE}")-- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)arch_name = model_type_arch.title()arch_name = arch_name.replace("_Vl_", "_VL_").replace("_Moe", "_MoE")@@ -1351,7 +1328,7 @@ class FastBaseModel:# Device-safe embedding offload._install_offload_embedding_hooks(embed_tokens, out_embed, _embed_device)# Must free GPU memory otherwise will not free!- torch.cuda.empty_cache()+ clean_gpu_cache()gc.collect()else:from unsloth_zoo.vllm_utils import (@@ -1452,10 +1429,7 @@ class FastBaseModel:# Clear deleted GPU itemsfor _ in range(3):gc.collect()- if DEVICE_TYPE in ("cuda", "hip"):- torch.cuda.empty_cache()- elif DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()+ clean_gpu_cache()# Counteract saved tokenizerstokenizer_name = model_name if tokenizer_name is None else tokenizer_name@@ -1759,10 +1733,7 @@ class FastBaseModel:# Clear deleted GPU itemsfor _ in range(3):gc.collect()- if DEVICE_TYPE in ("cuda", "hip"):- torch.cuda.empty_cache()- elif DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()+ clean_gpu_cache()return model, tokenizer@staticmethod@@ -1912,10 +1883,7 @@ class FastBaseModel:# Clear deleted GPU itemsfor _ in range(3):gc.collect()- if DEVICE_TYPE in ("cuda", "hip"):- torch.cuda.empty_cache()- elif DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()+ clean_gpu_cache()max_seq_length = model.max_seq_length# If we pass loftq_config = None we will get an errorloftq_config = validate_loftq_config(@@ -2061,10 +2029,7 @@ class FastBaseModel:# Clear deleted GPU itemsfor _ in range(3):gc.collect()- if DEVICE_TYPE in ("cuda", "hip"):- torch.cuda.empty_cache()- elif DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()+ clean_gpu_cache()patch_saving_functions(model, vision = True)patch_peft_fast_inference(model)@@ -2179,10 +2144,7 @@ class FastBaseModel:# Clear deleted GPU itemsfor _ in range(3):gc.collect()- if DEVICE_TYPE in ("cuda", "hip"):- torch.cuda.empty_cache()- elif DEVICE_TYPE == "xpu":- torch.xpu.empty_cache()+ clean_gpu_cache()# Add for_inference and for_trainingmodel.for_training = functools.partial(FastBaseModel.for_training, model)model.for_inference = functools.partial(FastBaseModel.for_inference, model)