Skip to content

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.

Let unsloth.models and unsloth.save import on Apple Silicon (#9447)

Vineeth Sai Varikuntla97d67a3c0ccc
diff --git a/tests/test_amp_helpers_every_device.py b/tests/test_amp_helpers_every_device.py
new file mode 100644
index 00000000000..3df80bfa20c
--- /dev/null
+++ b/tests/test_amp_helpers_every_device.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Both amp helpers are in `_utils.__all__`, so a DEVICE_TYPE whose branch leaves them unbound
+makes `from ._utils import *` raise (mlx did). Sliced with `ast`: importing `_utils` needs a GPU.
+"""
+
+import ast
+import types
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+UTILS_PATH = REPO_ROOT / "unsloth" / "models" / "_utils.py"
+AMP_NAMES = ("torch_amp_custom_fwd", "torch_amp_custom_bwd")
+
+# (DEVICE_TYPE, DEVICE_TYPE_TORCH), per device_type.py.
+DEVICES = [("cuda", "cuda"), ("hip", "cuda"), ("xpu", "xpu"), ("mlx", "mps")]
+
+
+def _binds(node, name):
+ return any(
+ isinstance(child, ast.Name) and child.id == name and isinstance(child.ctx, ast.Store)
+ for child in ast.walk(node)
+ )
+
+
+def _amp_branch():
+ """The top-level `if` that assigns the amp helpers."""
+ tree = ast.parse(UTILS_PATH.read_text(encoding = "utf-8"))
+ for node in tree.body:
+ if isinstance(node, ast.If) and _binds(node, AMP_NAMES[0]):
+ return node
+ raise AssertionError(f"no top-level branch in {UTILS_PATH.name} assigns {AMP_NAMES[0]}")
+
+
+def _fake_torch():
+ amp = types.SimpleNamespace(
+ custom_fwd = lambda device_type: f"fwd:{device_type}",
+ custom_bwd = lambda device_type: f"bwd:{device_type}",
+ )
+ cuda_amp = types.SimpleNamespace(custom_fwd = "fwd:legacy", custom_bwd = "bwd:legacy")
+ return types.SimpleNamespace(amp = amp, cuda = types.SimpleNamespace(amp = cuda_amp))
+
+
+def test_the_amp_helpers_are_exported():
+ """Without this the rest of the file would be testing nothing."""
+ tree = ast.parse(UTILS_PATH.read_text(encoding = "utf-8"))
+ exported = set()
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and _binds(node, "__all__"):
+ exported |= {
+ element.value
+ for element in ast.walk(node)
+ if isinstance(element, ast.Constant) and isinstance(element.value, str)
+ }
+ for name in AMP_NAMES:
+ assert name in exported, f"{name} is no longer in __all__; this test needs updating"
+
+
[email protected](("device_type", "device_type_torch"), DEVICES)
+def test_amp_helpers_are_bound_on_every_device(device_type, device_type_torch):
+ from packaging.version import Version
+
+ namespace = {
+ "torch": _fake_torch(),
+ "Version": Version,
+ "torch_version": "2.9.0",
+ "DEVICE_TYPE": device_type,
+ "DEVICE_TYPE_TORCH": device_type_torch,
+ }
+ exec(compile(ast.Module(body = [_amp_branch()], type_ignores = []), "<amp>", "exec"), namespace)
+
+ for name in AMP_NAMES:
+ assert name in namespace, (
+ f"DEVICE_TYPE={device_type!r} leaves {name} unbound, so "
+ f"`from ._utils import *` raises AttributeError on that runtime"
+ )
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index d1d38afda1d..25eb783848b 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -2078,6 +2078,10 @@ elif DEVICE_TYPE == "xpu":
else:
torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "xpu")
torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "xpu")
+else:
+ # Exhaustive because both names are in __all__: an unbound branch (mlx) breaks `import *`.
+ torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = DEVICE_TYPE_TORCH)
+ torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = DEVICE_TYPE_TORCH)
# Fix KeyError: 'Cache only has 0 layers, attempted to access layer with index 0'.