Repository navigation
[ROCm] Fix hipify skipping sources under Windows subst drives/symlinks in CUDAExtension - #194641
pablo-garay wants to merge 4 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194641
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (3 Unrelated Failures)As of commit 23eefa2 with merge base 3374f39 ( BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
jithunnair-amd
left a comment
There was a problem hiding this comment.
@jeffdaily Please review
jeffdaily
left a comment
There was a problem hiding this comment.
Thanks for chasing this down; the subst-drive diagnosis matches what I'd expect from the includes scope filter. A few things need to change before this goes in.
1. realpath on the sources changes Linux behavior and relocates generated files.
On POSIX os.getcwd() is already fully resolved, so os.path.realpath(os.getcwd()) is a no-op on Linux. The only Linux-visible change here is os.path.realpath(s) over sources, so "No effect on Linux" isn't quite right. When a source inside the build dir is a symlink (build systems that overlay/symlink sources into the build tree do this), realpath moves it out of build_dir. Repro against current hipify_python with build/foo.cu -> ../real/foo.cu:
MODE abspath key=/tmp/hipsym/build/foo.cu -> /tmp/hipsym/build/foo.hip [ok]
MODE realpath key=/tmp/hipsym/real/foo.cu -> /tmp/hipsym/real/foo.hip [ok]
The generated .hip now lands in the source tree rather than the build dir, and os.path.relpath(hipified_s_abs, build_dir) then yields ../real/foo.hip, which is exactly what the comment on the next line rules out ("must always be /-separated paths relative to the setup.py directory"). Nothing cleans those up either, since this call site passes no clean_ctx.
Suggest canonicalizing only when the plain abspath isn't already under the build dir:
def _canonical_source(s):
s_abs = os.path.abspath(s)
return s_abs if s_abs.startswith(build_dir + os.sep) else os.path.realpath(s)That still fixes the reported case (torchaudio passes C:\... absolutes while cwd is B:\..., so the prefix test fails and realpath applies) without moving symlinked sources.
2. The real root cause is in hipify_python, and this only fixes sources that live under build_dir.
hipify() appends extra_files to all_files verbatim, while preprocessor() tests _to_unix_path(filepath) against all_files. Since _to_unix_path replaces os.sep, on Windows the appended backslash spelling can never match the forward-slash form being tested, so the extra_files escape hatch is effectively dead and hipification depends entirely on the directory walk matching includes=[build_dir/*]. That's why the mismatch showed up as a silent skip. Normalizing on append (all_files.append(_to_unix_path(f)), plus the all_files_set membership test) fixes it at the source, is platform-independent, and unlike the change here it's unit-testable without ROCm hardware. As written, any Windows source outside build_dir is still silently skipped.
3. load() has the identical pattern and isn't touched.
torch/utils/cpp_extension.py around lines 2380/2390 uses the same extra_files=[os.path.abspath(s) for s in sources] / s_abs = os.path.abspath(source) pair with project_directory=build_directory. Under the same setup (build dir on the subst drive, caller-supplied sources resolved to the real drive) load/load_inline should skip hipify too. Either apply the same treatment or say why it's unaffected.
4. Please make the skip loud.
The whole failure mode is "hipify quietly did nothing" and the user only learns about it when hipcc reports a missing cuda_runtime_api.h. Warning in the loop when a .cu/.cuh source comes back with hipified_path is None (or missing from hipify_result) would make this class of bug self-diagnosing.
5. Test.
The symlink regression in (1) reproduces on Linux with no ROCm hardware; torch.utils.hipify.hipify_python is pure Python and importable standalone, and test/test_utils.py already has hipify tests. A test that puts a symlinked .cu in a build dir, calls hipify(..., includes=[build_dir/'*'], extra_files=[...], hipify_extra_files_only=True), and asserts the output stays under the build dir would pin both the fix and the regression. If the normalization moves into hipify_python per (2), the same test covers the path-spelling case as well. Trunk being green doesn't cover any of this, since no CI job builds under a subst drive.
Reviewed with assistance from Claude (Anthropic); findings verified locally and edited by me.
|
|
|
Thanks for the thorough review — fixing it at the root was the right call. Addressed all points in 86420ca:
PTAL. |
jeffdaily
left a comment
There was a problem hiding this comment.
Re-reviewed 86420ca. The hipify_python normalization is the right root-cause fix. Three things still need to change.
1. The new test passes on unmodified main.
test_hipify_keeps_symlinked_source_under_build_dir calls hipify() directly, so it never reaches CUDAExtension's _canonical_source, which is where the "don't realpath a source already under build_dir" decision lives. And _to_unix_path is the identity on POSIX, so the hipify_python.py change is a no-op for it too. Running the test body against current main:
/tmp/tmp04kh2mnc/build/kernel.cu -> /tmp/tmp04kh2mnc/build/kernel.hip [ok]
TEST PASSED on unpatched main
Neither behavior change in the PR is pinned. The Linux-visible half is testable if _canonical_source moves to module scope (it is currently duplicated verbatim in CUDAExtension and _jit_compile): assert it returns the abspath for a path under build_dir and the realpath for one outside. The separator half is Windows-only and I am fine leaving it uncovered, but then the test name and docstring shouldn't read as if they cover it.
2. The root-cause fix leaves two siblings in the same block broken the same way.
hipify_python.py:1165 iterates the raw extra_files argument; the loop above rebinds a local f, so neither the os.path.join(output_directory, f) nor the new _to_unix_path(f) reaches the iteration. A relative extra_files entry is still silently skipped on every platform after this PR:
extra_files=["kernel.cu"], hipify_extra_files_only=True
-> {'/tmp/.../build/kernel.cu': (None, '[ignored, not to be hipified]')}
Building the normalized list once and iterating that fixes it.
hipify_python.py:1152-1157 extends all_files with str(path) from Path.rglob, which is backslash-spelled on Windows and so can never match the _to_unix_path-normalized filepath at line 831. Additionally _fnmatch(str(path), includes) on line 1154 compares that backslash path against includes, normalized at line 1130, so on Windows header_include_dirs contributes nothing at all. CUDAExtension passes header_include_dirs=include_dirs, so an extension whose .cuh sits in an include_dirs entry stays unhipified on Windows even with this PR applied. That is the same failure mode the PR is fixing.
3. The _jit_compile guard is inconsistent with itself.
It tests os.path.abspath(s).startswith(os.path.realpath(build_directory) + os.sep) while leaving project_directory/output_directory as the unresolved build_directory; CUDAExtension resolves both. load_inline writes main.cpp/cuda.cu into build_directory and passes those as sources, so with a symlinked build_directory= or TORCH_EXTENSIONS_DIR (the default from get_default_build_root() is already realpath'd) the prefix test fails for files that genuinely are in the build dir and they take the realpath branch, which is exactly what the guard exists to prevent. Compare os.path.realpath(s) against the resolved base, or resolve build_directory once and pass the resolved form through as CUDAExtension does.
Also: the CI-green claim in the description points at run 32807838458, which predates 86420ca. Current head has 4 red mi300 jobs, all unrelated as far as I can tell (test_Transformer_multilayer_coder_cuda_tf32 failing consistently, and two inductor shards hitting the 270 minute job timeout), but the link is worth refreshing.
Reviewed with assistance from Claude (Anthropic); findings verified locally and edited by me.
|
@pablo-garay ping on my 09-14 review: the test still passes on unmodified main (it bypasses Drafted with AI assistance (Claude); reviewed by me. |
|
@jeffdaily thanks for the careful re-review — you were right on all four, 86420ca only got halfway. Fixed in d7e877e: 1. Test now pins the behavior. Moved the 2. Relative 3. 4. Verified the point-2 fix both ways on Windows (hipified with the fix; |
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
…DAExtension CUDAExtension scopes hipify to os.getcwd() and filters sources with includes=[build_dir/*], but source paths passed by some builds (e.g. torchaudio) resolve through symlinks/junctions or Windows subst drive aliases. On Windows ROCm CI the build runs under a subst drive (B:) while sources resolve to the real drive (C:), so the includes filter matches nothing and hipify silently skips the GPU sources, leaving raw CUDA headers (cuda_runtime_api.h) for hipcc. Normalize build_dir and the source paths with os.path.realpath so both sides share one canonical form. No effect on Linux, where the paths already agree. Cherry-pick of ROCm#3561 (ROCM-29365). Signed-off-by: pablo-garay <[email protected]>
…arn on skip - hipify_python: normalize extra_files with _to_unix_path on append so the Windows backslash spelling matches preprocessor's membership test (the real root cause of the silent skip). - CUDAExtension/load: only realpath sources not already under the build dir, so symlinked-in sources aren't relocated; warn when a .cu/.cuh source is left unhipified. - test_utils: add Linux-reproducible regression test for symlinked source. Signed-off-by: pablo-garay <[email protected]>
…ip_source, pin tests hipify_python: build the normalized extra_files list once and iterate that (relative entries were skipped because the preprocessing loop used the raw list); normalize rglob header-include paths with _to_unix_path. cpp_extension: hoist the per-call _canonical_source closure to a module-level _canonicalize_hip_source(source, build_dir) used by both CUDAExtension and _jit_compile; resolve build_directory once in _jit_compile and pass the resolved form to hipify and the guard. test_utils: replace the non-pinning symlink test with a direct unit test of _canonicalize_hip_source and a hipify() test for the relative extra_files skip (fails without the fix). Signed-off-by: pablo-garay <[email protected]>
On Linux, routing every out-of-build-dir source through realpath changed load()/CUDAExtension behavior for file-level symlinked sources: the generated .hip moved next to the symlink target, so quote-includes that only exist beside the symlink stopped resolving. The realpath is only needed for Windows subst drives and junctions, so gate it (and the build-dir realpath in _jit_compile) on IS_WINDOWS; POSIX paths are now the same as on main. test_canonicalize_hip_source checks both branches by patching IS_WINDOWS. Test Plan: ``` python test/test_utils.py -k "canonicalize_hip_source or hipify" ``` 11 passed on Linux ROCm (PR's cpp_extension/hipify loaded over an installed torch); a proj/k.cu -> store/k.cu symlink now canonicalizes to proj/k.cu, as on main. This change was developed with the assistance of an AI assistant (Claude).
|
Successfully rebased |
c7654f5 to
23eefa2
Compare
jeffdaily
left a comment
There was a problem hiding this comment.
Thanks, all three points from my last review are fixed at 23eefa2: _canonicalize_hip_source is shared and directly tested, the relative-extra_files and header_include_dirs paths are normalized, and _jit_compile compares against the same resolved build dir it passes to hipify. LGTM.
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 3 checks: rocm-mi300 / linux-noble-rocm-py3.11-mi300 / test (default, 1, 8, linux.rocm.gpu.mi300.1), rocm-mi300 / linux-noble-rocm-py3.11-mi300 / test (default, 8, 8, linux.rocm.gpu.mi300.1), rocm-mi300 / linux-noble-rocm-py3.11-mi300 / test (default, 6, 8, linux.rocm.gpu.mi300.1) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…s in CUDAExtension (pytorch#194641) ## Summary `CUDAExtension` scopes hipify to `os.getcwd()` and filters sources with `includes=[build_dir/*]`, comparing against `os.path.abspath(...)` source paths. When a build passes source paths that resolve through symlinks/junctions or Windows `subst` drive aliases, the two sides end up with different spellings of the same location, the `includes` filter matches nothing, and hipify **silently skips** the GPU sources leaving raw CUDA headers (e.g. `cuda_runtime_api.h`) for `hipcc`, which then fails with `fatal error: 'cuda_runtime_api.h' file not found`. This reproduces on Windows ROCm CI, where the build runs under a `subst` drive (e.g. `B:`) while a dependency such as torchaudio computes its source directory with `Path(...).resolve()` and lands on the real drive (e.g. `C:`). `build_dir` (`B:\...`) and the source paths (`C:\...`) then disagree. ## Fix The root cause is in `torch/utils/hipify/hipify_python.py`: `hipify()` appended `extra_files` to `all_files` verbatim, while `preprocessor()` tests `_to_unix_path(filepath)` against `all_files`. On Windows the appended backslash spelling never equals the forward-slash form being tested, so the `extra_files` escape hatch was effectively dead and hipification depended entirely on the `includes=[build_dir/*]` directory walk - which the subst-drive mismatch defeats. `extra_files` entries are now normalized with `_to_unix_path` on append (and added to `all_files_set`), fixing the silent skip at the source in a platform-independent, unit-testable way. In `CUDAExtension` (and the matching `load()` / `_jit_compile` path), each source is canonicalized only when its plain `os.path.abspath` isn't already under `build_dir`. This fixes the subst-drive case without `realpath`-ing sources that are legitimately symlinked *into* the build dir - doing so would relocate the generated `.hip` outside `build_dir` and break the "paths relative to the setup.py directory" invariant. The build directory itself is still `realpath`'d (a no-op on POSIX). Finally, when a `.cu`/`.cuh` source comes back unhipified, we now log a warning so this failure mode is self-diagnosing instead of surfacing later as a missing `cuda_runtime_api.h`. The only Linux-visible behavior change is the guarded source canonicalization; the build-dir `realpath` and the `extra_files` normalization are no-ops on POSIX. ## Test plan - New unit test `test/test_utils.py::TestHipify::test_hipify_keeps_symlinked_source_under_build_dir` (runs on Linux, no ROCm hardware): a `.cu` symlinked into the build dir is hipified in place, with the generated `.hip` staying under the build dir and not following the symlink into the real source tree. - Windows ROCm extension build (e.g. torchaudio) hipifies and compiles GPU sources: the hipify pass reports kernel replacements > 0 and produces `.hip` sources instead of leaving `.cu`. ## CI results Run on the current head with `ciflow/trunk` + full MI300 coverage (`ciflow/rocm-mi300`, `ciflow/periodic-rocm-mi300`, `ciflow/inductor-rocm-mi300`) — see [HUD](https://hud.pytorch.org/pr/194641). 338 checks passed (all of trunk, lint, CUDA, ASAN, Windows, macOS, aarch64, dynamo, and the ROCm MI350 matrix); the new hipify unit test passed. The only 4 failures are all on the `linux-noble-rocm-py3.12-mi300` matrix and are pre-existing ROCm flakes unrelated to this change (which only touches the extension build/hipify path, not these tests): - `test (default, 1, 8)` and `test (distributed, 3, 5)` — TF32 numeric-tolerance mismatch in `test_nn.py` Transformer tests (`Tensor-likes are not close`, ~0.23 abs diff vs 0.08 allowed). - `test (inductor, 1, 2)` and `test (inductor, 2, 2)` — the whole `Test` step hit the 270-minute wall-clock limit mid `test_torchinductor`/`test_aot_inductor` suite (no assertion failure). Cherry-pick of ROCm#3561 (ROCM-29365), validated end-to-end there with a full Windows ROCm multi-arch wheel build (torch + torchaudio + torchvision). Pull Request resolved: pytorch#194641 Approved by: https://github.com/jithunnair-amd, https://github.com/jeffdaily Co-authored-by: Jeff Daily <[email protected]>
…#3561) Resolve the build directory and source paths with os.path.realpath in CUDAExtension so hipify matches sources when Windows CI builds under a subst drive (B: aliasing C:). Without this, torchaudio GPU sources are left unhipified and fail on cuda_runtime_api.h. Same fix as release/2.13 (#3561) and release/2.14 (f11950f); nightly has it via pytorch#194641. (cherry picked from commit f11950f) Signed-off-by: pablo-garay <[email protected]>
…#3561) (#3832) ## Summary Cherry-pick the hipify `subst`-drive fix into `release/2.15`. It's the same change as `release/2.13` (#3561) and `release/2.14` (f11950f); upstream nightly has it via pytorch#194641. Windows CI builds under a `subst` drive (`B:` aliasing `C:\scratch-b`), so `CUDAExtension` compares `B:\...` with `C:\...` and hipify silently skips torchaudio's GPU sources. Resolving both sides with `os.path.realpath` fixes the match. No effect on Linux. ## Test plan - Failing without this: Windows py3.12 build of `release/2.15` ([run 38716492477](https://github.com/ROCm/TheRock/actions/runs/38716492477)) fails in torchaudio `rnnt/gpu/compute.cu` and `forced_align/gpu/compute.cu` with `'cuda_runtime_api.h' file not found`. - The diff is identical to the 2.14 fix, which builds torchaudio on Windows. - Re-running the Windows build on `pablo-garay/release-2.15-integration` with this commit for ROCm/TheRock#9031. Signed-off-by: pablo-garay <[email protected]>
## Issue being fixed Fixes #199664 ## BC-breaking? No ## Summary (human written only) This fixes `hipify()` on Windows, where extension source files and headers were not being hipified correctly, causing JIT-built HIP extensions to fail. It also fixes a secondary crash when the source files and build directory are on different drives. The fixes were tested successfully with ROCm and DeepSpeed. ## Agent details (if applicable) Prepared with Claude; I reviewed the change and reran the tests myself. > Since #194641 normalizes `extra_files` and include-dir headers, this PR covers the remaining Windows cases. When no relative path exists between a source and the output directory (different drives on Windows), the output path is anchored at the source's drive root, so the `.hip` file still lands next to the source. The two include rewrites that emitted `\` now go through `_to_unix_path`. On POSIX both are no-ops. > > Tested on Windows with ROCm torch 2.15.0a0+rocm10.2.0a20261001 (gfx1200), with the patched `hipify_python.py` loaded in place of the installed one. The two new `TestHipify` tests fail before the change and pass after. The repro from the issue builds and runs, and DeepSpeed's `FusedAdam` JIT-builds with sources and build directory on different drives and matches `torch.optim.AdamW` to within 5e-8. Pull Request resolved: #199665 Approved by: https://github.com/jeffdaily
…#3561) (#3832) ## Summary Cherry-pick the hipify `subst`-drive fix into `release/2.15`. It's the same change as `release/2.13` (#3561) and `release/2.14` (f11950f); upstream nightly has it via pytorch#194641. Windows CI builds under a `subst` drive (`B:` aliasing `C:\scratch-b`), so `CUDAExtension` compares `B:\...` with `C:\...` and hipify silently skips torchaudio's GPU sources. Resolving both sides with `os.path.realpath` fixes the match. No effect on Linux. ## Test plan - Failing without this: Windows py3.12 build of `release/2.15` ([run 38716492477](https://github.com/ROCm/TheRock/actions/runs/38716492477)) fails in torchaudio `rnnt/gpu/compute.cu` and `forced_align/gpu/compute.cu` with `'cuda_runtime_api.h' file not found`. - The diff is identical to the 2.14 fix, which builds torchaudio on Windows. - Re-running the Windows build on `pablo-garay/release-2.15-integration` with this commit for ROCm/TheRock#9031. Signed-off-by: pablo-garay <[email protected]>
|
HI @thiagocrepaldi please target these fixes for 2.16.0 release these do not affect wheels and are not eligible to 1.5.1 release |
Summary
CUDAExtensionscopes hipify toos.getcwd()and filters sources withincludes=[build_dir/*], comparing againstos.path.abspath(...)source paths. When a build passes source paths that resolve through symlinks/junctions or Windowssubstdrive aliases, the two sides end up with different spellings of the same location, theincludesfilter matches nothing, and hipify silently skips the GPU sources leaving raw CUDA headers (e.g.cuda_runtime_api.h) forhipcc, which then fails withfatal error: 'cuda_runtime_api.h' file not found.This reproduces on Windows ROCm CI, where the build runs under a
substdrive (e.g.B:) while a dependency such as torchaudio computes its source directory withPath(...).resolve()and lands on the real drive (e.g.C:).build_dir(B:\...) and the source paths (C:\...) then disagree.Fix
The root cause is in
torch/utils/hipify/hipify_python.py:hipify()appendedextra_filestoall_filesverbatim, whilepreprocessor()tests_to_unix_path(filepath)againstall_files. On Windows the appended backslash spelling never equals the forward-slash form being tested, so theextra_filesescape hatch was effectively dead and hipification depended entirely on theincludes=[build_dir/*]directory walk - which the subst-drive mismatch defeats.extra_filesentries are now normalized with_to_unix_pathon append (and added toall_files_set), fixing the silent skip at the source in a platform-independent, unit-testable way.In
CUDAExtension(and the matchingload()/_jit_compilepath), each source is canonicalized only when its plainos.path.abspathisn't already underbuild_dir. This fixes the subst-drive case withoutrealpath-ing sources that are legitimately symlinked into the build dir - doing so would relocate the generated.hipoutsidebuild_dirand break the "paths relative to the setup.py directory" invariant. The build directory itself is stillrealpath'd (a no-op on POSIX).Finally, when a
.cu/.cuhsource comes back unhipified, we now log a warning so this failure mode is self-diagnosing instead of surfacing later as a missingcuda_runtime_api.h.The only Linux-visible behavior change is the guarded source canonicalization; the build-dir
realpathand theextra_filesnormalization are no-ops on POSIX.Test plan
test/test_utils.py::TestHipify::test_hipify_keeps_symlinked_source_under_build_dir(runs on Linux, no ROCm hardware): a.cusymlinked into the build dir is hipified in place, with the generated.hipstaying under the build dir and not following the symlink into the real source tree..hipsources instead of leaving.cu.CI results
Run on the current head with
ciflow/trunk+ full MI300 coverage (ciflow/rocm-mi300,ciflow/periodic-rocm-mi300,ciflow/inductor-rocm-mi300) — see HUD. 338 checks passed (all of trunk, lint, CUDA, ASAN, Windows, macOS, aarch64, dynamo, and the ROCm MI350 matrix); the new hipify unit test passed.The only 4 failures are all on the
linux-noble-rocm-py3.12-mi300matrix and are pre-existing ROCm flakes unrelated to this change (which only touches the extension build/hipify path, not these tests):test (default, 1, 8)andtest (distributed, 3, 5)— TF32 numeric-tolerance mismatch intest_nn.pyTransformer tests (Tensor-likes are not close, ~0.23 abs diff vs 0.08 allowed).test (inductor, 1, 2)andtest (inductor, 2, 2)— the wholeTeststep hit the 270-minute wall-clock limit midtest_torchinductor/test_aot_inductorsuite (no assertion failure).Cherry-pick of ROCm#3561 (ROCM-29365), validated end-to-end there with a full Windows ROCm multi-arch wheel build (torch + torchaudio + torchvision).
cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang