Repository navigation
fix(amd): don't enable torch.compile when Triton's C toolchain can't compile it (Windows) - #7704
Conversation
…dows AMD (unslothai#7595) Triton imports fine on AMD but its HIP driver JIT-compiles hip_utils.c with clang-cl on first GPU touch, which needs the MSVC CRT headers via INCLUDE. Worker subprocesses don't inherit a Developer-Prompt env, so the first torch.compile dies on 'stdlib.h' not found. Establish the env in-process at the torch.compile gate via vswhere/vcvarsall, and disable torch.compile with a clear message when no MSVC toolchain is present instead of hard-crashing.
…or-triton-windows-amd
… one helper test_text_io_encoding rejects subprocess(text = True) without an explicit encoding, which failed Repo tests (CPU) on all four Python versions. Both calls now pass encoding = utf-8 with errors = replace, so a stray byte in cmd's `set` dump cannot take down the probe. The gate itself was pasted verbatim into three workers, and its `from core._msvc_env import ...` sat inside the `try: import triton` whose except ImportError reports 'Triton not found' -- an import failure there would have told the user to install triton. gate_torch_compile_on_windows() now owns both arms; each worker calls it once. Adds unit coverage for the three outcomes via a stubbed triton in sys.modules.
…or-triton-windows-amd
…king in tests _VS_YEAR_DIRS stopped at 2022, so a box with both VS 2019 and VS 2026 took the 2019 toolchain: the year loop returns before the glob fallback ever runs. Match setup.ps1's Find-VsBuildTools list (18/2026 first, plus the Preview edition). The gate tests called monkeypatch.delenv(TORCHDYNAMO_DISABLE, raising = False), which records nothing when the var is absent, so the gate's own write survived teardown and leaked into the rest of the pytest session. setenv first, then delenv, so the pre-state is recorded. Also note in the docstring why the env import is not conditional on the gate's verdict: unsloth's hand-written Triton kernels compile through the same clang-cl path, so they need INCLUDE even where training's section 1f disables dynamo.
…or-triton-windows-amd
The vcvarsall call passed its command as a list element, so list2cmdline escaped the quotes around the path and cmd got \"C:\Program Files...\" and reported "is not recognized as an internal or external command". Every real VS lives under a path with spaces, so the import failed on every machine: ensure_msvc_env_for_triton() always returned False and the gate reported "no MSVC toolchain was found" even where Build Tools was installed. The crash was replaced by a permanently wrong message, not fixed. Pass the command as a string with shell = True instead. Decode cmd/vswhere output as the console (OEM) codepage rather than UTF-8: errors="replace" was turning a non-ASCII path into U+FFFD, and since PATH is overwritten wholesale that silently corrupts it for the whole worker. Also surface vcvarsall's own failure output (no more >nul 2>&1) so the likely "VS present but no C++ workload" case has a reason in the log, and rank globbed candidates by _VS_YEAR_DIRS so VS 2026's "18" doesn't sort behind "2022". Tests cover _find_vcvarsall and _import_vcvars_env, which had none: the invocation form is asserted directly, and an end-to-end test runs the real vcvarsall when the machine has one (skipped otherwise).
…or-triton-windows-amd
…or-triton-windows-amd
…ver process The vcvarsall injection this PR started with does nothing. Measured on a Windows 11 ROCm 7.1 box with INCLUDE, LIB, LIBPATH, VCINSTALLDIR and WindowsSdkDir all cleared: triton/runtime/build.py:130 calls windows_utils.find_msvc_winsdk(), which reads VCINSTALLDIR, WindowsSdkDir, vswhere, PATH, the registry and Program Files but never INCLUDE, and it returned four include dirs regardless. clang-cl then found MSVC on its own, injecting -internal-isystem for the MSVC and ucrt dirs. Compile exit 0. Two discovery paths, neither reading INCLUDE. So importing vcvarsall is a no-op when Visual Studio is present, and when it is absent there is no vcvarsall to import. Taking the trim the description offered as the alternative: this is the graceful-disable half only, 213 lines to 130. crt_headers_reachable() asks Triton's own discovery, the same oracle the real compile uses, so it cannot disagree with what actually happens. INCLUDE stays as the fallback for Triton builds old enough to rely on it. It asks get_cc() first, because only cl.exe and clang-cl need those headers. Without the ROCm wheel get_cc() falls through to Triton's bundled TinyCC, which carries its own headers and is never passed an SDK /I. Gating that on MSVC would have disabled torch.compile on the ordinary Windows NVIDIA install, which compiles fine. Also closes the gap flagged on the thread, since a user hit it today. The workers are subprocesses; image and video generation run in the server process, which those gates never reach. An RX 9070 XT with no Visual Studio loaded Z-Image Q4 fine and died at step 0 of the first generation. torch_compile_runtime_available() was testing `import triton`, which succeeds there, and the GGUF arm at diffusion_speed.py:243 is an `if`, so it never reached the check inside compile_eligible(). Only the dense elif was protected, and GGUF is the one path that defaults compile on. Tests are platform-independent now: discovery and the compiler pick are stubbed through sys.modules, so they answer the same on a Linux runner and on a Windows box with or without VS. The old end-to-end test that ran the real vcvarsall goes with the code it tested. Each new test was mutation-checked. Not fixed, and the message no longer claims otherwise: disabling dynamo does not stop Unsloth's own @triton.jit kernels, which have no opt-out, so a train on a box with no MSVC still needs the toolchain.
|
Two things, and the first changes the PR. The root cause in my description was wrong for the Triton that ships. I said clang-cl finds the CRT headers through So the injection is a no-op when VS is present, and when it is absent there is no One thing that fell out of it: the gate has to ask The trim also let the tests stop depending on the machine. The old suite ran the real On the three checks you flagged: their logs have expired (HTTP 410, those runs are from 08-14), so I cannot show you they were unrelated, only re-run them. Current main is merged, 523 commits. Whatever is red after this push is a fair comparison. I also folded in the diffusion gap I flagged earlier, since a user hit it today: image and video generation run in the server process, which the worker gates never reach, and the GGUF arm at |
Codex P2, and it is right. setup.ps1:5334 swaps triton-windows for torch's pytorch-triton-xpu on Intel, and that owns the same top-level `triton` package without triton-windows' `runtime.build` helpers. The previous `except: return True` therefore read every Windows XPU install as needing MSVC, then `windows_utils` failed to import too and INCLUDE is normally unset, so every worker set TORCHDYNAMO_DISABLE=1. That undoes what the setup script installed the XPU Triton for, and it is a regression against main, where the gate was only `import triton`. Asking Triton is still exact, so that stays first. The fallback now checks for the one compiler this issue is about, the ROCm wheel's clang-cl at <platlib>/_rocm_sdk_core/lib/llvm/bin/clang-cl.exe, which get_cc() prefers over everything else. A path check cannot be fooled by a different Triton owning the package name, and it answers for builds that predate is_clang_cl. Also pins the toolchain probe in the new AMD-side test. Left real it asked the runner's own Visual Studio and answered for the wrong machine, which is how it passed here and would have flipped on a bare runner.
…OCm clang-cl Codex P2 on 1c14330, and it holds. A ROCm-to-XPU move under a pinned index is repaired in place (setup.ps1:4162, "reinstalling torch from the pin in place") and that path does not prune orphans, so `_rocm_sdk_core` can outlive the Triton that would have selected it. Keying the fallback on the file alone then reads a stale compiler as proof the active compiler is clang-cl, and disables torch.compile on an XPU box with no Visual Studio. The fallback now needs both halves: the compiler on disk, and the active `triton` coming from the triton-windows distribution, which is the only one whose build.py prefers that clang-cl. Resolved by distribution name via packages_distributions(), the same question setup.ps1 asks when it swaps triton-windows for pytorch-triton-xpu. Anything still unanswerable stays ungated, deliberately. Failing to gate costs the actionable message on a box that was already broken; gating wrongly breaks a box that works. Re-verified unstubbed on the R9700 / Windows 11 / ROCm 7.1 box after the change: needs_msvc_headers True, triton finds crt True, gate leaves TORCHDYNAMO_DISABLE unset.
…or-triton-windows-amd
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
clang-cl reads INCLUDE as system include paths while Triton passes its own discovered dirs as /I, so the compile sees both. Checking each source alone rejected a split toolchain, for example a VC toolset on INCLUDE beside an SDK that only Triton found, and disabled torch.compile on a machine that compiles. That is the false-positive direction, which is the only one this gate can get wrong at a user's expense. _triton_include_dirs now returns the dirs and _triton_finds_crt_headers wraps it, so an unaskable search still reads as unknown rather than as no headers. Two tests that patched the old seam are repointed at the new one; left as they were they would have stopped stubbing anything and asked the runner's own Visual Studio. Mutation-checked: judging Triton's dirs alone fails the split-toolchain test, and the companion test holds the gating direction when the union is incomplete.
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Security review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Header discovery is an inference, and it is wrong in the direction that costs a user something: 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 the directory heuristic sees no trace of. A host whose clang-cl finds a toolchain that Triton's discovery underreports was gated despite compiling fine. Before gating, compile a trivial translation unit with the compiler Triton will actually run, syntax-only (/Zs) so a missing lib path cannot look like a missing header. Success overrules every heuristic above it, since it is the same question the JIT asks minutes later. The probe can only ever rescue. It is consulted only after the header check has already failed, so a complete toolchain pays nothing, and an unrunnable probe keeps the header verdict rather than ungating -- unslothai#7595 is exactly the case where a probe might not run, and trading a measured protection for an absent one is the one outcome worse than a false positive. Mutation-checked both ways: removing the probe fails the rescue test, and treating an unrunnable probe as permission fails four gating tests.
The two marker files are entry points, not the toolchain. vcruntime.h includes sal.h, which lives in the Windows SDK's shared directory rather than beside either marker, and a mismatched SDK (ucrt from one version, shared from another) is a documented way to have both markers and still fail to compile. So the header check under-gates as well as over-gates, and neither direction is fixable by adding more filenames to look for. Run the probe first and return its verdict when it has one. The header checks stay, unchanged, as the fallback for a host where the compiler could not be run at all, since unknown is not evidence of a broken toolchain. Cost lands only where it is earned: the probe runs only when Triton will pick cl or clang-cl, so a TinyCC or non-Windows host never reaches it, and the one hot caller (torch_compile_runtime_available) is already lru_cached. Replaces the test asserting a complete-looking toolchain is NOT probed, which encoded the previous design. Its successor asserts the opposite and is mutation-checked: restoring the short-circuit fails it.
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |

Fixes #7595.
Problem
On Windows AMD, the first
torch.compiledies withfatal error: 'stdlib.h' file not found. Triton's AMD/HIP driver JIT-compileship_utils.con first GPU touch, and the compiler it picks is the ROCm wheel'sclang-cl(_rocm_sdk_core/lib/llvm/bin/clang-cl.exe). Without the CRT and Windows SDK headers that compile fails, and it fails at first GPU touch rather than at load, so it lands mid-training or mid-generation.Each worker gates
torch.compileonimport triton. That import succeeding does not mean a compile will.Why this PR changed shape
The original version imported a
vcvarsall.batenvironment into the worker, on the premise thatclang-clfinds the CRT headers throughINCLUDE. That premise is wrong for the Triton that ships. Measured on a Windows 11 ROCm 7.1 box withINCLUDE,LIB,LIBPATH,VCINSTALLDIRandWindowsSdkDirall cleared:triton/runtime/build.pycallswindows_utils.find_msvc_winsdk()and passes the result as/Iflags. That search readsVCINSTALLDIR,VCToolsVersion,WindowsSdkDir,WindowsSDKVersion, vswhere,PATH, the registry and the Program Files roots. It never readsINCLUDE(the string does not appear in the file). It returned four include dirs anyway.clang-clthen found MSVC independently, injecting...\VC\Tools\MSVC\14.44.35207\includeand...\Windows Kits\10\Include\10.0.26100.0\ucrtas-internal-isystem. Compile exit 0.So injecting
vcvarsallis a no-op when Visual Studio is present, and when it is absent there is novcvarsallto import. This PR is now the graceful-disable half only, which was the alternative raised as an open question._msvc_env.pydrops from 213 lines to 159.One correction to an earlier version of this description, which claimed "two independent discovery paths, neither consulting
INCLUDE". Only Triton's path ignoresINCLUDE.clang-clreads it first and exclusively and returns early when it finds anything there (clang/lib/Driver/ToolChains/MSVC.cpp,AddSystemIncludesFromEnv("INCLUDE")), skipping its own MSVC discovery entirely. The measurement above saw the fallback becauseINCLUDEhad been cleared. The conclusion is unchanged, and a partialINCLUDEactively suppressing clang-cl's auto-detection is a further argument against writing one.Fix
crt_headers_reachable()answers whether a Triton compile in this process will find its headers, by asking Triton's own discovery. That is the same oracle the real compile uses, so it cannot disagree with what actually happens.INCLUDEis kept as a positive signal only.It first asks which compiler Triton will pick, and whether that compiler even needs those headers. Only
cl.exeandclang-cldo. Without the ROCm wheel the pick falls through to Triton's bundled TinyCC, which carries its own headers and is never passed an SDK/I; gating a TinyCC box on MSVC would disabletorch.compileon an ordinary Windows NVIDIA install that compiles fine.gate_torch_compile_on_windows()folds this into the pre-existing "is Triton importable" gate in the three workers.Every call into Triton's private API fails open, so a Triton API move degrades to "do not gate" rather than breaking a working box. That direction is the whole risk here: this code can only ever disable
torch.compile, so the only way it can hurt anyone is a false positive.Private API drift, and what these names have actually done
All four are private and all four have moved. Read out of every published
triton-windowswin_amd64wheel:find_msvc_winsdkget_ccis_msvcis_clang_cl_find_compiler(language)Three consequences, each now handled and each covered by a test that fails when its fix is reverted:
_triton_finds_crt_headers()returnedFalsefor both. SinceINCLUDEis unset unless Studio was launched from a Developer Command Prompt, a rename, a raise or the 2-tuple return of3.2.0.post17would each have read as "no headers" and disabledtorch.compileon a Windows AMD box with Visual Studio installed. It now returnsNonefor "could not ask", and the only state that gates is a search that ran and came back empty, which is the 'stdlib.h' file not found during 1st install on AMD/Windows #7595 case itself.is_clang_clonly exists from 3.5.1.post23. Importing it in the same statement asget_ccandis_msvcmeant the whole import raised on every earlier release, discarding a usableget_ccand dropping through to a guess based on the ROCm wheel being on disk. Those releases predate the ROCm clang-cl branch and select TinyCC, which needs no SDK, so an AMD box with the wheel installed and no Visual Studio compiled fine and would have been gated. The names are now imported separately, and where the predicates are absent the fallback is what they do, a case-insensitive basename match.get_ccno longer exists on the release a barepip install triton-windowsresolves to. 3.8.0.post28 renamed it to_find_compiler(language); the"c"branch is the old body. Every install on that release skipped the compiler question and answered from the wheel layout. That still gated 'stdlib.h' file not found during 1st install on AMD/Windows #7595 correctly, but it decided from what is installed rather than from what Triton will run, which is the premise._find_compiler("c")is read whenget_ccis absent.Also worth recording, since an earlier version of this description got it wrong: the real fallback order in
get_ccisCC-> the ROCm wheel'sclang-cl->find_msvc_winsdk(env_only = True)-> bundled TinyCC ->which("cl")->which("gcc")->which("clang"). There is noPATHlookup forclang-cl, and the MSVC step isenv_only, so on a box with Visual Studio installed but outside a developer prompt Triton picks TinyCC, notcl.exe. And thewindows_utilssplit is not recent: it happened in October 2024 atv3.0.0-windows.post3. The genuinely old shape this has to tolerate is the 2-tuple return, not a missing module.Also closes the diffusion gap raised on this thread
The workers are subprocesses. Image and video generation run in the server process, which those gates never reach, so a user on an RX 9070 XT with no Visual Studio had Z-Image Q4 load fine and die at step 0 of the first generation. Two places:
diffusion_speed.pytorch_compile_runtime_available()testedimport triton. It now askscrt_headers_reachable().diffusion_speed.py:246is anif, so it never reached the check insidecompile_eligible(); only the denseelifwas protected. GGUF also defaults toSPEED_DEFAULT, so it is the one path that turns compile on by default and skipped the guard.Behaviour, and what was actually verified
The last column is the honest one.
find_msvc_winsdk(), a realclang-clcompile with the env stripped, and the gate leavingTORCHDYNAMO_DISABLEunsettorch.compiledisabled with an actionable message, generation proceeds eagerCCpinned to the bundledtcc.exe, but on no NVIDIA machinepytorch-triton-xpu)tritonname, ships nowindows_utilsand noget_cc, and reportspytorch-triton-xpufrompackages_distributions(), which is what the discriminator keys onplatform.machine(), so ARM64 answers exactly as x64 does; that equivalence is pinned by simulation, not by hardwarewin_amd64wheels read out of the archive and replayed against AMD/NVIDIA x VS/no-VS: 56 cells, no case where a box that compiles today is gatedTests
84 across
test_msvc_env_7595.py(37) andtest_diffusion_speed.py(47). Platform-independent: Triton's discovery and compiler pick are stubbed throughsys.modules, so they answer the same on a Linux runner and on a Windows box with or without VS. The old end-to-end test that ran the realvcvarsallgoes with the code it tested.Each new test is mutation-checked; reverting its fix makes it fail.
Beyond the unit tests, on Linux + NVIDIA:
_msvc_env.pyexecute on Linux, bothsys.platformguards and both returns, so no Triton probing happens off Windows at all.TORCHDYNAMO_DISABLE=1, was exercised against real inductor. Before this change that variable was only ever set whenimport tritonhad failed.torch.compilebecomes a true no-op, output is bit-identical to eager, backward still runs.core._msvc_env: each was spawned through its own orchestrator's realmp.get_context("spawn")and trampoline, and the gate ran to completion in the child.Self-hosted gfx1151 (Strix Halo) / Linux / ROCm 7.2.1, base vs head: NO_REGRESSION. That is the right verdict for this PR on Linux and the only one that host can give: the change is Windows-only, so the runner shows it is genuinely inert off win32 and cannot speak to the defect itself.
Bottom line. The premise correction and the "leave a working machine alone" direction are measured on real Windows AMD hardware, and the private-API drift that could break a working machine is replayed against every shipped triton-windows wheel. The failure direction is not measured: nobody available has a Windows box without Visual Studio, so the crash this prevents is reproduced in a stub rather than end to end.