* Studio: defer llama.cpp update probes and self-heal MLX on macOS Two macOS startup problems shared one root area in the FastAPI lifespan: - The llama.cpp capability + freshness probes ran inline before the server yielded, so a cold/slow/flaky network on the GitHub freshness check blocked 'Application startup complete' (~34s on CI, longer in the field). Move both probes to a daemon thread; app.state stays None until ready (status routes already re-probe at request time). Opt out with UNSLOTH_DISABLE_UPDATE_CHECK=1. - Train and Export were greyed out because mlx/mlx-lm/mlx-vlm arrive only transitively and a resolver backtrack silently drops them, so CHAT_ONLY stayed true. Add utils/mlx_repair.py: when Apple Silicon is detected without MLX, reinstall mlx/mlx-lm/mlx-vlm by name on a daemon thread and re-run hardware detection (opt out UNSLOTH_DISABLE_MLX_AUTOREPAIR=1). Surface a chat_only_reason in /api/health plus a sidebar tooltip so a greyed Train/Export explains itself instead of failing silently. * Studio: guard model defaults against a None model name load_model_defaults(None) called model_name.lower() with no guard, raising 'Error loading model defaults for None' before any model is selected. Return an empty dict for a falsy/non-str name. * Studio: drop obsolete upstream macOS + Windows Blackwell prebuilt pins Both pins worked around gaps in ggml-org upstream prebuilts, but Studio now routes every GPU host and all of macOS to the unslothai/llama.cpp fork (published_repo_for_host), which ships the needed bundles, so both pins are dead code on the default install path: - macOS b9415: macOS always routes to the fork (its own macOS bundles), and host_supports_macos_minos() is the backstop. The pin only fired under an explicit --published-repo ggml-org override. - Windows Blackwell b9360: Windows-NVIDIA routes to the fork, whose windows-x64-cuda13 bundle covers Blackwell (manifest max_sm 120, toolkit 13.3), so the pin's self-disable check makes it dormant on every default install; it could only activate under the same upstream override on a 13.0-13.2 driver. Remove the pin constants, functions, and call sites. Keep the Blackwell capability detection (_drop_blackwell_incapable_windows_cuda, _host_is_blackwell, _windows_cuda_attempt_covers_blackwell) that still drops a non-sm_120 cuda-12.4 build on a Blackwell host. After this, an explicit --published-repo ggml-org override on a Blackwell 13.0-13.2 host loses its GPU fallback and lands on CPU; the default fork path is unaffected. Update the install selection-logic and macOS-compat unit tests for the new no-pin behavior. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: walk back deeper on the macOS upstream prebuilt path After removing the b9415 macOS pin, the explicit --published-repo ggml-org upstream path still used the default 2-release fallback, so a pre-macOS-26 host behind a run of macOS-26-only builds would exhaust two too-new plans (minos is only checked post-download) and drop to a source build before reaching a loadable older release. Walk back as deep as the fork macOS path (DEFAULT_MAX_MACOS_RELEASE_FALLBACKS), turning the removed static pin into dynamic discovery. Addresses review feedback on the macOS upstream fallback. * Studio: pin transformers during MLX self-heal so it cannot break Studio mlx-lm/mlx-vlm declare transformers>=5, but the single-env install pins transformers==4.57.6. The self-heal used --upgrade with no constraint, so it could upgrade transformers in the live venv and break the rest of Studio just to make import mlx.core pass. Pin transformers to the installed version via a constraint file: the resolver either finds an mlx build compatible with it or fails (we stay chat-only), never upgrading transformers underneath Studio. Addresses review feedback on the MLX repair install. * Studio: harden MLX self-heal against an unsupported mlx-vlm Pinning transformers alone made uv backtrack mlx-vlm to 0.3.9 (below unsloth-zoo's mlx-vlm>=0.4.4), which imports but breaks VLM Train/Export -- so the self-heal could clear chat-only onto a broken stack. Mirror the main installer: set UV_OVERRIDE=overrides-darwin-arm64.txt so a current mlx-vlm coexists with the transformers pin, require the same minimum versions unsloth-zoo declares, and gate/validate on a full mlx_stack_available() check (not a bare import) so an old or partial stack stays chat-only. Addresses PR review. * Studio: filter Blackwell-incapable CUDA in resolve_upstream_asset_choice resolve_upstream_asset_choice returned the first windows-cuda choice unfiltered, so a Blackwell host could be handed an sm_120-incapable cuda-12.4 build while the sibling planners drop it. Apply _drop_blackwell_incapable_windows_cuda here too and fall through to the CPU bundle on a Blackwell host with no capable GPU asset. Addresses PR review. * Studio: re-poll health so MLX self-heal reaches an open UI The sidebar cached the initial /api/health, so a successful background MLX self-heal (chat_only flips false) did not re-enable Train/Export until a manual reload. While chat-only for the recoverable mlx_unavailable reason, re-poll /api/health and stop once Train/Export become available. Addresses PR review. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: make the disabled Train/Export tooltip reachable The greyed Train/Export items pass a tooltip explaining why (e.g. MLX missing), but a disabled <button> fires no pointer events and SidebarMenuButton only showed tooltips while collapsed, so the explanation never appeared. Wrap a disabled button in a focusable span and show its tooltip while expanded too; enabled items keep the collapsed-only behavior. Addresses PR review. * Studio: gate Train/Export on the full MLX stack, not bare mlx.core detect_hardware enabled MLX training whenever `import mlx.core` worked, but the MLX self-heal (utils/mlx_repair) treats a stack without mlx-lm/mlx-vlm at the versions unsloth-zoo requires as inadequate. That asymmetry let the UI enable Train/Export on exactly the partial/backtracked stack the self-heal is trying to repair (greyed-in-but-broken VLM export). Gate on the same mlx_stack_available() criterion so a partial stack stays chat-only (reason mlx_unavailable) and the background repair restores it. Addresses PR review. * Fix MLX repair and health auth for PR #6494 * Fix macOS upstream prebuilt fallback for PR #6494 * Fix MLX stack validation for PR #6494 * Fix MLX self-heal validation for PR #6494 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Review fixes: isolate hardware-state test, robust transformers pin - test_chat_only_reason.py: detect_hardware() assigns module globals directly, which monkeypatch does not revert; the autouse fixture now saves and restores DEVICE/CHAT_ONLY/CHAT_ONLY_REASON/IS_ROCM so a chat-only verdict here cannot leak into other backend tests (e.g. test_utils.py) on a GPU host. - mlx_repair.py: read the transformers version from importlib.metadata instead of importing transformers, so the install pin is not silently dropped when transformers has valid metadata but fails to import. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix CI: model full MLX stack in dispatch tests, keep selection test offline dispatch (macOS) job: - detect_hardware now gates MLX on the full stack (mlx_stack_available imports mlx_lm/mlx_vlm and checks dist versions), so faking only mlx.core makes the apple_silicon_mlx profile resolve to CPU. The dispatch tests assert the routing decision when the stack IS usable, so model a complete stack: test_hardware_dispatch_matrix patches utils.mlx_repair.mlx_stack_available and test_is_mlx_dispatch_gate patches hardware._has_usable_mlx_stack. The stack predicate's own internals stay covered by test_mlx_repair.py. Repo tests (CPU) job: - test_no_cuda_attempt_on_published_path_for_13_1 fell through to a live github_release_assets() upstream fetch after the Blackwell filter dropped every published attempt, which the offline security scanner blocks. Stub that fetch so the walk-back deterministically finds no usable CUDA build and raises PrebuiltFallback without network. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Harden MLX self-heal: prepare transformers constraint inside the try attempt_mlx_repair runs on a daemon thread, but _transformers_constraint_args was called before the try. A failure there (e.g. tempfile.mkstemp on a full disk or a bad TMPDIR) would propagate unhandled and silently kill the self-heal thread. Move the call inside the try and initialize constraint_path so any such failure is caught and leaves Studio chat-only instead of crashing the thread. --------- Co-authored-by: Daniel Han <michaelhan2050@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: wasimysaid <wasimysdev@gmail.com>
360 lines
13 KiB
Python
360 lines
13 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
|
"""Studio hardware dispatch matrix: spoofs platform/torch/mlx per PROFILES to exercise CUDA/ROCm/XPU/MLX/CPU paths without real hardware."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import importlib.machinery
|
|
import importlib.util
|
|
import sys
|
|
import types
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
import pytest
|
|
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
STUDIO_BACKEND = REPO_ROOT / "studio" / "backend"
|
|
|
|
|
|
@dataclass
|
|
class HardwareProfile:
|
|
name: str
|
|
system: str # platform.system() value
|
|
machine: str # platform.machine() value
|
|
cuda_available: bool # torch.cuda.is_available() value
|
|
hip_version: Optional[str] # torch.version.hip; None for NVIDIA, "6.1" etc. for ROCm
|
|
xpu_available: bool # torch.xpu.is_available() value
|
|
has_mlx: bool # whether to inject a fake mlx into sys.modules
|
|
mps_available: bool # torch.backends.mps.is_available() value
|
|
|
|
expect_is_mlx: bool # unsloth._IS_MLX
|
|
expect_device_type: str # Studio DeviceType (uppercased name: "CUDA"/"XPU"/"MLX"/"CPU")
|
|
expect_is_rocm: bool # Studio IS_ROCM
|
|
expect_apple_silicon: bool # Studio is_apple_silicon()
|
|
extra_notes: str = ""
|
|
|
|
|
|
PROFILES = [
|
|
HardwareProfile(
|
|
name = "nvidia_cuda",
|
|
system = "Linux",
|
|
machine = "x86_64",
|
|
cuda_available = True,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = False,
|
|
mps_available = False,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "CUDA",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = False,
|
|
),
|
|
HardwareProfile(
|
|
name = "amd_rocm",
|
|
system = "Linux",
|
|
machine = "x86_64",
|
|
cuda_available = True,
|
|
hip_version = "6.1",
|
|
xpu_available = False,
|
|
has_mlx = False,
|
|
mps_available = False,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "CUDA",
|
|
expect_is_rocm = True,
|
|
expect_apple_silicon = False,
|
|
extra_notes = "PyTorch ROCm reuses torch.cuda.* over HIP; "
|
|
"Studio still uses DeviceType.CUDA but flips IS_ROCM=True.",
|
|
),
|
|
HardwareProfile(
|
|
name = "intel_xpu",
|
|
system = "Linux",
|
|
machine = "x86_64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = True,
|
|
has_mlx = False,
|
|
mps_available = False,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "XPU",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = False,
|
|
),
|
|
HardwareProfile(
|
|
name = "apple_silicon_mlx",
|
|
system = "Darwin",
|
|
machine = "arm64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = True,
|
|
mps_available = True,
|
|
expect_is_mlx = True,
|
|
expect_device_type = "MLX",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = True,
|
|
),
|
|
HardwareProfile(
|
|
name = "apple_silicon_no_mlx",
|
|
system = "Darwin",
|
|
machine = "arm64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = False,
|
|
mps_available = True,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "CPU",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = True,
|
|
extra_notes = "Mac without mlx falls through to CPU (chat-only).",
|
|
),
|
|
HardwareProfile(
|
|
name = "linux_arm64_with_mlx",
|
|
system = "Linux",
|
|
machine = "arm64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = True,
|
|
mps_available = False,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "CPU",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = False,
|
|
extra_notes = "Canary: Linux ARM64 with mlx package installed must NOT "
|
|
"trigger MLX dispatch; the system check is what guards it.",
|
|
),
|
|
HardwareProfile(
|
|
name = "cpu_only",
|
|
system = "Linux",
|
|
machine = "x86_64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = False,
|
|
mps_available = False,
|
|
expect_is_mlx = False,
|
|
expect_device_type = "CPU",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = False,
|
|
),
|
|
]
|
|
|
|
PROFILE_IDS = [p.name for p in PROFILES]
|
|
|
|
|
|
@pytest.fixture
|
|
def spoof_hardware(monkeypatch):
|
|
"""Return a function that applies a HardwareProfile to the live process; monkeypatch cleans up on exit."""
|
|
|
|
def _apply(profile: HardwareProfile) -> None:
|
|
import platform
|
|
import torch
|
|
|
|
# platform spoof (used by both the unsloth gate and Studio's helpers)
|
|
monkeypatch.setattr(platform, "system", lambda: profile.system)
|
|
monkeypatch.setattr(platform, "machine", lambda: profile.machine)
|
|
|
|
monkeypatch.setattr(torch.cuda, "is_available", lambda: profile.cuda_available)
|
|
# Stub get_device_properties: detect_hardware reads .name, which crashes on a CPU CI runner.
|
|
if profile.cuda_available:
|
|
stub_props = types.SimpleNamespace(
|
|
name = "Stub GPU" if not profile.hip_version else "Stub AMD GPU",
|
|
)
|
|
monkeypatch.setattr(
|
|
torch.cuda,
|
|
"get_device_properties",
|
|
lambda i = 0: stub_props,
|
|
raising = False,
|
|
)
|
|
|
|
# torch.version.hip: None on NVIDIA, "6.1" etc. on ROCm
|
|
torch_version = torch.version
|
|
monkeypatch.setattr(torch_version, "hip", profile.hip_version, raising = False)
|
|
|
|
# Stub torch.xpu.* always; real get_device_name needs the XPU torch build.
|
|
if hasattr(torch, "xpu"):
|
|
monkeypatch.setattr(torch.xpu, "is_available", lambda: profile.xpu_available)
|
|
monkeypatch.setattr(
|
|
torch.xpu,
|
|
"get_device_name",
|
|
lambda i = 0: "Intel XPU (stub)",
|
|
raising = False,
|
|
)
|
|
elif profile.xpu_available:
|
|
xpu_stub = types.SimpleNamespace(
|
|
is_available = lambda: True,
|
|
get_device_name = lambda i = 0: "Intel XPU (stub)",
|
|
)
|
|
monkeypatch.setattr(torch, "xpu", xpu_stub, raising = False)
|
|
|
|
# torch.backends.mps.is_available
|
|
if hasattr(torch.backends, "mps"):
|
|
monkeypatch.setattr(torch.backends.mps, "is_available", lambda: profile.mps_available)
|
|
|
|
# mlx + mlx.core in sys.modules
|
|
if profile.has_mlx:
|
|
fake_mlx = types.ModuleType("mlx")
|
|
fake_mlx.__spec__ = importlib.machinery.ModuleSpec("mlx", loader = None)
|
|
fake_mlx.__path__ = []
|
|
fake_mlx_core = types.ModuleType("mlx.core")
|
|
fake_mlx.core = fake_mlx_core
|
|
monkeypatch.setitem(sys.modules, "mlx", fake_mlx)
|
|
monkeypatch.setitem(sys.modules, "mlx.core", fake_mlx_core)
|
|
# detect_hardware now gates MLX on the full stack via
|
|
# utils.mlx_repair.mlx_stack_available() (it imports mlx_lm/mlx_vlm and
|
|
# checks dist versions), which faking only mlx.core cannot satisfy. An
|
|
# mlx profile means a complete, healthy stack, so model that here;
|
|
# mlx_stack_available's own internals are covered by test_mlx_repair.py.
|
|
if str(STUDIO_BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(STUDIO_BACKEND))
|
|
import utils.mlx_repair as _mlx_repair # type: ignore
|
|
|
|
monkeypatch.setattr(_mlx_repair, "mlx_stack_available", lambda: True)
|
|
else:
|
|
# Drop cached mlx and patch find_spec so the unsloth gate sees mlx as absent.
|
|
monkeypatch.delitem(sys.modules, "mlx", raising = False)
|
|
monkeypatch.delitem(sys.modules, "mlx.core", raising = False)
|
|
real_find_spec = importlib.util.find_spec
|
|
|
|
def _no_mlx(name, *args, **kwargs):
|
|
if name == "mlx" or name.startswith("mlx."):
|
|
return None
|
|
return real_find_spec(name, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(importlib.util, "find_spec", _no_mlx)
|
|
|
|
# Studio's _has_mlx() does `import mlx.core`, not find_spec; block it
|
|
# with a meta_path finder that raises ImportError for mlx.*.
|
|
class _BlockMLXFinder:
|
|
def find_spec(
|
|
self_inner,
|
|
name,
|
|
path = None,
|
|
target = None,
|
|
):
|
|
if name == "mlx" or name.startswith("mlx."):
|
|
raise ImportError(
|
|
f"mlx import blocked by spoof_hardware " f"(profile={profile.name})"
|
|
)
|
|
return None
|
|
|
|
blocker = _BlockMLXFinder()
|
|
# New list so monkeypatch fully restores on teardown.
|
|
monkeypatch.setattr(
|
|
sys,
|
|
"meta_path",
|
|
[blocker, *sys.meta_path],
|
|
)
|
|
|
|
return _apply
|
|
|
|
|
|
def _evaluate_unsloth_is_mlx_gate() -> bool:
|
|
"""Re-evaluate the exact expression from unsloth/__init__.py:20-24."""
|
|
import importlib.util
|
|
import platform
|
|
|
|
return (
|
|
platform.system() == "Darwin"
|
|
and platform.machine() == "arm64"
|
|
and importlib.util.find_spec("mlx") is not None
|
|
)
|
|
|
|
|
|
def _import_studio_hardware_module():
|
|
"""Lazy-load Studio's hardware module under the bare-imports layout."""
|
|
if str(STUDIO_BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(STUDIO_BACKEND))
|
|
# Fresh import so detect_hardware re-runs under the current spoofs.
|
|
sys.modules.pop("utils.hardware.hardware", None)
|
|
sys.modules.pop("utils.hardware", None)
|
|
from utils.hardware import hardware as hw # type: ignore
|
|
|
|
return hw
|
|
|
|
|
|
@pytest.mark.parametrize("profile", PROFILES, ids = PROFILE_IDS)
|
|
def test_unsloth_is_mlx_gate_matches_profile(profile, spoof_hardware):
|
|
"""The _IS_MLX expression in unsloth/__init__.py flips correctly per profile."""
|
|
spoof_hardware(profile)
|
|
actual = _evaluate_unsloth_is_mlx_gate()
|
|
assert actual is profile.expect_is_mlx, (
|
|
f"profile {profile.name}: expected _IS_MLX={profile.expect_is_mlx}, "
|
|
f"got {actual}. {profile.extra_notes}"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("profile", PROFILES, ids = PROFILE_IDS)
|
|
def test_studio_detect_hardware_matches_profile(profile, spoof_hardware):
|
|
"""Studio's detect_hardware() routes to the right DeviceType per profile."""
|
|
spoof_hardware(profile)
|
|
hw = _import_studio_hardware_module()
|
|
detected = hw.detect_hardware()
|
|
expected = getattr(hw.DeviceType, profile.expect_device_type)
|
|
assert detected == expected, (
|
|
f"profile {profile.name}: expected {profile.expect_device_type}, "
|
|
f"got {detected!r}. {profile.extra_notes}"
|
|
)
|
|
assert hw.IS_ROCM is profile.expect_is_rocm, (
|
|
f"profile {profile.name}: expected IS_ROCM={profile.expect_is_rocm}, " f"got {hw.IS_ROCM}"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("profile", PROFILES, ids = PROFILE_IDS)
|
|
def test_studio_is_apple_silicon_matches_profile(profile, spoof_hardware):
|
|
"""Studio's is_apple_silicon() helper agrees with platform spoof."""
|
|
spoof_hardware(profile)
|
|
hw = _import_studio_hardware_module()
|
|
assert hw.is_apple_silicon() is profile.expect_apple_silicon, (
|
|
f"profile {profile.name}: expected is_apple_silicon={profile.expect_apple_silicon}, "
|
|
f"got {hw.is_apple_silicon()}"
|
|
)
|
|
|
|
|
|
# Negative-space tests: catch regressions where the dispatch order changes.
|
|
|
|
|
|
def test_cuda_takes_priority_over_mlx_when_both_available(spoof_hardware):
|
|
"""CUDA wins over MLX when both available: canary against GPU users being routed to MLX after refactors."""
|
|
profile = HardwareProfile(
|
|
name = "cuda_plus_mlx",
|
|
system = "Darwin",
|
|
machine = "arm64",
|
|
cuda_available = True,
|
|
hip_version = None,
|
|
xpu_available = False,
|
|
has_mlx = True,
|
|
mps_available = True,
|
|
expect_is_mlx = True,
|
|
expect_device_type = "CUDA",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = True,
|
|
)
|
|
spoof_hardware(profile)
|
|
hw = _import_studio_hardware_module()
|
|
assert hw.detect_hardware() == hw.DeviceType.CUDA
|
|
|
|
|
|
def test_xpu_takes_priority_over_mlx_when_both_available(spoof_hardware):
|
|
"""XPU is selected over MLX in the dispatch order."""
|
|
profile = HardwareProfile(
|
|
name = "xpu_plus_mlx",
|
|
system = "Darwin",
|
|
machine = "arm64",
|
|
cuda_available = False,
|
|
hip_version = None,
|
|
xpu_available = True,
|
|
has_mlx = True,
|
|
mps_available = True,
|
|
expect_is_mlx = True,
|
|
expect_device_type = "XPU",
|
|
expect_is_rocm = False,
|
|
expect_apple_silicon = True,
|
|
)
|
|
spoof_hardware(profile)
|
|
hw = _import_studio_hardware_module()
|
|
assert hw.detect_hardware() == hw.DeviceType.XPU
|