Skip to content

[ROCm] Install gitignored torch/_rocm_init.py into ROCm wheels - #191625

Closed
tvukovic-amd wants to merge 4 commits into
pytorch:mainfrom
tvukovic-amd:fix/rocm-init-wheel-packaging
Closed

tvukovic-amd wants to merge 4 commits into
pytorch:mainfrom
tvukovic-amd:fix/rocm-init-wheel-packaging

Conversation

@tvukovic-amd

@tvukovic-amd tvukovic-amd commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes ROCm/TheRock#6965

ROCm runtime-wheel builds inject a generated torch/_rocm_init.py that is gitignored (see .gitignore: injected by ROCm build scripts). At startup, torch/__init__.py optionally imports _rocm_init and calls initialize() to prepare ROCm for runtime-wheel deployments (see TheRock python packaging docs).
Like version.py, scikit-build-core does not include this file in the wheel, so ROCm wheels can ship without it and import torch fails. This adds an explicit CMake install() for _rocm_init.py when USE_ROCM is set and the file exists at build time. Applies to ROCm wheels on Linux and Windows.

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang

@pytorch-bot pytorch-bot Bot added module: rocm AMD GPU support for Pytorch topic: not user facing topic category labels Jul 30, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/191625

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 8b5c1d6 with merge base a55343a (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@malfet malfet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but shouldn't it be guarded behind USE_ROCM

Comment thread torch/CMakeLists.txt Resolved
Co-authored-by: Nikita Shulga <[email protected]>

@ScottTodd ScottTodd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This impacts ROCm on Linux as well, so the PR title and description could be updated.

Comment thread torch/CMakeLists.txt
Comment on lines 546 to +552
# version.py is gitignored (generated), so scikit-build-core won't include it
# via Python package collection. Install it explicitly via cmake instead.
install(FILES "${TORCH_SRC_DIR}/version.py" DESTINATION ".")

if(USE_ROCM AND EXISTS "${TORCH_SRC_DIR}/_rocm_init.py")
install(FILES "${TORCH_SRC_DIR}/_rocm_init.py" DESTINATION ".")
endif()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should a similar comment to the version.py comment be added for _rocm_init.py?

Depending on how much detail you want to include, either of these could be referenced:

  • pytorch/torch/__init__.py

    Lines 165 to 177 in 089bcc5

    # If PyTorch was built against the ROCm runtime wheels, then there will be
    # a _rocm_init module and it will define an initialize() function which can
    # prepare ROCm for use. See general documentation on ROCm runtime wheels:
    # https://github.com/ROCm/TheRock/blob/main/docs/packaging/python_packaging.md
    # Since this module is only ever added to the wheel if built for such a
    # deployment, it is always safe to attempt.
    try:
    from . import _rocm_init # type: ignore[attr-defined]
    except ImportError:
    pass
    else:
    _rocm_init.initialize()
    del _rocm_init
  • https://github.com/ROCm/TheRock/blob/main/docs/packaging/python_packaging.md (already linked from that __init__.py code
  • pytorch/.gitignore

    Lines 154 to 155 in 089bcc5

    # This file is injected by ROCm build scripts to bootstrap in torch/__init__.py.
    torch/_rocm_init.py

Some of that could also just go in the PR description / commit message.

ethanwee1 added a commit to ethanwee1/pytorch that referenced this pull request Jul 30, 2026
Scope this PR to the libomp140.x86_64.dll packaging fix. The
_rocm_init.py cmake install is also added by pytorch#191625; removing the
duplicate hunk here avoids a merge conflict regardless of merge order.
@ethanwee1

Copy link
Copy Markdown
Contributor

Started combined Windows validation (CMake _rocm_init + libomp140) on TheRock using PR #6782 fork-checkout input: https://github.com/ROCm/TheRock/actions/runs/30587605889 (pytorch ew/test-6965-combined, gfx1100, py3.12).

ScottTodd added a commit to ROCm/TheRock that referenced this pull request Jul 30, 2026
… PRs land (#7009)

## Motivation

This passes scikit-build-core force-include settings for our generated
and .gitignore'd `_rocm_init.py` file and Windows OpenMP runtime files.

* Local patch for #6965
* This should be compatible with
  * pytorch/pytorch#191625
  * pytorch/pytorch#191632
  * pytorch/pytorch#191629

## Technical Details

* `python -m build` backend configuration
(https://build.pypa.io/en/stable/how-to/config-settings.html) documents
`-C` as shorthand for `--config-setting`. It forwards `KEY=VALUE`
settings to the selected PEP 517 backend.
* scikit-build-core configuration
(https://scikit-build-core.readthedocs.io/en/stable/configuration/#configuration)
says every setting can be supplied through `pyproject.toml`, PEP 517
config settings, or environment variables. Its examples use dotted CLI
keys such as `-Ccmake.build-type=Debug` (see
https://scikit-build-core.readthedocs.io/en/stable/reference/configs.html#confval-cmake.build-type)
* scikit-build-core’s `wheel.force-include` section
(https://scikit-build-core.readthedocs.io/en/stable/configuration/#force-including-files)
documents the source-to-destination mapping and notes that exact
force-includes override exclusions.

## Test Plan

Trigger builds of pytorch on linux and windows using 'nightly', look for
`_rocm_init.py` and library load succeeding

| Config | Logs | Result |
-- | -- | --
Linux 'nightly' |
https://github.com/ROCm/TheRock/actions/runs/30588591418 | Pending
Linux 'release/2.12' |
https://github.com/ROCm/TheRock/actions/runs/30589526077 | Pending
Windows 'nightly' |
https://github.com/ROCm/TheRock/actions/runs/30588680552 | Pending

## Submission Checklist

- [x] Look over the contributing guidelines at
https://github.com/ROCm/TheRock/blob/main/CONTRIBUTING.md.

Co-authored-by: Codex <[email protected]>
@tvukovic-amd tvukovic-amd changed the title [ROCm][Windows] Install gitignored torch/_rocm_init.py into ROCm wheels [ROCm] Install gitignored torch/_rocm_init.py into ROCm wheels Jul 31, 2026
@tvukovic-amd

Copy link
Copy Markdown
Contributor Author

@ScottTodd
Thank you for the review. Updated PR title, description and added similar comment to the version.py

@ethanwee1

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Aug 3, 2026

Copy link
Copy Markdown

Pull workflow has not been scheduled for the PR yet. It could be because author doesn't have permissions to run those or skip-checks keywords were added to PR/commits, aborting merge. Please get/give approval for the workflows and/or remove skip ci decorators before next merge attempt. If you think this is a mistake, please contact PyTorch Dev Infra.

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end labels Aug 3, 2026
@ethanwee1

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@ethanwee1

Copy link
Copy Markdown
Contributor

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 18, 2026
pytorch#191625 added an install rule for the gitignored torch/_rocm_init.py after the
preceding commit was written, using DESTINATION "." and no SKBUILD guard -- the
pattern that commit replaces everywhere else. It was the last remaining
prefix-root destination in the tree, so a standalone ROCm `cmake --install` still
dropped _rocm_init.py at the prefix root next to bin/, include/ and lib/, which
is the pytorchgh-191102 regression with a smaller blast radius.

Guard it on SKBUILD and address SKBUILD_PLATLIB_DIR, matching the version.py rule
directly above it. Wheel contents are unchanged: under scikit-build-core the
prefix already is the torch package directory, so the old and new destinations
resolve to the same path.

Authored with assistance from Claude Code.

Test Plan:
No prefix-relative install destination remains in the build system:

```
grep -rn 'DESTINATION "\."' --include='*.cmake' --include='CMakeLists.txt' .
# (no matches)
```

Lint:

```
lintrunner -a torch/CMakeLists.txt
```

The rule is ROCm-gated and the file is gitignored, so it is only exercised by a
ROCm build where the ROCm packaging scripts have injected torch/_rocm_init.py;
ciflow/binaries covers that path once this leaves draft.
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 18, 2026
The preceding commits fix pytorchgh-191102, but nothing stops it coming back, and it
already did once: pytorch#191625 landed three weeks after the fix was written and
reintroduced the bug for ROCm builds with

  install(FILES "${TORCH_SRC_DIR}/_rocm_init.py" DESTINATION ".")

Neither the build, the test suite nor CI noticed. They cannot: the only
standalone-install path exercised in CI is tools/build_libtorch.py, which
configures with BUILD_PYTHON=OFF and so never evaluates the Python-side install
rules at all.

Add two grep_linter rules, so the pattern is rejected when it is written rather
than after a release. CMAKE_INSTALL_PREFIX_ROOT forbids a destination of "."
anywhere in the build system -- nothing belongs at the prefix root, since C++
artifacts go under the CMAKE_INSTALL_*DIR directories and package data goes to
the wheel tree. CMAKE_PLATLIB_DESTINATION additionally requires every destination
in the two files that exist solely to install package data to name that tree,
which catches the prefix-relative variant (DESTINATION "utils/model_dump") that a
check for "." alone would miss.

Both are registered in VERY_FAST_LINTERS in .spin/cmds.py. That is not
optional bookkeeping: spin re-runs its lint setup whenever .lintrunner.toml
changes, and _check_linters() raises on any linter code it cannot find in one of
the three speed categories, so adding a rule without classifying it breaks
`spin lint` for everyone. Both are plain greps over CMake files, which puts them
in the same category as CMAKE_MINIMUM_REQUIRED (the heavier cmakelint-based CMAKE
linter is FAST, not VERY_FAST).

This is a text check, not a behavioural one: a destination that reaches the
prefix root through a variable, or a new rule that uses the wheel tree but omits
its SKBUILD guard, still gets through. Closing that needs a job that configures
standalone and inspects the generated install rules, which no job does today.

Authored with assistance from Claude Code.

Test Plan:
Clean on the current tree:

```
lintrunner --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION --all-files
# ok No lint issues.
```

Both rules were then run through the adapter against the pre-fix tree, to confirm
they flag the real regressions rather than merely passing today:

```
BASE=$(git merge-base origin/viable/strict HEAD)
mkdir -p /tmp/prefix/{cmake,torch}
git show "${BASE}":torch/CMakeLists.txt     > /tmp/prefix/torch/CMakeLists.txt
git show "${BASE}":cmake/PackageData.cmake  > /tmp/prefix/cmake/PackageData.cmake
git show "${BASE}":cmake/FileMirroring.cmake > /tmp/prefix/cmake/FileMirroring.cmake

python3 tools/linter/adapters/grep_linter.py '--pattern=DESTINATION[[:space:]]+"\."' \
  --linter-name=CMAKE_INSTALL_PREFIX_ROOT --error-name=x --error-description=x \
  -- /tmp/prefix/torch/CMakeLists.txt /tmp/prefix/cmake/PackageData.cmake

python3 tools/linter/adapters/grep_linter.py '--pattern=DESTINATION[[:space:]]+"[^$]' \
  --linter-name=CMAKE_PLATLIB_DESTINATION --error-name=x --error-description=x \
  -- /tmp/prefix/cmake/PackageData.cmake /tmp/prefix/cmake/FileMirroring.cmake
```

CMAKE_INSTALL_PREFIX_ROOT flags 6 lines -- torch/CMakeLists.txt 474, 475, 517,
548 and 555, plus cmake/PackageData.cmake:21. Line 555 is the pytorch#191625
_rocm_init.py rule, so the check demonstrably catches the regression that
actually happened. CMAKE_PLATLIB_DESTINATION flags 12.

End to end through spin, which exercises the classification check:

```
spin lint -- --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION
```

It picks up the changed lint configuration, re-runs setup without raising on an
unclassified linter, and reports no lint issues.
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 28, 2026
pytorch#191625 added an install rule for the gitignored torch/_rocm_init.py after the
preceding commit was written, using DESTINATION "." and no SKBUILD guard -- the
pattern that commit replaces everywhere else. It was the last remaining
prefix-root destination in the tree, so a standalone ROCm `cmake --install` still
dropped _rocm_init.py at the prefix root next to bin/, include/ and lib/, which
is the pytorchgh-191102 regression with a smaller blast radius.

Guard it on SKBUILD and address SKBUILD_PLATLIB_DIR, matching the version.py rule
directly above it. Wheel contents are unchanged: under scikit-build-core the
prefix already is the torch package directory, so the old and new destinations
resolve to the same path.

Authored with assistance from Claude Code.

Test Plan:
No prefix-relative install destination remains in the build system:

```
grep -rn 'DESTINATION "\."' --include='*.cmake' --include='CMakeLists.txt' .
# (no matches)
```

Lint:

```
lintrunner -a torch/CMakeLists.txt
```

The rule is ROCm-gated and the file is gitignored, so it is only exercised by a
ROCm build where the ROCm packaging scripts have injected torch/_rocm_init.py;
ciflow/binaries covers that path once this leaves draft.
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 28, 2026
The preceding commits fix pytorchgh-191102, but nothing stops it coming back, and it
already did once: pytorch#191625 landed three weeks after the fix was written and
reintroduced the bug for ROCm builds with

  install(FILES "${TORCH_SRC_DIR}/_rocm_init.py" DESTINATION ".")

Neither the build, the test suite nor CI noticed. They cannot: the only
standalone-install path exercised in CI is tools/build_libtorch.py, which
configures with BUILD_PYTHON=OFF and so never evaluates the Python-side install
rules at all.

Add two grep_linter rules, so the pattern is rejected when it is written rather
than after a release. CMAKE_INSTALL_PREFIX_ROOT forbids a destination of "."
anywhere in the build system -- nothing belongs at the prefix root, since C++
artifacts go under the CMAKE_INSTALL_*DIR directories and package data goes to
the wheel tree. CMAKE_PLATLIB_DESTINATION additionally requires every destination
in the two files that exist solely to install package data to name that tree,
which catches the prefix-relative variant (DESTINATION "utils/model_dump") that a
check for "." alone would miss.

Both are registered in VERY_FAST_LINTERS in .spin/cmds.py. That is not
optional bookkeeping: spin re-runs its lint setup whenever .lintrunner.toml
changes, and _check_linters() raises on any linter code it cannot find in one of
the three speed categories, so adding a rule without classifying it breaks
`spin lint` for everyone. Both are plain greps over CMake files, which puts them
in the same category as CMAKE_MINIMUM_REQUIRED (the heavier cmakelint-based CMAKE
linter is FAST, not VERY_FAST).

This is a text check, not a behavioural one: a destination that reaches the
prefix root through a variable, or a new rule that uses the wheel tree but omits
its SKBUILD guard, still gets through. Closing that needs a job that configures
standalone and inspects the generated install rules, which no job does today.

Authored with assistance from Claude Code.

Test Plan:
Clean on the current tree:

```
lintrunner --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION --all-files
# ok No lint issues.
```

Both rules were then run through the adapter against the pre-fix tree, to confirm
they flag the real regressions rather than merely passing today:

```
BASE=$(git merge-base origin/viable/strict HEAD)
mkdir -p /tmp/prefix/{cmake,torch}
git show "${BASE}":torch/CMakeLists.txt     > /tmp/prefix/torch/CMakeLists.txt
git show "${BASE}":cmake/PackageData.cmake  > /tmp/prefix/cmake/PackageData.cmake
git show "${BASE}":cmake/FileMirroring.cmake > /tmp/prefix/cmake/FileMirroring.cmake

python3 tools/linter/adapters/grep_linter.py '--pattern=DESTINATION[[:space:]]+"\."' \
  --linter-name=CMAKE_INSTALL_PREFIX_ROOT --error-name=x --error-description=x \
  -- /tmp/prefix/torch/CMakeLists.txt /tmp/prefix/cmake/PackageData.cmake

python3 tools/linter/adapters/grep_linter.py '--pattern=DESTINATION[[:space:]]+"[^$]' \
  --linter-name=CMAKE_PLATLIB_DESTINATION --error-name=x --error-description=x \
  -- /tmp/prefix/cmake/PackageData.cmake /tmp/prefix/cmake/FileMirroring.cmake
```

CMAKE_INSTALL_PREFIX_ROOT flags 6 lines -- torch/CMakeLists.txt 474, 475, 517,
548 and 555, plus cmake/PackageData.cmake:21. Line 555 is the pytorch#191625
_rocm_init.py rule, so the check demonstrably catches the regression that
actually happened. CMAKE_PLATLIB_DESTINATION flags 12.

End to end through spin, which exercises the classification check:

```
spin lint -- --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION
```

It picks up the changed lint configuration, re-runs setup without raising on an
unclassified linter, and reports no lint issues.
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
…#191494)

Since v2.13.0 a standalone `cmake --install` scatters Python package
directories (_dynamo/, _export/, _inductor/, csrc/, testing/, utils/) across
CMAKE_INSTALL_PREFIX alongside bin/, include/, lib/ and share/, and writes
into the source checkout besides. Reported as #191102. The prefix-root
scattering comes from #177643, which added cmake/PackageData.cmake and its
unconditional include; the source-checkout writes from #177642, which did the
same for cmake/FileMirroring.cmake.

scikit-build-core models a wheel as several trees -- platlib, purelib, data,
headers, scripts, metadata -- and exports each to CMake as SKBUILD_<TREE>_DIR.
`wheel.install-dir` selects which tree, plus optional subpath, becomes
CMAKE_INSTALL_PREFIX; it defaults to empty, which makes the prefix the platlib
root itself. We set it to "torch" because the C++ tree has to sit at torch/lib
for the $ORIGIN/lib install rpath and torch/__init__.py's __file__ lookups to
resolve, and that pushes the prefix one level below platlib.

Most of our Python-side install rules were nonetheless written relative to the
prefix, using it as a proxy for the platlib tree. That only holds while
scikit-build-core is driving and install-dir is exactly "torch". A standalone
cmake install has a conventional prefix and no platlib at all, so the same
rules deposit torch/ package data at the prefix root. cmake/FileMirroring.cmake
did address the tree properly via SKBUILD_PLATLIB_DIR, but fell back to
PROJECT_SOURCE_DIR when it was undefined, which is how a standalone install
came to write into the checkout.

This is not an edge case: docs/libtorch.rst documents building libtorch with
`cmake --build . --target install` into a CMAKE_INSTALL_PREFIX of your choice,
which is the flow the report used. The layout that install should produce is
nowhere documented, which is a gap worth closing separately.

The rules now address SKBUILD_PLATLIB_DIR directly -- cmake/PackageData.cmake,
cmake/FileMirroring.cmake, and the _C, _nccl_ep, version.py and _rocm_init.py
rules in torch/CMakeLists.txt -- guarded on SKBUILD, the sentinel
scikit-build-core sets for exactly this question. A build scikit-build-core does
not drive (libtorch, tools/build_libtorch.py, downstream cmake --install)
installs the C++
distribution alone, which restores the pre-2.13 contract: setup.py owned all
the Python packaging back when a standalone install was C++ only.

Two alternatives are worth naming. The reporter suggested a named install
COMPONENT held out of the default install; that is orthogonal, and already in
flight as #184873 for wheel scoping, but it would not fix this on its own,
because CMake runs every install() rule on a component-less `cmake --install`
whatever its tag. Dropping `wheel.install-dir` instead would make the prefix
the platlib root and coincide the two, but it needs a torch/ prefix on ~90 C++
destinations, ~40 of them raw literals not routed through TORCH_INSTALL_LIB_DIR
and friends, and it inverts the conditional: standalone C++ installs would then
need torch/ suppressed everywhere.

The prefix-must-be-<platlib>/torch coupling is now enforced rather than
assumed. install-dir is what makes the two agree, so changing it silently
produces an install that only fails at import; a mismatch is now a
configure-time FATAL_ERROR naming both paths and pointing at pyproject.toml.

Note that tools/build_libtorch.py loses the torchgen/packaged mirroring, as it
builds with BUILD_PYTHON=OFF and no longer produces a Python payload. The only
consumer of those files is torchgen/gen_backend_stubs.py at runtime in an
installed torchgen, which is not in the libtorch path.

Three things surfaced while reviewing the above and are folded in. #191625 added
an install rule for the gitignored torch/_rocm_init.py while this was open, in
the same prefix-relative form; it was the last remaining DESTINATION "." in the
tree and is now guarded and addressed like its neighbours. The _C rule's ARCHIVE
clause is dropped: _C is a MODULE library, so no Windows import library is
produced and none ships -- the 2026-08-18 cp312 win_amd64 nightlies carry 13 to
16 .lib files across the cpu, cu126 and xpu variants, every one a genuine C++
import library and no _C.lib among them. It was also the one prefix-relative
destination left in a rule whose other two were absolute.

A lint rule is added so this class of regression is rejected when it is written
rather than after a release. #191625 is the evidence that it recurs: it landed
three weeks after this fix and nothing caught it, because no CI job installs
standalone and inspects the result -- tools/build_libtorch.py is the only
standalone-install path exercised in CI and it configures with BUILD_PYTHON=OFF,
so it never evaluates these rules. CMAKE_INSTALL_PREFIX_ROOT forbids a
destination of "." across the build system; CMAKE_PLATLIB_DESTINATION
additionally requires every destination in the two package-data files to name
the wheel tree, which catches the prefix-relative variant. Both reuse the
existing grep_linter adapter and are registered in VERY_FAST_LINTERS in
.spin/cmds.py, which spin requires of every linter. This is a text check, not a
behavioural one: a destination that reaches the prefix root through a variable,
or a new rule that uses the wheel tree but omits its SKBUILD guard, still gets
through.

Test Plan:

All on Linux/CPU unless noted, against the reporter's exact configure from the
issue:

```
cmake -S . -B build-standalone -GNinja \
  -DCMAKE_INSTALL_PREFIX=/tmp/prefix \
  -DATEN_NO_TEST=ON -DBUILD_BINARY=ON -DBUILD_CUSTOM_PROTOBUF=OFF \
  -DBUILD_PYTHON=ON -DBUILD_TEST=OFF -DUSE_OPENMP=ON \
  -DCMAKE_INSTALL_LIBDIR=lib -DUSE_DISTRIBUTED=OFF -DUSE_CUDA=OFF

grep -rhoE '\$\{CMAKE_INSTALL_PREFIX\}/[A-Za-z_./]*' \
  --include=cmake_install.cmake build-standalone/ \
  | sed 's|${CMAKE_INSTALL_PREFIX}/||' | cut -d/ -f1 | sort -u
grep -rh --include=cmake_install.cmake 'CMAKE_INSTALL_PREFIX}/\."' build-standalone/
grep -rh --include=cmake_install.cmake "DESTINATION \"$PWD" build-standalone/
grep -rhE --include=cmake_install.cmake 'DESTINATION "(/torch|/torchgen)' build-standalone/
```

Before: `. bin csrc _dynamo _export _inductor include lib share testing utils`,
plus seven rules with destinations inside the source checkout. After:
`bin include lib share`, and the other three greps empty. The last one checks
that an unset SKBUILD_PLATLIB_DIR has not turned a destination into an absolute
path at the filesystem root. The greps must recurse over every
cmake_install.cmake, not just the top-level one, since several of the offending
rules live in subdirectory scopes.

Same configure with -DUSE_CUDA=ON -DUSE_DISTRIBUTED=ON -DUSE_NCCL=ON
-DUSE_NCCL_EP=ON -DUSE_SYSTEM_NCCL=ON: the _nccl_ep target is still built (it
appears in build.ninja, producing torch/_nccl_ep.cpython-310-x86_64-linux-gnu.so)
but contributes no install rule, and the prefix root stays clean.

The guard, exercised the way it can actually regress -- by changing install-dir
in pyproject.toml to something other than "torch" and building a wheel -- fails
configure with the FATAL_ERROR, reporting platlib, the expected prefix and the
actual one.

Wheel contents, via scikit-build-core:

```
pip install -e . -v --no-build-isolation   # twice, consecutively
python -c "import torch, torchgen.packaged, functorch; print(torch.__version__)"
```

Both builds succeed, each configure picking up its own staging directory. The
installed file list under site-packages is identical to a pre-change build of
the same base: 9679 files, none gained or lost, including the mirrored copies
that exist only in the install tree (valgrind.h/callgrind.h, torchgen/packaged
with native_functions.yaml, tags.yaml, 42 templates and 16 autograd files) and
the generated version.py, _C, 43 .pyi stubs and 20 jinja templates. import and
a matmul both work.

The new lint rules, checked in both directions -- clean on this tree, and
flagging the real regressions on the pre-fix tree:

```
spin lint -- --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION
```

CMAKE_INSTALL_PREFIX_ROOT flags 6 lines on the pre-fix tree -- torch/CMakeLists.txt
474, 475, 517, 548 and 555, plus cmake/PackageData.cmake:21 -- where 555 is the
#191625 _rocm_init.py rule, so the check demonstrably rejects the regression that
actually happened. CMAKE_PLATLIB_DESTINATION flags 12.

Lint:

```
lintrunner -a --take CMAKE,NEWLINE,SPACES,TABS,CODESPELL,COPYRIGHT,EXEC \
  CMakeLists.txt cmake/FileMirroring.cmake cmake/PackageData.cmake \
  cmake/Summary.cmake torch/CMakeLists.txt .lintrunner.toml .spin/cmds.py
```

Not covered: Windows and macOS were not exercised locally; ciflow/binaries is
what covers them.

This change was authored with the assistance of an AI coding assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Fixes #191102

Pull Request resolved: #191494
Approved by: https://github.com/atalman
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…pytorch#191494)

Since v2.13.0 a standalone `cmake --install` scatters Python package
directories (_dynamo/, _export/, _inductor/, csrc/, testing/, utils/) across
CMAKE_INSTALL_PREFIX alongside bin/, include/, lib/ and share/, and writes
into the source checkout besides. Reported as pytorch#191102. The prefix-root
scattering comes from pytorch#177643, which added cmake/PackageData.cmake and its
unconditional include; the source-checkout writes from pytorch#177642, which did the
same for cmake/FileMirroring.cmake.

scikit-build-core models a wheel as several trees -- platlib, purelib, data,
headers, scripts, metadata -- and exports each to CMake as SKBUILD_<TREE>_DIR.
`wheel.install-dir` selects which tree, plus optional subpath, becomes
CMAKE_INSTALL_PREFIX; it defaults to empty, which makes the prefix the platlib
root itself. We set it to "torch" because the C++ tree has to sit at torch/lib
for the $ORIGIN/lib install rpath and torch/__init__.py's __file__ lookups to
resolve, and that pushes the prefix one level below platlib.

Most of our Python-side install rules were nonetheless written relative to the
prefix, using it as a proxy for the platlib tree. That only holds while
scikit-build-core is driving and install-dir is exactly "torch". A standalone
cmake install has a conventional prefix and no platlib at all, so the same
rules deposit torch/ package data at the prefix root. cmake/FileMirroring.cmake
did address the tree properly via SKBUILD_PLATLIB_DIR, but fell back to
PROJECT_SOURCE_DIR when it was undefined, which is how a standalone install
came to write into the checkout.

This is not an edge case: docs/libtorch.rst documents building libtorch with
`cmake --build . --target install` into a CMAKE_INSTALL_PREFIX of your choice,
which is the flow the report used. The layout that install should produce is
nowhere documented, which is a gap worth closing separately.

The rules now address SKBUILD_PLATLIB_DIR directly -- cmake/PackageData.cmake,
cmake/FileMirroring.cmake, and the _C, _nccl_ep, version.py and _rocm_init.py
rules in torch/CMakeLists.txt -- guarded on SKBUILD, the sentinel
scikit-build-core sets for exactly this question. A build scikit-build-core does
not drive (libtorch, tools/build_libtorch.py, downstream cmake --install)
installs the C++
distribution alone, which restores the pre-2.13 contract: setup.py owned all
the Python packaging back when a standalone install was C++ only.

Two alternatives are worth naming. The reporter suggested a named install
COMPONENT held out of the default install; that is orthogonal, and already in
flight as pytorch#184873 for wheel scoping, but it would not fix this on its own,
because CMake runs every install() rule on a component-less `cmake --install`
whatever its tag. Dropping `wheel.install-dir` instead would make the prefix
the platlib root and coincide the two, but it needs a torch/ prefix on ~90 C++
destinations, ~40 of them raw literals not routed through TORCH_INSTALL_LIB_DIR
and friends, and it inverts the conditional: standalone C++ installs would then
need torch/ suppressed everywhere.

The prefix-must-be-<platlib>/torch coupling is now enforced rather than
assumed. install-dir is what makes the two agree, so changing it silently
produces an install that only fails at import; a mismatch is now a
configure-time FATAL_ERROR naming both paths and pointing at pyproject.toml.

Note that tools/build_libtorch.py loses the torchgen/packaged mirroring, as it
builds with BUILD_PYTHON=OFF and no longer produces a Python payload. The only
consumer of those files is torchgen/gen_backend_stubs.py at runtime in an
installed torchgen, which is not in the libtorch path.

Three things surfaced while reviewing the above and are folded in. pytorch#191625 added
an install rule for the gitignored torch/_rocm_init.py while this was open, in
the same prefix-relative form; it was the last remaining DESTINATION "." in the
tree and is now guarded and addressed like its neighbours. The _C rule's ARCHIVE
clause is dropped: _C is a MODULE library, so no Windows import library is
produced and none ships -- the 2026-08-18 cp312 win_amd64 nightlies carry 13 to
16 .lib files across the cpu, cu126 and xpu variants, every one a genuine C++
import library and no _C.lib among them. It was also the one prefix-relative
destination left in a rule whose other two were absolute.

A lint rule is added so this class of regression is rejected when it is written
rather than after a release. pytorch#191625 is the evidence that it recurs: it landed
three weeks after this fix and nothing caught it, because no CI job installs
standalone and inspects the result -- tools/build_libtorch.py is the only
standalone-install path exercised in CI and it configures with BUILD_PYTHON=OFF,
so it never evaluates these rules. CMAKE_INSTALL_PREFIX_ROOT forbids a
destination of "." across the build system; CMAKE_PLATLIB_DESTINATION
additionally requires every destination in the two package-data files to name
the wheel tree, which catches the prefix-relative variant. Both reuse the
existing grep_linter adapter and are registered in VERY_FAST_LINTERS in
.spin/cmds.py, which spin requires of every linter. This is a text check, not a
behavioural one: a destination that reaches the prefix root through a variable,
or a new rule that uses the wheel tree but omits its SKBUILD guard, still gets
through.

Test Plan:

All on Linux/CPU unless noted, against the reporter's exact configure from the
issue:

```
cmake -S . -B build-standalone -GNinja \
  -DCMAKE_INSTALL_PREFIX=/tmp/prefix \
  -DATEN_NO_TEST=ON -DBUILD_BINARY=ON -DBUILD_CUSTOM_PROTOBUF=OFF \
  -DBUILD_PYTHON=ON -DBUILD_TEST=OFF -DUSE_OPENMP=ON \
  -DCMAKE_INSTALL_LIBDIR=lib -DUSE_DISTRIBUTED=OFF -DUSE_CUDA=OFF

grep -rhoE '\$\{CMAKE_INSTALL_PREFIX\}/[A-Za-z_./]*' \
  --include=cmake_install.cmake build-standalone/ \
  | sed 's|${CMAKE_INSTALL_PREFIX}/||' | cut -d/ -f1 | sort -u
grep -rh --include=cmake_install.cmake 'CMAKE_INSTALL_PREFIX}/\."' build-standalone/
grep -rh --include=cmake_install.cmake "DESTINATION \"$PWD" build-standalone/
grep -rhE --include=cmake_install.cmake 'DESTINATION "(/torch|/torchgen)' build-standalone/
```

Before: `. bin csrc _dynamo _export _inductor include lib share testing utils`,
plus seven rules with destinations inside the source checkout. After:
`bin include lib share`, and the other three greps empty. The last one checks
that an unset SKBUILD_PLATLIB_DIR has not turned a destination into an absolute
path at the filesystem root. The greps must recurse over every
cmake_install.cmake, not just the top-level one, since several of the offending
rules live in subdirectory scopes.

Same configure with -DUSE_CUDA=ON -DUSE_DISTRIBUTED=ON -DUSE_NCCL=ON
-DUSE_NCCL_EP=ON -DUSE_SYSTEM_NCCL=ON: the _nccl_ep target is still built (it
appears in build.ninja, producing torch/_nccl_ep.cpython-310-x86_64-linux-gnu.so)
but contributes no install rule, and the prefix root stays clean.

The guard, exercised the way it can actually regress -- by changing install-dir
in pyproject.toml to something other than "torch" and building a wheel -- fails
configure with the FATAL_ERROR, reporting platlib, the expected prefix and the
actual one.

Wheel contents, via scikit-build-core:

```
pip install -e . -v --no-build-isolation   # twice, consecutively
python -c "import torch, torchgen.packaged, functorch; print(torch.__version__)"
```

Both builds succeed, each configure picking up its own staging directory. The
installed file list under site-packages is identical to a pre-change build of
the same base: 9679 files, none gained or lost, including the mirrored copies
that exist only in the install tree (valgrind.h/callgrind.h, torchgen/packaged
with native_functions.yaml, tags.yaml, 42 templates and 16 autograd files) and
the generated version.py, _C, 43 .pyi stubs and 20 jinja templates. import and
a matmul both work.

The new lint rules, checked in both directions -- clean on this tree, and
flagging the real regressions on the pre-fix tree:

```
spin lint -- --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION
```

CMAKE_INSTALL_PREFIX_ROOT flags 6 lines on the pre-fix tree -- torch/CMakeLists.txt
474, 475, 517, 548 and 555, plus cmake/PackageData.cmake:21 -- where 555 is the
pytorch#191625 _rocm_init.py rule, so the check demonstrably rejects the regression that
actually happened. CMAKE_PLATLIB_DESTINATION flags 12.

Lint:

```
lintrunner -a --take CMAKE,NEWLINE,SPACES,TABS,CODESPELL,COPYRIGHT,EXEC \
  CMakeLists.txt cmake/FileMirroring.cmake cmake/PackageData.cmake \
  cmake/Summary.cmake torch/CMakeLists.txt .lintrunner.toml .spin/cmds.py
```

Not covered: Windows and macOS were not exercised locally; ciflow/binaries is
what covers them.

This change was authored with the assistance of an AI coding assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Fixes pytorch#191102

Pull Request resolved: pytorch#191494
Approved by: https://github.com/atalman
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…pytorch#191494)

Since v2.13.0 a standalone `cmake --install` scatters Python package
directories (_dynamo/, _export/, _inductor/, csrc/, testing/, utils/) across
CMAKE_INSTALL_PREFIX alongside bin/, include/, lib/ and share/, and writes
into the source checkout besides. Reported as pytorch#191102. The prefix-root
scattering comes from pytorch#177643, which added cmake/PackageData.cmake and its
unconditional include; the source-checkout writes from pytorch#177642, which did the
same for cmake/FileMirroring.cmake.

scikit-build-core models a wheel as several trees -- platlib, purelib, data,
headers, scripts, metadata -- and exports each to CMake as SKBUILD_<TREE>_DIR.
`wheel.install-dir` selects which tree, plus optional subpath, becomes
CMAKE_INSTALL_PREFIX; it defaults to empty, which makes the prefix the platlib
root itself. We set it to "torch" because the C++ tree has to sit at torch/lib
for the $ORIGIN/lib install rpath and torch/__init__.py's __file__ lookups to
resolve, and that pushes the prefix one level below platlib.

Most of our Python-side install rules were nonetheless written relative to the
prefix, using it as a proxy for the platlib tree. That only holds while
scikit-build-core is driving and install-dir is exactly "torch". A standalone
cmake install has a conventional prefix and no platlib at all, so the same
rules deposit torch/ package data at the prefix root. cmake/FileMirroring.cmake
did address the tree properly via SKBUILD_PLATLIB_DIR, but fell back to
PROJECT_SOURCE_DIR when it was undefined, which is how a standalone install
came to write into the checkout.

This is not an edge case: docs/libtorch.rst documents building libtorch with
`cmake --build . --target install` into a CMAKE_INSTALL_PREFIX of your choice,
which is the flow the report used. The layout that install should produce is
nowhere documented, which is a gap worth closing separately.

The rules now address SKBUILD_PLATLIB_DIR directly -- cmake/PackageData.cmake,
cmake/FileMirroring.cmake, and the _C, _nccl_ep, version.py and _rocm_init.py
rules in torch/CMakeLists.txt -- guarded on SKBUILD, the sentinel
scikit-build-core sets for exactly this question. A build scikit-build-core does
not drive (libtorch, tools/build_libtorch.py, downstream cmake --install)
installs the C++
distribution alone, which restores the pre-2.13 contract: setup.py owned all
the Python packaging back when a standalone install was C++ only.

Two alternatives are worth naming. The reporter suggested a named install
COMPONENT held out of the default install; that is orthogonal, and already in
flight as pytorch#184873 for wheel scoping, but it would not fix this on its own,
because CMake runs every install() rule on a component-less `cmake --install`
whatever its tag. Dropping `wheel.install-dir` instead would make the prefix
the platlib root and coincide the two, but it needs a torch/ prefix on ~90 C++
destinations, ~40 of them raw literals not routed through TORCH_INSTALL_LIB_DIR
and friends, and it inverts the conditional: standalone C++ installs would then
need torch/ suppressed everywhere.

The prefix-must-be-<platlib>/torch coupling is now enforced rather than
assumed. install-dir is what makes the two agree, so changing it silently
produces an install that only fails at import; a mismatch is now a
configure-time FATAL_ERROR naming both paths and pointing at pyproject.toml.

Note that tools/build_libtorch.py loses the torchgen/packaged mirroring, as it
builds with BUILD_PYTHON=OFF and no longer produces a Python payload. The only
consumer of those files is torchgen/gen_backend_stubs.py at runtime in an
installed torchgen, which is not in the libtorch path.

Three things surfaced while reviewing the above and are folded in. pytorch#191625 added
an install rule for the gitignored torch/_rocm_init.py while this was open, in
the same prefix-relative form; it was the last remaining DESTINATION "." in the
tree and is now guarded and addressed like its neighbours. The _C rule's ARCHIVE
clause is dropped: _C is a MODULE library, so no Windows import library is
produced and none ships -- the 2026-08-18 cp312 win_amd64 nightlies carry 13 to
16 .lib files across the cpu, cu126 and xpu variants, every one a genuine C++
import library and no _C.lib among them. It was also the one prefix-relative
destination left in a rule whose other two were absolute.

A lint rule is added so this class of regression is rejected when it is written
rather than after a release. pytorch#191625 is the evidence that it recurs: it landed
three weeks after this fix and nothing caught it, because no CI job installs
standalone and inspects the result -- tools/build_libtorch.py is the only
standalone-install path exercised in CI and it configures with BUILD_PYTHON=OFF,
so it never evaluates these rules. CMAKE_INSTALL_PREFIX_ROOT forbids a
destination of "." across the build system; CMAKE_PLATLIB_DESTINATION
additionally requires every destination in the two package-data files to name
the wheel tree, which catches the prefix-relative variant. Both reuse the
existing grep_linter adapter and are registered in VERY_FAST_LINTERS in
.spin/cmds.py, which spin requires of every linter. This is a text check, not a
behavioural one: a destination that reaches the prefix root through a variable,
or a new rule that uses the wheel tree but omits its SKBUILD guard, still gets
through.

Test Plan:

All on Linux/CPU unless noted, against the reporter's exact configure from the
issue:

```
cmake -S . -B build-standalone -GNinja \
  -DCMAKE_INSTALL_PREFIX=/tmp/prefix \
  -DATEN_NO_TEST=ON -DBUILD_BINARY=ON -DBUILD_CUSTOM_PROTOBUF=OFF \
  -DBUILD_PYTHON=ON -DBUILD_TEST=OFF -DUSE_OPENMP=ON \
  -DCMAKE_INSTALL_LIBDIR=lib -DUSE_DISTRIBUTED=OFF -DUSE_CUDA=OFF

grep -rhoE '\$\{CMAKE_INSTALL_PREFIX\}/[A-Za-z_./]*' \
  --include=cmake_install.cmake build-standalone/ \
  | sed 's|${CMAKE_INSTALL_PREFIX}/||' | cut -d/ -f1 | sort -u
grep -rh --include=cmake_install.cmake 'CMAKE_INSTALL_PREFIX}/\."' build-standalone/
grep -rh --include=cmake_install.cmake "DESTINATION \"$PWD" build-standalone/
grep -rhE --include=cmake_install.cmake 'DESTINATION "(/torch|/torchgen)' build-standalone/
```

Before: `. bin csrc _dynamo _export _inductor include lib share testing utils`,
plus seven rules with destinations inside the source checkout. After:
`bin include lib share`, and the other three greps empty. The last one checks
that an unset SKBUILD_PLATLIB_DIR has not turned a destination into an absolute
path at the filesystem root. The greps must recurse over every
cmake_install.cmake, not just the top-level one, since several of the offending
rules live in subdirectory scopes.

Same configure with -DUSE_CUDA=ON -DUSE_DISTRIBUTED=ON -DUSE_NCCL=ON
-DUSE_NCCL_EP=ON -DUSE_SYSTEM_NCCL=ON: the _nccl_ep target is still built (it
appears in build.ninja, producing torch/_nccl_ep.cpython-310-x86_64-linux-gnu.so)
but contributes no install rule, and the prefix root stays clean.

The guard, exercised the way it can actually regress -- by changing install-dir
in pyproject.toml to something other than "torch" and building a wheel -- fails
configure with the FATAL_ERROR, reporting platlib, the expected prefix and the
actual one.

Wheel contents, via scikit-build-core:

```
pip install -e . -v --no-build-isolation   # twice, consecutively
python -c "import torch, torchgen.packaged, functorch; print(torch.__version__)"
```

Both builds succeed, each configure picking up its own staging directory. The
installed file list under site-packages is identical to a pre-change build of
the same base: 9679 files, none gained or lost, including the mirrored copies
that exist only in the install tree (valgrind.h/callgrind.h, torchgen/packaged
with native_functions.yaml, tags.yaml, 42 templates and 16 autograd files) and
the generated version.py, _C, 43 .pyi stubs and 20 jinja templates. import and
a matmul both work.

The new lint rules, checked in both directions -- clean on this tree, and
flagging the real regressions on the pre-fix tree:

```
spin lint -- --take CMAKE_INSTALL_PREFIX_ROOT,CMAKE_PLATLIB_DESTINATION
```

CMAKE_INSTALL_PREFIX_ROOT flags 6 lines on the pre-fix tree -- torch/CMakeLists.txt
474, 475, 517, 548 and 555, plus cmake/PackageData.cmake:21 -- where 555 is the
pytorch#191625 _rocm_init.py rule, so the check demonstrably rejects the regression that
actually happened. CMAKE_PLATLIB_DESTINATION flags 12.

Lint:

```
lintrunner -a --take CMAKE,NEWLINE,SPACES,TABS,CODESPELL,COPYRIGHT,EXEC \
  CMakeLists.txt cmake/FileMirroring.cmake cmake/PackageData.cmake \
  cmake/Summary.cmake torch/CMakeLists.txt .lintrunner.toml .spin/cmds.py
```

Not covered: Windows and macOS were not exercised locally; ciflow/binaries is
what covers them.

This change was authored with the assistance of an AI coding assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Fixes pytorch#191102

Pull Request resolved: pytorch#191494
Approved by: https://github.com/atalman
ethanwee1 added a commit to ethanwee1/pytorch that referenced this pull request Oct 14, 2026
TheRock writes torch/_rocm_init.py before ROCm wheel builds; .gitignore
drops it from scikit-build-core's package walk. Add a wheel.exclude
negation so the file is shipped when present (ScottTodd's pyproject.toml
suggestion; same pattern as nativert .py un-excludes).

Alternative to CMake install (pytorch#191625); safe when the file is
absent on non-ROCm builds unlike wheel.force-include.

Fixes ROCm/TheRock#6965
Fixes ROCm/TheRock#6991
ethanwee1 added a commit to ethanwee1/pytorch that referenced this pull request Oct 15, 2026
TheRock writes torch/_rocm_init.py before ROCm wheel builds; .gitignore
drops it from scikit-build-core's package walk. Add a wheel.exclude
negation so the file is shipped when present (ScottTodd's pyproject.toml
suggestion; same pattern as nativert .py un-excludes).

Alternative to CMake install (pytorch#191625); safe when the file is
absent on non-ROCm builds unlike wheel.force-include.

Fixes ROCm/TheRock#6965
Fixes ROCm/TheRock#6991
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged module: rocm AMD GPU support for Pytorch open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Issue] PyTorch nightly builds are missing _rocm_init.py. Windows fails to load c10_hip.dll, Linux fails to load libMIOpen.so.1

7 participants