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
Studio: give Intel XPU Triton a working C++ toolchain on Windows (#14814)
Debojyoti Banerjeeff823acd9b8b
diff --git a/studio/backend/core/_msvc_env.py b/studio/backend/core/_msvc_env.pyindex abbdb76d09a..a0970de70f7 100644--- a/studio/backend/core/_msvc_env.py+++ b/studio/backend/core/_msvc_env.py@@ -313,6 +313,11 @@ def gate_torch_compile_on_windows(log: logging.Logger) -> None:)return+ # Intel's XPU Triton picks its compiler differently from triton-windows and needs cl set up for it (#14807).+ from ._xpu_triton_toolchain import prepare_xpu_triton_compiler # noqa: PLC0415++ prepare_xpu_triton_compiler(log)+try:reachable = crt_headers_reachable()except Exception: # noqa: BLE001 -- a probe must not take down the worker it exists to protectdiff --git a/studio/backend/core/_xpu_triton_toolchain.py b/studio/backend/core/_xpu_triton_toolchain.pynew file mode 100644index 00000000000..5ffb3efa5ea--- /dev/null+++ b/studio/backend/core/_xpu_triton_toolchain.py@@ -0,0 +1,237 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Windows XPU Triton builds its helpers with icpx, else cl, else $CXX, and uses MSVC flags only when+the path contains `cl.EXE`; Studio is not started from a Developer Prompt, so load vcvars and hand it+`cl.EXE`, plus the Level Zero SDK the helpers link against (#14807)."""++from __future__ import annotations++import os+import sys+import shutil+import logging+import tempfile+import subprocess+from pathlib import Path++from utils.subprocess_compat import windows_hidden_subprocess_kwargs++from ._msvc_env import _have_crt_headers++logger = logging.getLogger(__name__)++_VCVARS_KEYS = ("PATH", "INCLUDE", "LIB", "LIBPATH")+++def _triton_is_xpu() -> bool:+ """Only Intel's fork ships an `intel` backend; cheaper than `packages_distributions()`."""+ path = getattr(sys.modules.get("triton"), "__file__", None)+ return bool(path) and os.path.isdir(os.path.join(os.path.dirname(path), "backends", "intel"))+++def _basename(path: str) -> str:+ return os.path.basename(str(path)).lower()+++def _is_cl(path: str) -> bool:+ return _basename(path) in ("cl", "cl.exe")+++def _is_icpx(path: str) -> bool:+ return _basename(path) in ("icpx", "icpx.exe")+++def _triton_cl_spelling(cl_path: str) -> str:+ """Triton's MSVC test is a case-sensitive `"cl.EXE" in cc`; Windows paths are not."""+ return os.path.join(os.path.dirname(cl_path), "cl.EXE")+++def _msvc_environment_loaded() -> bool:+ return bool(shutil.which("cl")) and _have_crt_headers() and bool(os.environ.get("LIB"))+++def _level_zero_sdk_found() -> bool:+ """Neither the GPU driver nor the wheels ship it; Triton reads LEVEL_ZERO_V1_SDK_PATH, else ZE_PATH."""+ root = os.environ.get("LEVEL_ZERO_V1_SDK_PATH") or os.environ.get("ZE_PATH")+ dirs = [os.path.join(root, "include")] if root else []+ dirs += os.environ.get("INCLUDE", "").split(os.pathsep)+ return any(d and os.path.isfile(os.path.join(d, "level_zero", "ze_api.h")) for d in dirs)+++# Official Windows SDK (MIT, 317 KB), pinned by hash.+_L0_VERSION = "1.34.0"+_L0_URL = (+ "https://github.com/oneapi-src/level-zero/releases/download/"+ f"v{_L0_VERSION}/level-zero-win-sdk-{_L0_VERSION}.zip"+)+_L0_SHA256 = "3050280cc94b7a5db7fb173391fcced9b7284ae196bcaf05a566d2911baa7733"+++def _sdk_complete(root: Path) -> bool:+ return (root / "include" / "level_zero" / "ze_api.h").is_file() and (+ root / "lib" / "ze_loader.lib"+ ).is_file()+++def _fetch_level_zero_sdk(dest: Path) -> None:+ import hashlib # noqa: PLC0415+ import io # noqa: PLC0415+ import urllib.request # noqa: PLC0415+ import zipfile # noqa: PLC0415++ with urllib.request.urlopen(_L0_URL, timeout = 30) as response:+ blob = response.read()+ if hashlib.sha256(blob).hexdigest() != _L0_SHA256:+ raise ValueError("Level Zero SDK archive does not match its pinned hash")+ dest.parent.mkdir(parents = True, exist_ok = True)+ staging = Path(tempfile.mkdtemp(prefix = dest.name + ".", dir = dest.parent))+ try:+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:+ for member in archive.infolist():+ # The archive names members with backslashes; zipfile only maps those on Windows.+ parts = member.filename.replace("\\", "/").split("/")+ if member.is_dir() or not parts[-1]:+ continue+ if any(p in ("", ".", "..") or ":" in p for p in parts):+ raise ValueError(f"unexpected member {member.filename!r}")+ target = staging.joinpath(*parts)+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(archive.read(member))+ # A concurrent worker may have installed the same pinned archive first.+ try:+ os.replace(staging, dest)+ except OSError:+ if not _sdk_complete(dest):+ raise+ finally:+ if staging.exists():+ shutil.rmtree(staging, ignore_errors = True)+++def _provide_level_zero_sdk() -> str | None:+ try:+ from utils.paths.storage_roots import cache_root # noqa: PLC0415+ from utils.utils import package_installs_offline # noqa: PLC0415++ dest = cache_root() / f"level-zero-sdk-{_L0_VERSION}"+ if not _sdk_complete(dest) and not package_installs_offline():+ _fetch_level_zero_sdk(dest)+ return str(dest) if _sdk_complete(dest) else None+ except Exception: # noqa: BLE001+ logger.debug("Could not provide the Level Zero SDK", exc_info = True)+ return None+++def _vcvars_path() -> str | None:+ root = os.environ.get("ProgramFiles(x86)") or r"C:\Program Files (x86)"+ vswhere = os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe")+ if not os.path.isfile(vswhere):+ return None+ try:+ done = subprocess.run(+ [+ vswhere,+ "-latest",+ "-products",+ "*",+ "-requires",+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",+ "-property",+ "installationPath",+ ],+ capture_output = True,+ text = True,+ timeout = 60,+ **windows_hidden_subprocess_kwargs(),+ )+ except Exception: # noqa: BLE001+ logger.debug("vswhere could not be run", exc_info = True)+ return None+ install = (done.stdout or "").strip().splitlines()+ if done.returncode != 0 or not install:+ return None+ vcvars = os.path.join(install[0].strip(), "VC", "Auxiliary", "Build", "vcvars64.bat")+ return vcvars if os.path.isfile(vcvars) else None+++def _vcvars_environment(vcvars: str) -> dict | None:+ """`/u`: UTF-16 `set` output, else the OEM code page garbles non-ASCII PATH entries (setuptools)."""+ try:+ done = subprocess.run(+ f'cmd /d /u /s /c ""{vcvars}" >nul 2>&1 && set"',+ capture_output = True,+ timeout = 120,+ **windows_hidden_subprocess_kwargs(),+ )+ except Exception: # noqa: BLE001+ logger.debug("vcvars64.bat could not be run", exc_info = True)+ return None+ if done.returncode != 0:+ return None+ env = {}+ for line in (done.stdout or b"").decode("utf-16-le", errors = "replace").splitlines():+ key, sep, value = line.partition("=")+ if sep and key.upper() in _VCVARS_KEYS:+ env[key.upper()] = value+ return env if "INCLUDE" in env and "PATH" in env else None+++def _load_msvc_environment() -> bool:+ vcvars = _vcvars_path()+ if vcvars is None:+ return False+ env = _vcvars_environment(vcvars)+ if not env:+ return False+ os.environ.update(env)+ return True+++def prepare_xpu_triton_compiler(log: logging.Logger) -> None:+ """Make XPU Triton's helper builds work on Windows. Never raises; an unfixable state is logged."""+ if sys.platform != "win32" or not _triton_is_xpu():+ return+ try:+ _prepare(log)+ except Exception: # noqa: BLE001 -- a toolchain fix must not take down the worker+ logger.debug("Preparing XPU Triton's compiler raised", exc_info = True)+++def _prepare(log: logging.Logger) -> None:+ cxx = os.environ.get("CXX")+ if cxx and _is_icpx(cxx):+ return+ if cxx and not _is_cl(cxx):+ log.warning(+ "CXX=%s: Intel XPU Triton on Windows adds MSVC /LIBPATH: flags to every build, so only "+ "cl or icpx can compile its helpers. Unset CXX to let Studio use Visual Studio's cl.",+ cxx,+ )+ return+ if not cxx and shutil.which("icpx"):+ return+ if not _msvc_environment_loaded() and _load_msvc_environment():+ log.info("Loaded the Visual Studio C++ environment for Intel XPU Triton")+ cl = shutil.which(cxx or "cl")+ if cl is None:+ log.warning(+ "Intel XPU Triton needs a C++ compiler on Windows and none was found. Install Visual "+ "Studio Build Tools (C++ workload): winget install Microsoft.VisualStudio.2022.BuildTools "+ '--override "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended".'+ )+ return+ os.environ["CXX"] = _triton_cl_spelling(cl)+ if _level_zero_sdk_found():+ return+ sdk = _provide_level_zero_sdk()+ if sdk is not None:+ os.environ["LEVEL_ZERO_V1_SDK_PATH"] = sdk+ return+ log.warning(+ "Intel XPU Triton on Windows also needs the Level Zero SDK, which the GPU driver does not "+ "include, and it could not be downloaded: unzip level-zero-win-sdk-%s.zip from "+ "https://github.com/oneapi-src/level-zero/releases and set LEVEL_ZERO_V1_SDK_PATH to that "+ "folder, then restart Unsloth.",+ _L0_VERSION,+ )diff --git a/studio/backend/tests/test_xpu_triton_toolchain_14807.py b/studio/backend/tests/test_xpu_triton_toolchain_14807.pynew file mode 100644index 00000000000..3f527db492e--- /dev/null+++ b/studio/backend/tests/test_xpu_triton_toolchain_14807.py@@ -0,0 +1,332 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Intel XPU Triton's compiler on Windows (#14807). Discovery is stubbed, so these also run on CI Linux."""++import os+import sys+import types+import logging++import pytest++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++from core import _msvc_env+from core import _xpu_triton_toolchain as toolchain++CL = os.path.join("C:", "VS", "VC", "Tools", "MSVC", "bin", "Hostx64", "x64", "cl.exe")+++def xpu_windows(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(toolchain, "_triton_is_xpu", lambda: True)+ monkeypatch.delenv("CXX", raising = False)+++def _which(table):+ return lambda name: table.get(name)+++def test_triton_spelling_matches_its_msvc_test():+ spelled = toolchain._triton_cl_spelling(CL)+ assert "cl.EXE" in spelled+ assert os.path.dirname(spelled) == os.path.dirname(CL)+++def test_loads_visual_studio_and_points_triton_at_cl(xpu_windows, monkeypatch):+ table = {}++ def load():+ table["cl"] = CL+ return True++ monkeypatch.setattr(toolchain.shutil, "which", _which(table))+ monkeypatch.setattr(toolchain, "_msvc_environment_loaded", lambda: False)+ monkeypatch.setattr(toolchain, "_load_msvc_environment", load)++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert os.environ["CXX"] == toolchain._triton_cl_spelling(CL)+++def test_a_lowercase_cl_in_cxx_is_respelled(xpu_windows, monkeypatch):+ monkeypatch.setenv("CXX", CL)+ monkeypatch.setattr(toolchain.shutil, "which", _which({CL: CL}))+ monkeypatch.setattr(toolchain, "_msvc_environment_loaded", lambda: True)++ def never():+ raise AssertionError("the environment was already loaded")++ monkeypatch.setattr(toolchain, "_load_msvc_environment", never)++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert "cl.EXE" in os.environ["CXX"]+++def test_a_gnu_driver_in_cxx_is_left_alone_with_a_warning(xpu_windows, monkeypatch, caplog):+ monkeypatch.setenv("CXX", "clang++.exe")+ monkeypatch.setattr(toolchain, "_load_msvc_environment", lambda: pytest.fail("not wanted"))++ with caplog.at_level(logging.WARNING):+ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert os.environ["CXX"] == "clang++.exe"+ assert "/LIBPATH:" in caplog.text++[email protected]("where", ["LEVEL_ZERO_V1_SDK_PATH", "ZE_PATH", "INCLUDE", None])+def test_a_missing_level_zero_sdk_is_named(xpu_windows, monkeypatch, caplog, tmp_path, where):+ for var in ("LEVEL_ZERO_V1_SDK_PATH", "ZE_PATH", "INCLUDE"):+ monkeypatch.delenv(var, raising = False)+ (tmp_path / "include" / "level_zero").mkdir(parents = True)+ (tmp_path / "include" / "level_zero" / "ze_api.h").write_text("")+ if where == "INCLUDE":+ monkeypatch.setenv("INCLUDE", str(tmp_path / "include"))+ elif where:+ monkeypatch.setenv(where, str(tmp_path))+ monkeypatch.setattr(toolchain.shutil, "which", _which({"cl": CL}))+ monkeypatch.setattr(toolchain, "_msvc_environment_loaded", lambda: True)+ monkeypatch.setattr(toolchain, "_provide_level_zero_sdk", lambda: None)++ with caplog.at_level(logging.WARNING):+ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert os.environ["CXX"] == toolchain._triton_cl_spelling(CL)+ assert ("LEVEL_ZERO_V1_SDK_PATH" in caplog.text) is (where is None)+++def test_a_missing_level_zero_sdk_is_provided(xpu_windows, monkeypatch, caplog):+ for var in ("LEVEL_ZERO_V1_SDK_PATH", "ZE_PATH", "INCLUDE"):+ monkeypatch.delenv(var, raising = False)+ monkeypatch.setattr(toolchain.shutil, "which", _which({"cl": CL}))+ monkeypatch.setattr(toolchain, "_msvc_environment_loaded", lambda: True)+ monkeypatch.setattr(toolchain, "_provide_level_zero_sdk", lambda: r"C:\studio\cache\l0")++ with caplog.at_level(logging.WARNING):+ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert os.environ["LEVEL_ZERO_V1_SDK_PATH"] == r"C:\studio\cache\l0"+ assert "Level Zero" not in caplog.text+++def _sdk_zip(names):+ import io+ import zipfile++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ for name in names:+ z.writestr(name, "x")+ return buf.getvalue()+++def _serve(+ monkeypatch,+ blob,+ pin = True,+):+ import hashlib+ import contextlib+ import urllib.request++ if pin:+ monkeypatch.setattr(toolchain, "_L0_SHA256", hashlib.sha256(blob).hexdigest())++ @contextlib.contextmanager+ def urlopen(url, timeout):+ yield types.SimpleNamespace(read = lambda: blob)++ monkeypatch.setattr(urllib.request, "urlopen", urlopen)+++def test_the_sdk_archive_is_unpacked_from_its_backslash_names(tmp_path, monkeypatch):+ # The real archive's layout: Windows separators inside the zip.+ _serve(monkeypatch, _sdk_zip([r"include\level_zero\ze_api.h", r"lib\ze_loader.lib"]))+ dest = tmp_path / "level-zero-sdk"++ toolchain._fetch_level_zero_sdk(dest)++ assert toolchain._sdk_complete(dest)+ assert [p.name for p in tmp_path.iterdir()] == ["level-zero-sdk"]+++ "names, pin",+ [+ ([r"include\level_zero\ze_api.h", r"lib\ze_loader.lib"], False),+ ([r"..\evil.dll", r"lib\ze_loader.lib"], True),+ ],+)+def test_a_bad_sdk_archive_leaves_nothing_behind(tmp_path, monkeypatch, names, pin):+ _serve(monkeypatch, _sdk_zip(names), pin = pin)+ dest = tmp_path / "level-zero-sdk"++ with pytest.raises(ValueError):+ toolchain._fetch_level_zero_sdk(dest)++ assert list(tmp_path.iterdir()) == []+++def test_icpx_on_path_is_left_to_triton(xpu_windows, monkeypatch):+ monkeypatch.setattr(toolchain.shutil, "which", _which({"icpx": "icpx.exe"}))+ monkeypatch.setattr(toolchain, "_load_msvc_environment", lambda: pytest.fail("not wanted"))++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert "CXX" not in os.environ+++def test_no_compiler_anywhere_warns_and_sets_nothing(xpu_windows, monkeypatch, caplog):+ monkeypatch.setattr(toolchain.shutil, "which", _which({}))+ monkeypatch.setattr(toolchain, "_msvc_environment_loaded", lambda: False)+ monkeypatch.setattr(toolchain, "_load_msvc_environment", lambda: False)++ with caplog.at_level(logging.WARNING):+ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert "CXX" not in os.environ+ assert "Build Tools" in caplog.text+++ "backends, expected", [(("amd", "nvidia"), False), (("amd", "intel", "nvidia"), True)]+)+def test_only_a_triton_with_an_intel_backend_is_xpu(tmp_path, monkeypatch, backends, expected):+ pkg = tmp_path / "triton"+ for name in backends:+ (pkg / "backends" / name).mkdir(parents = True)+ fake = types.ModuleType("triton")+ fake.__file__ = str(pkg / "__init__.py")+ monkeypatch.setitem(sys.modules, "triton", fake)++ assert toolchain._triton_is_xpu() is expected+++def test_triton_windows_is_not_touched(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(toolchain, "_triton_is_xpu", lambda: False)+ monkeypatch.delenv("CXX", raising = False)+ monkeypatch.setattr(toolchain, "_prepare", lambda log: pytest.fail("not wanted"))++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))++ assert "CXX" not in os.environ+++def test_off_windows_nothing_happens(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(toolchain, "_prepare", lambda log: pytest.fail("not wanted"))++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))+++def test_a_failure_never_reaches_the_worker(xpu_windows, monkeypatch):+ def boom(log):+ raise RuntimeError("vswhere blew up")++ monkeypatch.setattr(toolchain, "_prepare", boom)++ toolchain.prepare_xpu_triton_compiler(logging.getLogger("t"))+++def test_vcvars_environment_keeps_only_what_cl_needs(monkeypatch):+ out = "\n".join(+ [+ r"Path=C:\VS\bin;C:\Users\José\bin",+ r"INCLUDE=C:\VS\include",+ r"LIB=C:\VS\lib",+ r"LIBPATH=C:\VS\libpath",+ r"VSCMD_ARG_TGT_ARCH=x64",+ r"USERNAME=someone",+ ]+ )+ monkeypatch.setattr(+ toolchain.subprocess,+ "run",+ lambda *a, **k: types.SimpleNamespace(returncode = 0, stdout = out.encode("utf-16-le")),+ )++ env = toolchain._vcvars_environment(r"C:\VS\vcvars64.bat")++ assert env == {+ "PATH": r"C:\VS\bin;C:\Users\José\bin",+ "INCLUDE": r"C:\VS\include",+ "LIB": r"C:\VS\lib",+ "LIBPATH": r"C:\VS\libpath",+ }+++def test_a_failed_vcvars_yields_nothing(monkeypatch):+ monkeypatch.setattr(+ toolchain.subprocess,+ "run",+ lambda *a, **k: types.SimpleNamespace(returncode = 1, stdout = b""),+ )++ assert toolchain._vcvars_environment(r"C:\VS\vcvars64.bat") is None+++def test_the_windows_gate_prepares_xpu_triton(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(_msvc_env, "_torch_is_rocm_build", lambda: False)+ monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))+ monkeypatch.setattr(_msvc_env, "crt_headers_reachable", lambda: True)+ calls = []+ monkeypatch.setattr(toolchain, "prepare_xpu_triton_compiler", lambda log: calls.append(log))++ _msvc_env.gate_torch_compile_on_windows(logging.getLogger("t"))++ assert len(calls) == 1++[email protected]("offline", [True, False])+def test_offline_installs_use_only_a_cached_sdk(tmp_path, monkeypatch, offline):+ from utils import utils as studio_utils+ from utils.paths import storage_roots++ monkeypatch.setattr(storage_roots, "cache_root", lambda: tmp_path)+ monkeypatch.setattr(studio_utils, "package_installs_offline", lambda: offline)+ fetched = []++ def fetch(dest):+ fetched.append(dest)+ for rel in (("include", "level_zero", "ze_api.h"), ("lib", "ze_loader.lib")):+ dest.joinpath(*rel).parent.mkdir(parents = True, exist_ok = True)+ dest.joinpath(*rel).write_text("")++ monkeypatch.setattr(toolchain, "_fetch_level_zero_sdk", fetch)++ got = toolchain._provide_level_zero_sdk()++ assert bool(fetched) is not offline+ assert (got is None) is offline+ if offline:+ fetch(tmp_path / f"level-zero-sdk-{toolchain._L0_VERSION}")+ assert toolchain._provide_level_zero_sdk() is not None+++def test_toolchain_probes_open_no_console_window(tmp_path, monkeypatch):+ # Desktop starts workers with no console; cmd.exe and vswhere.exe would each flash one.+ hidden = {"creationflags": 0x08000000}+ monkeypatch.setattr(toolchain, "windows_hidden_subprocess_kwargs", lambda: dict(hidden))+ vswhere = tmp_path / "Microsoft Visual Studio" / "Installer" / "vswhere.exe"+ vswhere.parent.mkdir(parents = True)+ vswhere.write_text("")+ monkeypatch.setenv("ProgramFiles(x86)", str(tmp_path))+ seen = []++ def run(*a, **k):+ seen.append(k)+ return types.SimpleNamespace(returncode = 1, stdout = b"" if "text" not in k else "")++ monkeypatch.setattr(toolchain.subprocess, "run", run)++ toolchain._vcvars_path()+ toolchain._vcvars_environment(r"C:\VS\vcvars64.bat")++ assert len(seen) == 2+ assert all(k.get("creationflags") == hidden["creationflags"] for k in seen)