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
fix(amd): don't enable torch.compile when Triton's C toolchain can't compile it (Windows) (#7704)
Leo Borcherding607a8af64d76
diff --git a/studio/backend/core/_msvc_env.py b/studio/backend/core/_msvc_env.pynew file mode 100644index 00000000000..6baaea50e46--- /dev/null+++ b/studio/backend/core/_msvc_env.py@@ -0,0 +1,233 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Gate torch.compile on Triton's C toolchain, on Windows (#7595). `import triton` succeeding does not+mean a compile will: Triton's clang-cl JIT dies on `'stdlib.h'` mid-run when the CRT headers are absent.+It passes its own `/I` dirs and never reads `INCLUDE`, so there is nothing to repair, only a state to refuse."""++from __future__ import annotations++import os+import sys+import logging++logger = logging.getLogger(__name__)+++def _headers_complete(dirs) -> bool:+ """`stdlib.h` alone is a standalone SDK: its ucrt pulls in `vcruntime.h` from the VC toolset,+ so the compile still dies there (measured with the toolset dir removed). Both, or not whole."""++ def found(name: str) -> bool:+ return any(d and os.path.isfile(os.path.join(d, name)) for d in dirs)++ return found("stdlib.h") and found("vcruntime.h")+++def _have_crt_headers() -> bool:+ return _headers_complete(os.environ.get("INCLUDE", "").split(os.pathsep))+++def _triton_include_dirs() -> list | None:+ """None means the search could not be run, which is not the same as running and finding nothing.+ Only the latter may gate: `find_msvc_winsdk` is private, so a rename or a changed return arity+ would otherwise read as "no headers" and disable torch.compile on a machine with Visual Studio."""+ try:+ from triton.windows_utils import find_msvc_winsdk # noqa: PLC0415+ _, inc_dirs, _ = find_msvc_winsdk()+ except Exception: # noqa: BLE001+ logger.debug("Triton's MSVC/WinSDK discovery is unavailable", exc_info = True)+ return None+ return list(inc_dirs)+++def _triton_finds_crt_headers() -> bool | None:+ dirs = _triton_include_dirs()+ return None if dirs is None else _headers_complete(dirs)+++def _triton_is_triton_windows() -> bool:+ """XPU Triton and triton-windows own the same top-level name; only the distribution says which."""+ try:+ import importlib.metadata as md # noqa: PLC0415+ dists = md.packages_distributions().get("triton") or ()+ except Exception: # noqa: BLE001+ logger.debug("Could not resolve which distribution owns `triton`", exc_info = True)+ return False+ return any(d.lower().replace("_", "-") == "triton-windows" for d in dists)+++def _rocm_clang_cl_present() -> bool:+ import sysconfig # noqa: PLC0415+ return os.path.isfile(+ os.path.join(+ sysconfig.get_path("platlib"), "_rocm_sdk_core", "lib", "llvm", "bin", "clang-cl.exe"+ )+ )+++def _cc_needs_msvc_headers(cc: str) -> bool:+ """Triton's own predicates decide, so this cannot disagree with what it does. They are imported+ apart from `get_cc` because `is_clang_cl` only arrived in triton-windows 3.5.1.post23: importing+ all three together failed on every earlier release and threw away a usable `get_cc` with it.+ The fallback is what both predicates do, a case-insensitive basename match."""+ try:+ from triton.runtime.build import is_clang_cl, is_msvc # noqa: PLC0415+ return bool(is_msvc(cc) or is_clang_cl(cc))+ except Exception: # noqa: BLE001+ logger.debug("Triton's compiler predicates are unavailable", exc_info = True)+ return os.path.basename(str(cc)).lower() in ("cl", "cl.exe", "clang-cl", "clang-cl.exe")+++def _triton_cc() -> str:+ """triton-windows 3.8.0.post28, what a bare `pip install triton-windows` gives you today, has no+ `get_cc` at all: it was renamed `_find_compiler(language)`, whose "c" branch is the old body.+ Without this the newest release never reaches the compiler question and answers from the wheel+ layout instead."""+ try:+ from triton.runtime.build import get_cc # noqa: PLC0415+ except ImportError:+ from triton.runtime.build import _find_compiler # noqa: PLC0415+ return _find_compiler("c")+ return get_cc()+++def _needs_msvc_headers() -> bool:+ """Only cl and clang-cl need them; Triton otherwise picks bundled TinyCC, which carries its own.+ The fallback needs both halves: an in-place ROCm-to-XPU repair leaves the compiler on disk without+ the Triton that selects it. Unanswerable means ungated: gating wrongly breaks a working box."""+ try:+ cc = _triton_cc()+ except Exception: # noqa: BLE001+ logger.debug("Triton's compiler selection is unavailable", exc_info = True)+ return _triton_is_triton_windows() and _rocm_clang_cl_present()+ return _cc_needs_msvc_headers(cc)+++def _toolchain_summary() -> str:+ """0 include dirs means no Visual Studio; dirs missing only `vcruntime.h` means an SDK+ without the VC toolset."""+ try:+ cc = os.path.basename(_triton_cc())+ except Exception: # noqa: BLE001+ cc = "unknown"+ try:+ from triton.windows_utils import find_msvc_winsdk # noqa: PLC0415+ _, inc_dirs, _ = find_msvc_winsdk()+ except Exception: # noqa: BLE001+ inc_dirs = []+ logger.debug("Triton include dirs: %s", list(inc_dirs))+ missing = [+ h+ for h in ("stdlib.h", "vcruntime.h")+ if not any(d and os.path.isfile(os.path.join(d, h)) for d in inc_dirs)+ ]+ return (+ f"compiler={cc}, Triton include dirs={len(inc_dirs)}, "+ f"missing headers={','.join(missing) or 'none'}, "+ f"INCLUDE={'set' if os.environ.get('INCLUDE') else 'unset'}"+ )+++def _compiles_a_trivial_translation_unit(cc: str, inc_dirs) -> bool | None:+ """Ask the compiler instead of predicting it. None means the probe could not be run.++ Header discovery is an inference and it is wrong in the expensive direction: clang-cl+ locates MSVC through its own search, so on a measured R9700 it compiled with INCLUDE,+ VCINSTALLDIR and WindowsSdkDir all cleared, injecting an -internal-isystem we can see+ no trace of. Predicting from directories alone would disable torch.compile there."""+ import subprocess # noqa: PLC0415+ import tempfile # noqa: PLC0415++ try:+ with tempfile.TemporaryDirectory() as tmp:+ src = os.path.join(tmp, "probe.c")+ with open(src, "w", encoding = "utf-8") as fh:+ fh.write("#include <stdlib.h>\nint main(void){return 0;}\n")+ # Syntax-only: no link, so a missing lib path cannot masquerade as a missing+ # header, and nothing is written outside the temporary directory.+ argv = [cc, "/Zs", src] + [f"/I{d}" for d in inc_dirs if d]+ done = subprocess.run(+ argv,+ cwd = tmp,+ capture_output = True,+ timeout = 90,+ )+ except Exception: # noqa: BLE001+ logger.debug("The compiler probe could not be run", exc_info = True)+ return None+ if done.returncode != 0:+ logger.debug("Compiler probe failed: %s", (done.stderr or b"")[-400:])+ return done.returncode == 0+++def crt_headers_reachable() -> bool:+ if sys.platform != "win32":+ return True+ if not _needs_msvc_headers():+ return True+ triton_dirs = _triton_include_dirs()++ # The compiler is asked FIRST, because every check below it is inference and inference is+ # wrong in both directions. It over-gates when clang-cl locates MSVC through its own search,+ # which the directory listing cannot see. It under-gates on a partial or mismatched SDK: the+ # two markers are only the entry points, and `vcruntime.h` includes `sal.h`, which lives in+ # the SDK's `shared` directory rather than beside either marker, so a dir set can carry both+ # markers and still fail to compile. Only a compile answers the question the JIT will ask.+ if triton_dirs is not None:+ try:+ verdict = _compiles_a_trivial_translation_unit(_triton_cc(), triton_dirs)+ except Exception: # noqa: BLE001+ verdict = None+ if verdict is not None:+ return verdict++ # Fallback, for a host where the probe could not be run at all. Unknown is not evidence of+ # a broken toolchain, so these keep their fail-open shape.+ env_dirs = os.environ.get("INCLUDE", "").split(os.pathsep)+ if _headers_complete(env_dirs):+ return True+ # INCLUDE is a positive signal only: unset is the normal case (Studio is not launched from a+ # Developer Command Prompt), so only Triton's own search coming back empty may gate.+ if triton_dirs is None:+ return True+ # Judged over the UNION, because that is what the compile sees: clang-cl reads INCLUDE as+ # system include paths and Triton passes its own dirs as /I. Judging each alone rejects a+ # split toolchain (VC toolset on INCLUDE, SDK discovered by Triton) that compiles fine.+ return _headers_complete(triton_dirs + env_dirs)+++def gate_torch_compile_on_windows(log: logging.Logger) -> None:+ if sys.platform != "win32":+ return+ try:+ import triton # noqa: F401, PLC0415+ except ImportError:+ os.environ["TORCHDYNAMO_DISABLE"] = "1"+ log.warning(+ "Triton not found on Windows — torch.compile disabled. "+ 'Install for better performance: pip install "triton-windows<3.7"'+ )+ return++ try:+ reachable = crt_headers_reachable()+ except Exception: # noqa: BLE001 -- a probe must not take down the worker it exists to protect+ logger.debug("The toolchain probe raised; leaving torch.compile alone", exc_info = True)+ reachable = True+ if reachable:+ log.info("Triton available — torch.compile enabled")+ return++ os.environ["TORCHDYNAMO_DISABLE"] = "1"+ # This only turns off the compiles we own; Unsloth's @triton.jit kernels still need the toolchain.+ log.warning(+ "Triton is installed but its C toolchain has no CRT headers, so its "+ "clang-cl JIT would fail on 'stdlib.h' (#7595). torch.compile disabled; "+ "directly launched Triton kernels still need the toolchain. "+ "Install Visual Studio Build Tools (C++ workload): winget "+ 'install Microsoft.VisualStudio.2022.BuildTools --override "--add '+ 'Microsoft.VisualStudio.Workload.VCTools --includeRecommended". '+ "Probe saw: %s.",+ _toolchain_summary(),+ )diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex 5388780bd0b..3d9c285d236 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -574,16 +574,10 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> Nonereturn# ── 1b. Check Triton on Windows (must precede import torch) ──+ # Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).if sys.platform == "win32":- try:- import triton # noqa: F401- logger.info("Triton available — torch.compile enabled")- except ImportError:- os.environ["TORCHDYNAMO_DISABLE"] = "1"- logger.warning(- "Triton not found on Windows — torch.compile disabled. "- 'Install for better performance: pip install "triton-windows<3.7"'- )+ from core._msvc_env import gate_torch_compile_on_windows+ gate_torch_compile_on_windows(logger)# ── 1c. Stub torchao on Windows ROCm ──# See core/_torchao_stub.py: torchao crashes on Windows ROCm (RCCL absent).diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 5d67f4bfb1b..23577d2c774 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -161,7 +161,11 @@ def torch_compile_runtime_available() -> bool:import triton # noqa: F401, PLC0415except Exception: # noqa: BLE001 -- absent or broken Triton means eager, never a failed loadreturn False- return True+ try:+ from .._msvc_env import crt_headers_reachable # noqa: PLC0415+ return crt_headers_reachable()+ except Exception: # noqa: BLE001 -- this runs during load; never fail it over a probe+ return Truedef compile_eligible(target: Any, *, is_gguf: bool, family: Any) -> bool:@@ -240,7 +244,8 @@ def apply_speed_optims(# default = LIGHT: GGUF compiles ONLY the dequant op chain (cheap, VRAM-free, resolution-invariant); dense falls back to the# regional block compile. max = FULL: regional max-autotune compile of the repeated block. eager = no compile.if mode == SPEED_DEFAULT:- if is_gguf and on_cuda and family_allows_compile:+ # Asked directly: this arm never reaches compile_eligible(), unlike the dense arm below.+ if is_gguf and on_cuda and family_allows_compile and torch_compile_runtime_available():applied["compiled_dequant"] = gguf_compile.install_compiled_dequant(logger)elif compile_eligible(target, is_gguf = is_gguf, family = family):# A U-Net (SDXL) fuses QKV BEFORE its whole-module compile: 36.3 vs 39.3 ms/step (LPIPS 0.033). DiTs were neutral, so they keep the fuse on max only.diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 20b96f209b4..086599a5689 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -1231,16 +1231,10 @@ def run_inference_process(# ── Windows: check Triton availability ──# Ahead of the torchao stub below, matching the training and export workers' gate-then-stub order.+ # Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).if sys.platform == "win32":- try:- import triton # noqa: F401- logger.info("Triton available — torch.compile enabled")- except ImportError:- os.environ["TORCHDYNAMO_DISABLE"] = "1"- logger.warning(- "Triton not found on Windows — torch.compile disabled. "- 'Install for better performance: pip install "triton-windows<3.7"'- )+ from core._msvc_env import gate_torch_compile_on_windows+ gate_torch_compile_on_windows(logger)# ── Stub torchao on Windows ROCm before ANY transformers import ──# Must precede every path that pulls transformers, not just the ML imports in section 2:diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 82b5178a561..9431d49a12d 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -3888,16 +3888,10 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -># stdlib multiprocessing onto "fork" never reached it; the guard now asks multiprocess.# ── 1c. On Windows, check Triton availability (must be before import torch) ──+ # Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).if sys.platform == "win32":- try:- import triton # noqa: F401- logger.info("Triton available — torch.compile enabled")- except ImportError:- os.environ["TORCHDYNAMO_DISABLE"] = "1"- logger.warning(- "Triton not found on Windows — torch.compile disabled. "- 'Install for better performance: pip install "triton-windows<3.7"'- )+ from core._msvc_env import gate_torch_compile_on_windows+ gate_torch_compile_on_windows(logger)# ── 1d. Stub torchao on Windows ROCm ──# See core/_torchao_stub.py (no RCCL on Windows ROCm); run before transformers/unsloth_zoo.diff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.pyindex 7f53a5f8923..9943c4f35ee 100644--- a/studio/backend/tests/test_diffusion_speed.py+++ b/studio/backend/tests/test_diffusion_speed.py@@ -60,6 +60,23 @@ def _family(*, compile_ok = True):return types.SimpleNamespace(supports_torch_compile = compile_ok)[email protected](autouse = True)+def _compile_runtime_independent_of_the_host(monkeypatch):+ """Keep these tests off the HOST's toolchain, which is what "hermetic" above claims.++ ``torch_compile_runtime_available`` asks whether THIS machine can run inductor, and on+ Windows that means asking whether a Triton wheel is installed. Without this, every+ compile-tier assertion in the file fails on a Windows checkout with no ``triton-windows``+ for a reason that has nothing to do with tiering (measured: 15 failures on a+ ``windows-latest`` runner, all green on Linux and macOS). Pin the non-Windows branch; the+ tests that are *about* Windows set ``sys.platform`` themselves and a later setattr wins.+ The lru_cache is dropped either side so one test's answer is never another test's."""+ ds_mod.torch_compile_runtime_available.cache_clear()+ monkeypatch.setattr(ds_mod.sys, "platform", "linux")+ yield+ ds_mod.torch_compile_runtime_available.cache_clear()++def _stub_torch(monkeypatch):torch = types.ModuleType("torch")torch.bfloat16 = "bfloat16" # _is_bfloat16 compares by identity then str fallback@@ -719,12 +736,24 @@ def _clear_runtime_cache():torch_compile_runtime_available.cache_clear()-def test_torchdynamo_disable_is_honored_on_every_platform(monkeypatch):+def _set_crt_headers(monkeypatch, reachable: bool):+ from core import _msvc_env+ monkeypatch.setattr(_msvc_env, "crt_headers_reachable", lambda: reachable)++[email protected]("platform", ["linux", "win32"])+def test_torchdynamo_disable_is_honored_on_every_platform(monkeypatch, platform):from core.inference import diffusion_speed as ds_mod# compile_eligible reads torch to test the dtype, and without the stub it returns False for# every input -- which would make the assertions below pass whatever the gate did._stub_torch(monkeypatch)+ # Both platforms, or the name is a claim the test never checks. The positive control must+ # clear the Windows toolchain question first, or the negatives hold for the wrong reason.+ monkeypatch.setattr(ds_mod.sys, "platform", platform)+ if platform == "win32":+ monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))+ _set_crt_headers(monkeypatch, True)_clear_runtime_cache()monkeypatch.delenv("TORCHDYNAMO_DISABLE", raising = False)# The positive control. Without it the two `is False` lines below prove nothing.@@ -753,13 +782,65 @@ def test_windows_without_triton_falls_back_to_eager(monkeypatch):assert ds_mod.torch_compile_runtime_available() is Falseassert ds_mod.compile_eligible(_target(), is_gguf = False, family = _family()) is False- # A Windows install that DOES have the wheel is not held back.monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))+ _set_crt_headers(monkeypatch, True)+ _clear_runtime_cache()+ assert ds_mod.torch_compile_runtime_available() is True+ _clear_runtime_cache()+++def test_windows_with_triton_but_no_msvc_falls_back_to_eager(monkeypatch):+ from core.inference import diffusion_speed as ds_mod++ monkeypatch.delenv("TORCHDYNAMO_DISABLE", raising = False)+ monkeypatch.setattr(ds_mod.sys, "platform", "win32")+ monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))++ _set_crt_headers(monkeypatch, False)+ _clear_runtime_cache()+ assert ds_mod.torch_compile_runtime_available() is False++ _set_crt_headers(monkeypatch, True)_clear_runtime_cache()assert ds_mod.torch_compile_runtime_available() is True_clear_runtime_cache()+def test_gguf_dequant_respects_the_runtime_gate(monkeypatch):+ from core.inference import diffusion_speed as ds_mod++ _stub_torch(monkeypatch)+ called = _stub_gguf_accel(monkeypatch)+ monkeypatch.delenv("TORCHDYNAMO_DISABLE", raising = False)+ monkeypatch.setattr(ds_mod.sys, "platform", "win32")+ monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))++ _set_crt_headers(monkeypatch, False)+ _clear_runtime_cache()+ applied = apply_speed_optims(+ object(),+ _target(),+ is_gguf = True,+ family = _family(),+ speed_mode = SPEED_DEFAULT,+ )+ assert called["compiled_dequant"] == 0+ assert not applied.get("compiled_dequant")++ _set_crt_headers(monkeypatch, True)+ _clear_runtime_cache()+ applied = apply_speed_optims(+ object(),+ _target(),+ is_gguf = True,+ family = _family(),+ speed_mode = SPEED_DEFAULT,+ )+ assert called["compiled_dequant"] == 1+ assert applied.get("compiled_dequant") is True+ _clear_runtime_cache()++def test_linux_and_mac_are_not_asked_about_triton(monkeypatch):"""Only Windows ships without it, and a probe import on a healthy Linux box is pure cost."""from core.inference import diffusion_speed as ds_moddiff --git a/studio/backend/tests/test_msvc_env_7595.py b/studio/backend/tests/test_msvc_env_7595.pynew file mode 100644index 00000000000..0be1f3f6e93--- /dev/null+++ b/studio/backend/tests/test_msvc_env_7595.py@@ -0,0 +1,544 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Triton C-toolchain gate on Windows (#7595). Discovery is stubbed, so these also run on CI Linux."""++import os+import sys+import types+import logging++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++from core import _msvc_env+++def _fake_triton(+ monkeypatch,+ inc_dirs,+ cc = "clang-cl.exe",+ with_is_clang_cl = True,+):+ pkg = types.ModuleType("triton")+ utils = types.ModuleType("triton.windows_utils")+ utils.find_msvc_winsdk = lambda *a, **k: (None, list(inc_dirs), [])+ pkg.windows_utils = utils+ runtime = types.ModuleType("triton.runtime")+ build = types.ModuleType("triton.runtime.build")+ build.get_cc = lambda: cc+ build.is_msvc = lambda c: os.path.basename(c).lower() in ("cl", "cl.exe")+ if with_is_clang_cl:+ build.is_clang_cl = lambda c: os.path.basename(c).lower() in ("clang-cl", "clang-cl.exe")+ runtime.build = build+ pkg.runtime = runtime+ monkeypatch.setitem(sys.modules, "triton", pkg)+ monkeypatch.setitem(sys.modules, "triton.windows_utils", utils)+ monkeypatch.setitem(sys.modules, "triton.runtime", runtime)+ monkeypatch.setitem(sys.modules, "triton.runtime.build", build)+++def test_have_crt_headers_true_when_include_has_both_headers(tmp_path, monkeypatch):+ (tmp_path / "stdlib.h").write_text("/* stub */")+ (tmp_path / "vcruntime.h").write_text("/* stub */")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ assert _msvc_env._have_crt_headers() is True+++def test_have_crt_headers_false_when_include_lacks_stdlib(tmp_path, monkeypatch):+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ assert _msvc_env._have_crt_headers() is False+++def test_have_crt_headers_false_when_include_has_only_stdlib(tmp_path, monkeypatch):+ (tmp_path / "stdlib.h").write_text("/* stub */")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ assert _msvc_env._have_crt_headers() is False+++def test_have_crt_headers_false_when_include_unset(monkeypatch):+ monkeypatch.delenv("INCLUDE", raising = False)+ assert _msvc_env._have_crt_headers() is False+++def _sdk_dirs(tmp_path, *, with_toolset):+ """The real layout: `stdlib.h` in the SDK's ucrt, `vcruntime.h` in the VC toolset include."""+ ucrt = tmp_path / "ucrt"+ ucrt.mkdir()+ (ucrt / "stdlib.h").write_text("/* stub */")+ dirs = [str(tmp_path / "um"), str(ucrt)]+ (tmp_path / "um").mkdir()+ if with_toolset:+ msvc = tmp_path / "msvc"+ msvc.mkdir()+ (msvc / "vcruntime.h").write_text("/* stub */")+ dirs.append(str(msvc))+ return dirs+++def test_triton_discovery_true_when_dirs_carry_both_headers(tmp_path, monkeypatch):+ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = True))+ assert _msvc_env._triton_finds_crt_headers() is True+++def test_triton_discovery_false_when_sdk_lacks_the_vc_toolset(tmp_path, monkeypatch):+ """A standalone SDK passes the `stdlib.h` check and the compile still dies on `vcruntime.h`+ (measured on an R9700 with the toolset dir removed). This must gate."""+ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = False))+ assert _msvc_env._triton_finds_crt_headers() is False+++def test_triton_discovery_false_when_no_dir_has_stdlib(tmp_path, monkeypatch):+ _fake_triton(monkeypatch, [str(tmp_path)])+ assert _msvc_env._triton_finds_crt_headers() is False+++def test_triton_discovery_false_when_search_returns_nothing(monkeypatch):+ _fake_triton(monkeypatch, [])+ assert _msvc_env._triton_finds_crt_headers() is False+++def test_triton_discovery_is_unknown_when_triton_absent(monkeypatch):+ monkeypatch.setitem(sys.modules, "triton.windows_utils", None)+ assert _msvc_env._triton_finds_crt_headers() is None+++def test_triton_discovery_survives_a_raising_search(monkeypatch):+ pkg = types.ModuleType("triton")+ utils = types.ModuleType("triton.windows_utils")++ def boom(*a, **k):+ raise RuntimeError("vswhere blew up")++ utils.find_msvc_winsdk = boom+ pkg.windows_utils = utils+ monkeypatch.setitem(sys.modules, "triton", pkg)+ monkeypatch.setitem(sys.modules, "triton.windows_utils", utils)+ assert _msvc_env._triton_finds_crt_headers() is None+++def test_triton_discovery_is_unknown_when_the_search_changes_arity(monkeypatch):+ """`find_msvc_winsdk` is private. A 2- or 4-tuple must read as unknown, never as "no headers"."""+ for shape in ((["c:/inc"], []), ("", ["c:/inc"], [], [])):+ pkg = types.ModuleType("triton")+ utils = types.ModuleType("triton.windows_utils")+ utils.find_msvc_winsdk = lambda s = shape: s+ pkg.windows_utils = utils+ monkeypatch.setitem(sys.modules, "triton", pkg)+ monkeypatch.setitem(sys.modules, "triton.windows_utils", utils)+ assert _msvc_env._triton_finds_crt_headers() is None+++def test_triton_discovery_is_unknown_when_the_search_returns_none(monkeypatch):+ pkg = types.ModuleType("triton")+ utils = types.ModuleType("triton.windows_utils")+ utils.find_msvc_winsdk = lambda *a, **k: None+ pkg.windows_utils = utils+ monkeypatch.setitem(sys.modules, "triton", pkg)+ monkeypatch.setitem(sys.modules, "triton.windows_utils", utils)+ assert _msvc_env._triton_finds_crt_headers() is None+++def test_reachable_is_true_off_win32(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(+ _msvc_env,+ "_triton_include_dirs",+ lambda: (_ for _ in ()).throw(AssertionError("probed off win32")),+ )+ assert _msvc_env.crt_headers_reachable() is True+++def test_reachable_via_triton_even_when_include_is_empty(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = True))+ assert _msvc_env.crt_headers_reachable() is True+++def test_reachable_via_include_when_triton_finds_nothing(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ (tmp_path / "stdlib.h").write_text("/* stub */")+ (tmp_path / "vcruntime.h").write_text("/* stub */")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ _fake_triton(monkeypatch, [])+ assert _msvc_env.crt_headers_reachable() is True+++def test_not_reachable_when_neither_source_has_headers(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ _fake_triton(monkeypatch, [])+ assert _msvc_env.crt_headers_reachable() is False+++def test_unreachable_discovery_does_not_gate_a_visual_studio_box(tmp_path, monkeypatch):+ """The dangerous direction. Discovery that cannot be asked is not evidence of a missing SDK, and+ clang-cl locates MSVC itself, so gating here would disable torch.compile on a box that compiles."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe")+ monkeypatch.setitem(sys.modules, "triton.windows_utils", None)+ assert _msvc_env.crt_headers_reachable() is True+++def test_a_search_that_ran_and_found_nothing_still_gates(tmp_path, monkeypatch):+ """The other half: without this, the #7595 crash is no longer prevented at all."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe")+ assert _msvc_env.crt_headers_reachable() is False+++def test_tinycc_does_not_need_msvc_headers(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ _fake_triton(monkeypatch, [], cc = "tcc.exe")+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_clang_cl_does_need_msvc_headers(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe")+ assert _msvc_env._needs_msvc_headers() is True+ assert _msvc_env.crt_headers_reachable() is False+++def test_xpu_triton_without_the_private_api_is_not_gated(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ monkeypatch.setitem(sys.modules, "triton.runtime.build", None)+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: False)+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_stale_rocm_clang_cl_under_xpu_triton_is_not_gated(tmp_path, monkeypatch):+ """setup.ps1:4162 repairs in place without pruning, so `_rocm_sdk_core` outlives its Triton."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ monkeypatch.setitem(sys.modules, "triton.runtime.build", None)+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: True)+ monkeypatch.setattr(_msvc_env, "_triton_is_triton_windows", lambda: False)+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_tinycc_is_not_gated_on_a_release_without_is_clang_cl(tmp_path, monkeypatch):+ """3.2.0.post18 to 3.5.1.post22 have `get_cc` but no `is_clang_cl`; importing them together+ lost `get_cc` and gated a TinyCC box that compiles fine (7 of the 14 real releases)."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [], cc = "tcc.exe", with_is_clang_cl = False)+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: True)+ monkeypatch.setattr(_msvc_env, "_triton_is_triton_windows", lambda: True)+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_clang_cl_is_still_gated_without_is_clang_cl(tmp_path, monkeypatch):+ """The other half: dropping the predicate must not drop the detection."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe", with_is_clang_cl = False)+ assert _msvc_env._needs_msvc_headers() is True+ assert _msvc_env.crt_headers_reachable() is False+++def test_a_raising_predicate_does_not_escape(tmp_path, monkeypatch):+ """`is_msvc(None)` is a TypeError. The call used to sit outside the try, so it escaped."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [], cc = "tcc.exe")+ build = sys.modules["triton.runtime.build"]++ def boom(_c):+ raise TypeError("expected str, bytes or os.PathLike object, not NoneType")++ monkeypatch.setattr(build, "is_msvc", boom)+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def _fake_triton_38(monkeypatch, inc_dirs, cc):+ """triton-windows 3.8.0.post28: `get_cc` is gone, `_find_compiler(language)` replaces it."""+ _fake_triton(monkeypatch, inc_dirs, cc = cc)+ build = sys.modules["triton.runtime.build"]+ monkeypatch.delattr(build, "get_cc")+ build._find_compiler = lambda language: cc+ return build+++def test_the_get_cc_rename_is_followed(tmp_path, monkeypatch):+ """3.8.0.post28, what a bare `pip install triton-windows` gives you, has no `get_cc`: the+ wheel-layout guess answers from what is installed, not from what Triton will run."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton_38(monkeypatch, [], cc = "tcc.exe")+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: True)+ monkeypatch.setattr(_msvc_env, "_triton_is_triton_windows", lambda: True)+ assert _msvc_env._triton_cc() == "tcc.exe"+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_the_get_cc_rename_still_gates_clang_cl(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton_38(monkeypatch, [], cc = "clang-cl.exe")+ assert _msvc_env._needs_msvc_headers() is True+ assert _msvc_env.crt_headers_reachable() is False+++def test_neither_compiler_name_present_falls_back(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe")+ build = sys.modules["triton.runtime.build"]+ monkeypatch.delattr(build, "get_cc")+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: False)+ assert _msvc_env._needs_msvc_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_triton_is_triton_windows_reads_the_distribution_name(monkeypatch):+ import importlib.metadata as md++ monkeypatch.setattr(md, "packages_distributions", lambda: {"triton": ["triton-windows"]})+ assert _msvc_env._triton_is_triton_windows() is True+ monkeypatch.setattr(md, "packages_distributions", lambda: {"triton": ["pytorch-triton-xpu"]})+ assert _msvc_env._triton_is_triton_windows() is False+ monkeypatch.setattr(md, "packages_distributions", lambda: {})+ assert _msvc_env._triton_is_triton_windows() is False++ def boom():+ raise RuntimeError("metadata is unreadable")++ monkeypatch.setattr(md, "packages_distributions", boom)+ assert _msvc_env._triton_is_triton_windows() is False+++def test_no_private_api_but_rocm_clang_cl_on_disk_is_gated(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ monkeypatch.setitem(sys.modules, "triton.runtime.build", None)+ monkeypatch.setattr(_msvc_env, "_rocm_clang_cl_present", lambda: True)+ monkeypatch.setattr(_msvc_env, "_triton_is_triton_windows", lambda: True)+ # Left real, this asks the runner's own Visual Studio and answers for the wrong machine.+ monkeypatch.setattr(_msvc_env, "_triton_include_dirs", lambda: [])+ assert _msvc_env._needs_msvc_headers() is True+ assert _msvc_env.crt_headers_reachable() is False+++def test_a_split_toolchain_is_judged_over_the_union(tmp_path, monkeypatch):+ """clang-cl reads INCLUDE as system include paths and Triton passes its dirs as /I, so the+ compile sees both. Judging each source alone gates a machine whose halves are split across+ them, which is the false positive that costs a user a working torch.compile."""+ monkeypatch.setattr(sys, "platform", "win32")+ vc = tmp_path / "vc"+ vc.mkdir()+ (vc / "vcruntime.h").write_text("/* stub */")+ ucrt = tmp_path / "ucrt"+ ucrt.mkdir()+ (ucrt / "stdlib.h").write_text("/* stub */")+ monkeypatch.setenv("INCLUDE", str(vc))+ _fake_triton(monkeypatch, [str(ucrt)])+ assert _msvc_env._have_crt_headers() is False+ assert _msvc_env._triton_finds_crt_headers() is False+ assert _msvc_env.crt_headers_reachable() is True+++def test_the_union_still_gates_when_neither_half_is_there(tmp_path, monkeypatch):+ """The other direction: a union that is still incomplete must gate, or #7595 is unprevented."""+ monkeypatch.setattr(sys, "platform", "win32")+ ucrt = tmp_path / "ucrt"+ ucrt.mkdir()+ (ucrt / "stdlib.h").write_text("/* stub */")+ monkeypatch.setenv("INCLUDE", str(tmp_path / "empty"))+ _fake_triton(monkeypatch, [str(ucrt)])+ assert _msvc_env.crt_headers_reachable() is False+++def test_a_compiler_that_actually_works_overrules_the_header_heuristic(tmp_path, monkeypatch):+ """The heuristic reads directories; clang-cl locates MSVC through its own search and can+ compile from an -internal-isystem we see no trace of (measured on an R9700 with INCLUDE,+ VCINSTALLDIR and WindowsSdkDir cleared). So a compile that succeeds has to win, or a+ working machine loses torch.compile on the strength of a guess."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [str(tmp_path)])+ monkeypatch.setattr(_msvc_env, "_compiles_a_trivial_translation_unit", lambda cc, d: True)+ assert _msvc_env.crt_headers_reachable() is True+++def test_a_compiler_that_fails_still_gates(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [str(tmp_path)])+ monkeypatch.setattr(_msvc_env, "_compiles_a_trivial_translation_unit", lambda cc, d: False)+ assert _msvc_env.crt_headers_reachable() is False+++def test_an_unrunnable_probe_keeps_the_header_verdict(tmp_path, monkeypatch):+ """A probe that cannot run says nothing, and #7595 is exactly the case where it might not+ run. Treating unknown as permission would trade a measured protection for an absent one."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, [str(tmp_path)])+ monkeypatch.setattr(_msvc_env, "_compiles_a_trivial_translation_unit", lambda cc, d: None)+ assert _msvc_env.crt_headers_reachable() is False+++def test_marker_positive_dirs_are_still_probed(tmp_path, monkeypatch):+ """stdlib.h and vcruntime.h are entry points, not the whole toolchain: vcruntime.h includes+ sal.h, which lives in the SDK's `shared` directory rather than beside either marker, so a+ mismatched SDK can carry both markers and still fail to compile. The markers must not+ short-circuit the compiler."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ dirs = _sdk_dirs(tmp_path, with_toolset = True)+ _fake_triton(monkeypatch, dirs)+ monkeypatch.setattr(_msvc_env, "_compiles_a_trivial_translation_unit", lambda cc, d: False)+ # The heuristic would say yes; the compiler says no, and the compiler wins.+ assert _msvc_env._headers_complete(dirs) is True+ assert _msvc_env.crt_headers_reachable() is False+++def test_marker_positive_dirs_survive_an_unrunnable_probe(tmp_path, monkeypatch):+ """The fallback still has to exist: a host where the compiler cannot be run keeps the+ header verdict, so a complete-looking toolchain is not gated on an absent measurement."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = True))+ monkeypatch.setattr(_msvc_env, "_compiles_a_trivial_translation_unit", lambda cc, d: None)+ assert _msvc_env.crt_headers_reachable() is True+++def test_the_probe_really_compiles_and_really_reports_failure(tmp_path):+ """The probe itself, against a real compiler on whatever platform runs this. cc accepts the+ MSVC-style flags clang and clang-cl do; if none is installed the probe must say None, never+ guess. Left as a live check because a probe that silently stopped compiling would report+ False on every host and disable torch.compile everywhere."""+ import shutil++ cc = shutil.which("clang-cl") or shutil.which("clang") or shutil.which("cc")+ if cc is None:+ assert _msvc_env._compiles_a_trivial_translation_unit("no-such-compiler", []) is None+ return+ flag_style_ok = _msvc_env._compiles_a_trivial_translation_unit(cc, [])+ # A cc that rejects /Zs answers False rather than crashing, which is the contract that+ # matters here; on a real clang-cl it answers True.+ assert flag_style_ok in (True, False)+ assert _msvc_env._compiles_a_trivial_translation_unit("no-such-compiler", []) is None+++def test_rocm_clang_cl_present_probes_the_platlib_path(tmp_path, monkeypatch):+ import sysconfig++ monkeypatch.setattr(sysconfig, "get_path", lambda name: str(tmp_path))+ assert _msvc_env._rocm_clang_cl_present() is False+ exe = tmp_path / "_rocm_sdk_core" / "lib" / "llvm" / "bin"+ exe.mkdir(parents = True)+ (exe / "clang-cl.exe").write_text("")+ assert _msvc_env._rocm_clang_cl_present() is True+++def test_toolchain_summary_separates_no_vs_from_a_partial_sdk(tmp_path, monkeypatch):+ _fake_triton(monkeypatch, [], cc = "clang-cl.exe")+ monkeypatch.delenv("INCLUDE", raising = False)+ summary = _msvc_env._toolchain_summary()+ assert "compiler=clang-cl.exe" in summary+ assert "include dirs=0" in summary+ assert "missing headers=stdlib.h,vcruntime.h" in summary+ assert "INCLUDE=unset" in summary++ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = False), cc = "clang-cl.exe")+ monkeypatch.setenv("INCLUDE", str(tmp_path))+ summary = _msvc_env._toolchain_summary()+ assert "include dirs=2" in summary+ assert "missing headers=vcruntime.h" in summary+ assert "INCLUDE=set" in summary+++def test_toolchain_summary_never_raises(monkeypatch):+ monkeypatch.setitem(sys.modules, "triton.runtime.build", None)+ monkeypatch.setitem(sys.modules, "triton.windows_utils", None)+ assert "compiler=unknown" in _msvc_env._toolchain_summary()+++def test_gate_survives_a_probe_that_raises(monkeypatch):+ """This gate exists to stop a crash at worker startup; it must not become one."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("TORCHDYNAMO_DISABLE", "")+ monkeypatch.delenv("TORCHDYNAMO_DISABLE")+ monkeypatch.setitem(sys.modules, "triton", types.ModuleType("triton"))++ def boom():+ raise RuntimeError("sysconfig has no platlib on this scheme")++ monkeypatch.setattr(_msvc_env, "crt_headers_reachable", boom)+ _msvc_env.gate_torch_compile_on_windows(logging.getLogger("test_gate_7595"))+ assert "TORCHDYNAMO_DISABLE" not in os.environ+++def _gate(monkeypatch, *, triton_importable, headers_ok):+ monkeypatch.setattr(sys, "platform", "win32")+ # setenv first: delenv(raising = False) records nothing when absent, so the gate's write leaks.+ monkeypatch.setenv("TORCHDYNAMO_DISABLE", "")+ monkeypatch.delenv("TORCHDYNAMO_DISABLE")+ # A None entry in sys.modules makes `import triton` raise ImportError.+ monkeypatch.setitem(+ sys.modules, "triton", types.ModuleType("triton") if triton_importable else None+ )+ monkeypatch.setattr(_msvc_env, "crt_headers_reachable", lambda: headers_ok)+ records = []+ logger = logging.getLogger("test_gate_7595")+ monkeypatch.setattr(logger, "warning", lambda msg, *a: records.append(("warning", msg)))+ monkeypatch.setattr(logger, "info", lambda msg, *a: records.append(("info", msg)))+ _msvc_env.gate_torch_compile_on_windows(logger)+ return records+++def test_gate_is_noop_off_win32(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setenv("TORCHDYNAMO_DISABLE", "")+ monkeypatch.delenv("TORCHDYNAMO_DISABLE")+ monkeypatch.setattr(+ _msvc_env,+ "crt_headers_reachable",+ lambda: (_ for _ in ()).throw(AssertionError("gate ran off win32")),+ )+ _msvc_env.gate_torch_compile_on_windows(logging.getLogger("test_gate_7595"))+ assert "TORCHDYNAMO_DISABLE" not in os.environ+++def test_gate_disables_when_triton_missing(monkeypatch):+ records = _gate(monkeypatch, triton_importable = False, headers_ok = True)+ assert os.environ["TORCHDYNAMO_DISABLE"] == "1"+ assert any("Triton not found" in msg for _, msg in records)+++def test_gate_disables_when_headers_unreachable(monkeypatch):+ records = _gate(monkeypatch, triton_importable = True, headers_ok = False)+ assert os.environ["TORCHDYNAMO_DISABLE"] == "1"+ assert any("'stdlib.h'" in msg for _, msg in records)+++def test_gate_enables_when_triton_and_headers_present(monkeypatch):+ records = _gate(monkeypatch, triton_importable = True, headers_ok = True)+ assert "TORCHDYNAMO_DISABLE" not in os.environ+ assert records == [("info", "Triton available — torch.compile enabled")]+++def test_gate_does_not_disable_where_triton_already_compiles(monkeypatch, tmp_path):+ """Visual Studio installed, INCLUDE unset: judging on INCLUDE alone would gate a working box."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("TORCHDYNAMO_DISABLE", "")+ monkeypatch.delenv("TORCHDYNAMO_DISABLE")+ monkeypatch.delenv("INCLUDE", raising = False)+ _fake_triton(monkeypatch, _sdk_dirs(tmp_path, with_toolset = True))++ _msvc_env.gate_torch_compile_on_windows(logging.getLogger("test_gate_7595"))+ assert "TORCHDYNAMO_DISABLE" not in os.environ