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.

Studio: fix torch.compile for image generation on AMD (training config leak, Windows without Visual Studio, max tier) (#13227)

Daniel Han0acf8b171731
diff --git a/studio/backend/core/_msvc_env.py b/studio/backend/core/_msvc_env.py
index a7044b04a4d..eaa538855eb 100644
--- a/studio/backend/core/_msvc_env.py
+++ b/studio/backend/core/_msvc_env.py
@@ -161,7 +161,63 @@ def _compiles_a_trivial_translation_unit(cc: str, inc_dirs) -> bool | None:
return done.returncode == 0
+def _bundled_tcc() -> str | None:
+ import sysconfig # noqa: PLC0415
+ path = os.path.join(sysconfig.get_path("platlib"), "triton", "runtime", "tcc", "tcc.exe")
+ return path if os.path.isfile(path) else None
+
+
+def _clear_compiler_cache() -> None:
+ """`_find_compiler` is lru_cached in triton-windows 3.8, so a CC set after its first call is otherwise ignored."""
+ try:
+ from triton.runtime import build # noqa: PLC0415
+ except Exception: # noqa: BLE001
+ return
+ for name in ("_find_compiler", "get_cc"):
+ clear = getattr(getattr(build, name, None), "cache_clear", None)
+ if callable(clear):
+ clear()
+
+
+def _triton_driver_builds() -> bool:
+ """Creating the active driver compiles its C helper (`hip_utils.c` on AMD) with the selected compiler."""
+ try:
+ _clear_compiler_cache()
+ from triton.runtime import driver # noqa: PLC0415
+
+ driver.active.get_current_target()
+ return True
+ except Exception: # noqa: BLE001
+ logger.debug("Triton's driver did not build with the bundled TinyCC", exc_info = True)
+ return False
+
+
+def _switch_to_bundled_tcc() -> bool:
+ """clang-cl without the CRT headers (#9897): build with the TinyCC triton-windows bundles, which carries its own
+ and is what it already picks when no ROCm wheel is installed. Kept only if Triton's driver then builds; an
+ explicit CC is the user's choice."""
+ if os.environ.get("CC"):
+ return False
+ tcc = _bundled_tcc()
+ if tcc is None:
+ return False
+ os.environ["CC"] = tcc
+ if _triton_driver_builds():
+ logger.info(
+ "Triton's C toolchain has no CRT headers; building with its bundled TinyCC (%s)", tcc
+ )
+ return True
+ os.environ.pop("CC", None)
+ _clear_compiler_cache()
+ return False
+
+
def crt_headers_reachable() -> bool:
+ """Whether Triton's JIT can build its C helpers here, switching to the bundled TinyCC when clang-cl cannot."""
+ return _crt_headers_reachable() or _switch_to_bundled_tcc()
+
+
+def _crt_headers_reachable() -> bool:
if sys.platform != "win32":
return True
if not _needs_msvc_headers():
diff --git a/studio/backend/core/inference/diffusion_gguf_compile.py b/studio/backend/core/inference/diffusion_gguf_compile.py
index 893a7e5b360..3eda3c1b8a8 100644
--- a/studio/backend/core/inference/diffusion_gguf_compile.py
+++ b/studio/backend/core/inference/diffusion_gguf_compile.py
@@ -14,8 +14,8 @@ dequant inputs are the fixed-shape WEIGHT tensors, so it compiles once and never
resolution change. ``forward_native`` resolves the function as a module global, so replacing the
module attribute reroutes every linear.
-The ``default`` tier's lever (block stays eager). NOT used under ``max``: there the block compiles
-as one graph that fuses the dequant inline, and a separate compiled dequant would break that graph.
+The ``default`` tier's lever (block stays eager), and ``max``'s where the block cannot compile (ROCm). NOT used
+when ``max`` compiles the block: that graph fuses the dequant inline, and a separate compiled dequant would break it.
The swap goes through the shared reversible patch backend; ``uninstall_*`` restores the exact
original so a later bit-identical ``off`` load runs stock dequant. Kill-switch:
@@ -27,6 +27,7 @@ already serves the per-forward cast from its pool. See outputs/arch_patch/SUMMAR
from __future__ import annotations
+import functools
import os
from typing import Any
@@ -52,6 +53,7 @@ def _gguf_utils():
_compiled_dequant_installed = False
+_compile_error: str | None = None
_DEQUANT_ATTR = "dequantize_gguf_tensor"
@@ -59,10 +61,15 @@ def is_compiled_dequant_installed() -> bool:
return _compiled_dequant_installed
+def compile_error() -> str | None:
+ """Why the installed compiled dequant now runs eager, or None while it still compiles."""
+ return _compile_error if _compiled_dequant_installed else None
+
+
def install_compiled_dequant(logger: Any = None) -> bool:
"""Replace ``dequantize_gguf_tensor`` with ``torch.compile(orig, dynamic=True)`` via the patch
backend. Idempotent. Returns True if the compiled dequant is in place, False otherwise."""
- global _compiled_dequant_installed
+ global _compiled_dequant_installed, _compile_error
if not _enabled(_ENV_COMPILE_DEQUANT):
return False
if _compiled_dequant_installed:
@@ -73,11 +80,13 @@ def install_compiled_dequant(logger: Any = None) -> bool:
try:
import torch # noqa: PLC0415
- compiled = torch.compile(gguf_utils.dequantize_gguf_tensor, dynamic = True)
+ eager = gguf_utils.dequantize_gguf_tensor
+ compiled = _guard(torch.compile(eager, dynamic = True), eager, logger)
# force=True: the compiled callable's fingerprint differs from the original, which can_safely_patch would
# correctly reject.
if apply_patch(gguf_utils, _DEQUANT_ATTR, compiled, force = True):
_compiled_dequant_installed = True
+ _compile_error = None
return True
return False
except Exception as exc: # noqa: BLE001 - optimisation only
@@ -86,6 +95,38 @@ def install_compiled_dequant(logger: Any = None) -> bool:
return False
+def _guard(compiled: Any, eager: Any, logger: Any) -> Any:
+ """``compiled`` behind an eager fallback, like the block and VAE decode compiles: a lazy compile that fails on
+ the first generation (#9897, Triton could not build its driver) ran nothing, so the stock dequant answers."""
+ failed: list = []
+
+ from . import diffusion_compile_config # noqa: PLC0415
+
+ @functools.wraps(eager)
+ def guarded(*args: Any, **kwargs: Any) -> Any:
+ if not failed:
+ # The lazy compile runs in the caller's context; on torch 2.12+ the load's knob writes may not be visible.
+ diffusion_compile_config.apply()
+ try:
+ return compiled(*args, **kwargs)
+ except Exception as exc: # noqa: BLE001 - reraised unless a compile-time failure
+ from .diffusion_speed import is_compile_failure # noqa: PLC0415 - diffusion_speed imports this
+
+ if not is_compile_failure(exc):
+ raise
+ global _compile_error
+ failed.append(type(exc).__name__)
+ _compile_error = (
+ f"{type(exc).__name__}: {str(exc).splitlines()[0] if str(exc) else ''}"[:300]
+ )
+ # The handled exception pins inductor's frames through the eager retry.
+ exc.__traceback__ = None
+ _warn(logger, "compiled dequant (running eager)", exc)
+ return eager(*args, **kwargs)
+
+ return guarded
+
+
def uninstall_compiled_dequant() -> None:
"""Restore the original ``dequantize_gguf_tensor``. Idempotent."""
global _compiled_dequant_installed
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 31795fe672e..1aa50b11eb6 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -62,8 +62,10 @@ _INDUCTOR_FLAGS = (
("force_fuse_int_mm_with_mul", "inductor_force_fuse_int_mm_with_mul"),
("fx_graph_cache", "inductor_fx_graph_cache"),
("dynamic_scale_rblock", "inductor_dynamic_scale_rblock"),
+ ("memory_planning", "inductor_memory_planning"),
)
_INDUCTOR_TRITON_FLAGS = (("unique_kernel_names", "inductor_triton_unique_kernel_names"),)
+_DYNAMO_FLAGS = (("suppress_errors", "dynamo_suppress_errors"),)
_DYNAMO_MODULE = "torch._dynamo.config"
REDUCTION_FILTER_OPTION = "test_configs.force_filter_reduction_configs"
_INDUCTOR_MODULE = "torch._inductor.config"
@@ -190,6 +192,11 @@ def snapshot_backend_flags() -> Optional[dict]:
for attr, key in _INDUCTOR_TRITON_FLAGS:
if hasattr(triton_cfg, attr):
state[key] = bool(compile_config.get_knob(_INDUCTOR_TRITON_MODULE, attr))
+ dynamo_cfg = _dynamo_config()
+ if dynamo_cfg is not None:
+ for attr, key in _DYNAMO_FLAGS:
+ if hasattr(dynamo_cfg, attr):
+ state[key] = bool(compile_config.get_knob(_DYNAMO_MODULE, attr))
getter = getattr(torch, "get_float32_matmul_precision", None)
if callable(getter):
try:
@@ -254,6 +261,35 @@ def restore_backend_flags(state: Optional[dict]) -> None:
triton_cfg = getattr(inductor_cfg, "triton", None) if inductor_cfg is not None else None
for attr, key in _INDUCTOR_TRITON_FLAGS:
_set_knob(triton_cfg, _INDUCTOR_TRITON_MODULE, attr, key)
+ dynamo_cfg = _dynamo_config()
+ for attr, key in _DYNAMO_FLAGS:
+ _set_knob(dynamo_cfg, _DYNAMO_MODULE, attr, key)
+
+
+def _gguf_dequant_compilable(is_gguf: bool, on_cuda: bool, family_allows_compile: bool) -> bool:
+ return is_gguf and on_cuda and family_allows_compile and torch_compile_runtime_available()
+
+
+def _pin_compile_defaults() -> None:
+ """torch's defaults for every diffusion compile, against Unsloth's training config, which sets both process-wide
+ on torch < 2.12 (#9897). ``memory_planning``: its pooled buffers come back from ``inductor::_alloc_from_pool`` as
+ views AOTAutograd's custom-op aliasing check rejects at the first call (every gfx1151 render under ``CI``, a
+ deprecation warning elsewhere). ``suppress_errors``: a failed compile would silently run eager; Studio's own
+ guards fall back with a warning instead, as on torch 2.12+ where the render thread never saw the training config."""
+ inductor_cfg = _inductor_config()
+ if inductor_cfg is not None and hasattr(inductor_cfg, "memory_planning"):
+ compile_config.set_knob(_INDUCTOR_MODULE, "memory_planning", False)
+ dynamo_cfg = _dynamo_config()
+ if dynamo_cfg is not None and hasattr(dynamo_cfg, "suppress_errors"):
+ compile_config.set_knob(_DYNAMO_MODULE, "suppress_errors", False)
+
+
+def _dynamo_config() -> Any:
+ try:
+ import torch
+ return getattr(getattr(torch, "_dynamo", None), "config", None)
+ except Exception: # noqa: BLE001 - no dynamo -> nothing to snapshot/set
+ return None
def _inductor_config() -> Any:
@@ -471,6 +507,8 @@ def apply_speed_optims(
# `off` load never inherits them.
if mode == SPEED_OFF:
return applied
+ if mode in (SPEED_DEFAULT, SPEED_MAX):
+ _pin_compile_defaults()
if getattr(target, "backend", None) == "rocm":
try:
@@ -510,7 +548,7 @@ def apply_speed_optims(
# of the repeated block. eager = no compile.
if mode == SPEED_DEFAULT:
# 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():
+ if _gguf_dequant_compilable(is_gguf, on_cuda, family_allows_compile):
applied["compiled_dequant"] = gguf_compile.install_compiled_dequant(logger)
elif compile_eligible(target, is_gguf = is_gguf, family = family) and not fp16_unet_offloaded(
target, pipe, offload_active = offload_active
@@ -529,21 +567,25 @@ def apply_speed_optims(
onload_device = _onload_device(target) if stream_int8_gemm else None,
filter_reductions = filter_reductions,
)
- elif (
- mode == SPEED_MAX
- and compile_eligible(target, is_gguf = is_gguf, family = family)
- and not fp16_unet_offloaded(target, pipe, offload_active = offload_active)
- ):
- applied["compiled"] = _compile_repeated_blocks(
- pipe,
- logger,
- max_autotune = True,
- cache_active = cache_active,
- offload_active = offload_active,
- denoiser_offloaded = denoiser_offloaded,
- onload_device = _onload_device(target) if stream_int8_gemm else None,
- filter_reductions = filter_reductions,
- )
+ elif mode == SPEED_MAX:
+ if compile_eligible(target, is_gguf = is_gguf, family = family) and not fp16_unet_offloaded(
+ target, pipe, offload_active = offload_active
+ ):
+ applied["compiled"] = _compile_repeated_blocks(
+ pipe,
+ logger,
+ max_autotune = True,
+ cache_active = cache_active,
+ offload_active = offload_active,
+ denoiser_offloaded = denoiser_offloaded,
+ onload_device = _onload_device(target) if stream_int8_gemm else None,
+ filter_reductions = filter_reductions,
+ )
+ if not applied["compiled"] and _gguf_dequant_compilable(
+ is_gguf, on_cuda, family_allows_compile
+ ):
+ # No block compile (ROCm, or its setup failed): keep default's dequant compile rather than run slower.
+ applied["compiled_dequant"] = gguf_compile.install_compiled_dequant(logger)
if applied["compiled"]:
applied["int8_gemm"] = any(
@@ -1418,7 +1460,8 @@ def settle_compile_fallback(
the recorded failure, or None when nothing fell back."""
dit_error = compile_fallback_error(pipe)
vae_error = _vae_compile_error(getattr(pipe, "vae", None))
- fallback = dit_error or vae_error
+ dequant_error = gguf_compile.compile_error()
+ fallback = dit_error or vae_error or dequant_error
if not fallback:
return None
optims = tuple(getattr(state, "speed_optims", None) or ())
@@ -1431,6 +1474,8 @@ def settle_compile_fallback(
updated.remove("compiled")
if vae_error and "compiled_vae_decode" in updated:
updated.remove("compiled_vae_decode")
+ if dequant_error and "compiled_dequant" in updated:
+ updated.remove("compiled_dequant")
if tuple(updated) != optims:
# The load states are frozen dataclasses; the status must still reflect what actually runs.
object.__setattr__(state, "speed_optims", tuple(updated))
diff --git a/studio/backend/tests/test_diffusion_gguf_compile.py b/studio/backend/tests/test_diffusion_gguf_compile.py
index b0699643519..69e75aaf73d 100644
--- a/studio/backend/tests/test_diffusion_gguf_compile.py
+++ b/studio/backend/tests/test_diffusion_gguf_compile.py
@@ -74,6 +74,94 @@ def test_uninstall_all(monkeypatch):
assert gguf_utils.dequantize_gguf_tensor is orig
+def _inductor_error():
+ from torch._inductor.exc import InductorError
+
+ # What #9897 raised: Triton's driver build (clang-cl on hip_utils.c) failed inside inductor's codegen.
+ import subprocess
+ return InductorError(subprocess.CalledProcessError(1, ["clang-cl.exe", "hip_utils.c"]), None)
+
+
+def test_compile_failure_falls_back_to_eager():
+ calls: list = []
+
+ def compiled(t):
+ calls.append("compiled")
+ raise _inductor_error()
+
+ def eager(t):
+ calls.append("eager")
+ return t * 2
+
+ guarded = gc._guard(compiled, eager, logging.getLogger("t"))
+ x = torch.ones(3)
+ assert torch.equal(guarded(x), x * 2)
+ assert gc._compile_error.startswith("InductorError")
+ assert torch.equal(guarded(x), x * 2)
+ assert calls == ["compiled", "eager", "eager"]
+
+
+def test_the_lazy_compile_sees_the_recorded_compile_config():
+ import threading
+
+ from core.inference import diffusion_compile_config as cc
+
+ cc._reset_for_tests()
+ seen = {}
+
+ def compiled(t):
+ seen["memory_planning"] = torch._inductor.config.memory_planning
+ return t
+
+ try:
+ assert cc.set_knob("torch._inductor.config", "memory_planning", False)
+ guarded = gc._guard(compiled, lambda t: t, None)
+
+ def render():
+ # A render context still carrying the training config (torch 2.12+ keeps config writes per context).
+ torch._inductor.config.memory_planning = True
+ guarded(torch.ones(1))
+
+ worker = threading.Thread(target = render)
+ worker.start()
+ worker.join()
+ assert seen["memory_planning"] is False
+ finally:
+ cc._reset_for_tests()
+
+
+ "exc",
+ [RuntimeError("bad weight"), torch.OutOfMemoryError("CUDA out of memory")],
+ ids = ["kernel_error", "oom"],
+)
+def test_non_compile_errors_still_raise(exc):
+ def compiled(t):
+ raise exc
+
+ guarded = gc._guard(compiled, lambda t: t, None)
+ with pytest.raises(type(exc)):
+ guarded(torch.ones(1))
+
+
+def test_installed_dequant_survives_a_failing_compile(monkeypatch):
+ def failing_compile(fn, **kwargs):
+ def compiled(*a, **k):
+ raise _inductor_error()
+
+ return compiled
+
+ monkeypatch.setattr(torch, "compile", failing_compile)
+ orig = gguf_utils.dequantize_gguf_tensor
+ assert gc.install_compiled_dequant() is True
+ plain = torch.arange(4, dtype = torch.float32)
+ # A non-GGUF tensor goes through the stock function unchanged, so this compares to the original exactly.
+ assert torch.equal(gguf_utils.dequantize_gguf_tensor(plain), orig(plain))
+ assert gc.compile_error().startswith("InductorError")
+ gc.uninstall_all()
+ assert gc.compile_error() is None
+
+
class TestGgufTrimmedDimsAreRestored:
"""GGUF stores no leading size-1 axes, so ``nn.Parameter(torch.zeros((1, dim)))`` comes back as
``(dim,)`` and diffusers' exact shape check refuses the load. Z-Image is the live case: a GGUF
diff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.py
index ab05869541a..8705a25fddb 100644
--- a/studio/backend/tests/test_diffusion_speed.py
+++ b/studio/backend/tests/test_diffusion_speed.py
@@ -535,6 +535,31 @@ def test_speed_max_gguf_regional_compile_not_dequant(monkeypatch):
assert called == {"compiled_dequant": 0}
+def test_speed_max_gguf_without_block_compile_keeps_dequant_compile(monkeypatch):
+ # ROCm targets never regionally compile, so max used to run the GGUF dequant eager: slower than default on gfx1151
+ # (3.83 vs 2.98 s per 512 px FLUX.2-klein Q2_K render).
+ _stub_torch(monkeypatch)
+ called = _stub_gguf_accel(monkeypatch)
+ pipe = _Pipe(with_compile = True, with_fuse = True)
+ applied = apply_speed_optims(
+ pipe, _target(compile_ok = False), is_gguf = True, family = _family(), speed_mode = SPEED_MAX
+ )
+ assert applied["compiled"] is False and pipe.compiled is False
+ assert applied["compiled_dequant"] is True
+ assert called == {"compiled_dequant": 1}
+
+
+def test_speed_max_gguf_whose_block_compile_fails_keeps_dequant_compile(monkeypatch):
+ _stub_torch(monkeypatch)
+ called = _stub_gguf_accel(monkeypatch)
+ monkeypatch.setattr(ds_mod, "_compile_repeated_blocks", lambda *a, **k: False)
+ applied = apply_speed_optims(
+ _Pipe(with_compile = True), _target(), is_gguf = True, family = _family(), speed_mode = SPEED_MAX
+ )
+ assert applied["compiled"] is False and applied["compiled_dequant"] is True
+ assert called == {"compiled_dequant": 1}
+
+
def test_speed_default_cudnn_benchmark_only_on_cuda(monkeypatch):
_stub_torch(monkeypatch)
pipe = _Pipe(with_compile = True)
@@ -1234,6 +1259,53 @@ def test_snapshot_restores_emulate_precision_casts(monkeypatch):
assert cfg.emulate_precision_casts is False
+def _stub_training_config(torch):
+ """Unsloth's training config as torch < 2.12 leaves it process-wide: memory planning on, compile errors suppressed."""
+ inductor = types.SimpleNamespace(memory_planning = True, emulate_precision_casts = False)
+ dynamo = types.SimpleNamespace(suppress_errors = True)
+ torch._inductor = types.SimpleNamespace(config = inductor)
+ torch._dynamo = types.SimpleNamespace(config = dynamo)
+ return inductor, dynamo
+
+
[email protected]("is_gguf", [True, False], ids = ["gguf_dequant", "regional"])
+def test_compile_runs_with_torch_defaults_not_the_training_config(monkeypatch, is_gguf):
+ # #9897: memory planning's inductor::_alloc_from_pool views fail AOTAutograd's aliasing check at the first render,
+ # and suppress_errors hid every failed compile as a silent eager run.
+ torch = _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ inductor, dynamo = _stub_training_config(torch)
+ apply_speed_optims(
+ _Pipe(with_compile = True),
+ _target(),
+ is_gguf = is_gguf,
+ family = _family(),
+ speed_mode = SPEED_DEFAULT,
+ )
+ assert inductor.memory_planning is False
+ assert dynamo.suppress_errors is False
+
+
[email protected]("mode", [SPEED_OFF, SPEED_EAGER])
+def test_non_compiling_tiers_leave_the_compile_config_alone(monkeypatch, mode):
+ torch = _stub_torch(monkeypatch)
+ inductor, dynamo = _stub_training_config(torch)
+ apply_speed_optims(
+ _Pipe(with_compile = True), _target(), is_gguf = True, family = _family(), speed_mode = mode
+ )
+ assert inductor.memory_planning is True and dynamo.suppress_errors is True
+
+
+def test_snapshot_restores_the_compile_config(monkeypatch):
+ torch = _stub_torch(monkeypatch)
+ inductor, dynamo = _stub_training_config(torch)
+ snap = snapshot_backend_flags()
+ inductor.memory_planning = False
+ dynamo.suppress_errors = False
+ restore_backend_flags(snap)
+ assert inductor.memory_planning is True and dynamo.suppress_errors is True
+
+
def test_missing_inductor_config_is_tolerated(monkeypatch):
# A build without torch._inductor (or with the flag renamed) must break neither the snapshot nor the compile path.
_stub_torch(monkeypatch) # the stub torch has no _inductor attribute
@@ -1940,6 +2012,14 @@ def test_settle_fallback_keeps_compiled_while_another_dit_still_compiles(monkeyp
assert state.speed_optims == ("cuda_graph", "compile_fallback_eager")
+def test_settle_fallback_drops_a_dequant_compile_that_fell_back(monkeypatch):
+ monkeypatch.setattr(ds_mod.gguf_compile, "compile_error", lambda: "InductorError: hip_utils.c")
+ pipe = types.SimpleNamespace(transformer = _Dit([_Block(lambda x: x)]))
+ state = types.SimpleNamespace(speed_optims = ("compiled_dequant", "cudnn_benchmark"))
+ assert "hip_utils" in ds_mod.settle_compile_fallback(state, pipe)
+ assert state.speed_optims == ("cudnn_benchmark", "compile_fallback_eager")
+
+
def test_settle_fallback_sees_a_modular_workflows_named_partition(monkeypatch):
# MiniMax-H3's reference workflow compiles transformer_ref through a view; settlement runs on the bare pipe.
_stub_torch_compile_errors(monkeypatch)
diff --git a/studio/backend/tests/test_msvc_env_7595.py b/studio/backend/tests/test_msvc_env_7595.py
index 0be1f3f6e93..9a0f4d189cc 100644
--- a/studio/backend/tests/test_msvc_env_7595.py
+++ b/studio/backend/tests/test_msvc_env_7595.py
@@ -542,3 +542,38 @@ def test_gate_does_not_disable_where_triton_already_compiles(monkeypatch, tmp_pa
_msvc_env.gate_torch_compile_on_windows(logging.getLogger("test_gate_7595"))
assert "TORCHDYNAMO_DISABLE" not in os.environ
+
+
+def _no_headers(monkeypatch, tcc, builds):
+ monkeypatch.setattr(_msvc_env, "_crt_headers_reachable", lambda: False)
+ monkeypatch.setattr(_msvc_env, "_bundled_tcc", lambda: tcc)
+ monkeypatch.setattr(_msvc_env, "_triton_driver_builds", lambda: builds)
+ # setenv first so teardown removes a CC the code under test writes straight into os.environ.
+ monkeypatch.setenv("CC", "")
+ monkeypatch.delenv("CC")
+
+
+def test_clang_cl_without_headers_switches_to_bundled_tinycc(monkeypatch):
+ # #9897: Windows ROCm without Visual Studio. TinyCC built hip_utils.c and every kernel launcher on gfx1151.
+ _no_headers(monkeypatch, r"C:\py\triton\runtime\tcc\tcc.exe", builds = True)
+ assert _msvc_env.crt_headers_reachable() is True
+ assert os.environ["CC"] == r"C:\py\triton\runtime\tcc\tcc.exe"
+
+
+def test_tinycc_that_cannot_build_the_driver_still_gates(monkeypatch):
+ _no_headers(monkeypatch, r"C:\py\triton\runtime\tcc\tcc.exe", builds = False)
+ assert _msvc_env.crt_headers_reachable() is False
+ assert "CC" not in os.environ
+
+
+def test_no_bundled_tinycc_still_gates(monkeypatch):
+ _no_headers(monkeypatch, None, builds = True)
+ assert _msvc_env.crt_headers_reachable() is False
+ assert "CC" not in os.environ
+
+
+def test_an_explicit_cc_is_never_replaced(monkeypatch):
+ _no_headers(monkeypatch, r"C:\py\triton\runtime\tcc\tcc.exe", builds = True)
+ monkeypatch.setenv("CC", r"C:\llvm\bin\clang-cl.exe")
+ assert _msvc_env.crt_headers_reachable() is False
+ assert os.environ["CC"] == r"C:\llvm\bin\clang-cl.exe"