Skip to content

Forward cross-compilation toolchain variables before project() - #190003

Closed
CodersAcademy006 wants to merge 2 commits into
pytorch:mainfrom
CodersAcademy006:riscv/cmake-cross-var-before-project
Closed

CodersAcademy006 wants to merge 2 commits into
pytorch:mainfrom
CodersAcademy006:riscv/cmake-cross-var-before-project

Conversation

@CodersAcademy006

Copy link
Copy Markdown
Contributor

Fixes a cross-compilation regression: target CMAKE_SYSTEM_NAME / CMAKE_SYSTEM_PROCESSOR passed via the environment are silently dropped, so the build configures for the host architecture.

Root cause

CMake requires CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR to be set before project() in order to enter cross-compile mode and report the target architecture.

#177640 moved environment variable handling out of setup.py into cmake/EnvVarForwarding.cmake. That file is included at CMakeLists.txt:24, which is after project(Torch CXX C) at CMakeLists.txt:13. It forwards a variable only when it is not already defined (EnvVarForwarding.cmake:61,68):

if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var})

By line 24 project() has already defined the toolchain variables to their host values, so the guard skips them and the target values from the environment are lost. Architecture guards downstream (for example the {Q,X}NNPACK selection in cmake/Dependencies.cmake) then evaluate against the host and build host kernels while cross-compiling.

Before #177640 these were passed as -D arguments from setup.py, which took effect at project() time. This restores that behavior.

Why it went unnoticed

This only affects true cross-compilation. Architectures that build natively under emulation never rely on the forwarded triplet, so their CI stays green.

Reproduction

Minimal, isolated, mirroring the include order and the skip-if-defined guard. Host is arm64, environment sets CMAKE_SYSTEM_PROCESSOR=riscv64 CMAKE_SYSTEM_NAME=Linux:

forwarding position CMAKE_SYSTEM_PROCESSOR CMAKE_CROSSCOMPILING
after project() (current) arm64 (env dropped) FALSE
before project() (this PR) riscv64 TRUE
before project(), no env set arm64 FALSE

The change

Forward only the toolchain-determining variables before project(). Every assignment is guarded by DEFINED ENV{...} AND NOT DEFINED ..., so this is a no-op for native builds (third row above) and does not override anything already passed via -D or a toolchain file. EnvVarForwarding.cmake keeps handling everything else, unchanged.

Validation

Verified against current main that the ordering issue is still present and that no other change forwards these variables before project(). Mechanism verified with the isolated reproduction above (cmake 4.3.4), including the native no-op case. Downstream effect previously observed on a riscv64 cross configure: with the fix cmake correctly reports Target architecture "riscv64" is not supported in {Q/X}NNPACK and disables them, instead of silently selecting host kernels. A full riscv64 cross build is gated on separate, unrelated blockers, so CI here is the build gate.

Refs #180975

cc @zklaus (author of #177640) @luhenry @malfet

CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR must be set before project()
for CMake to enter cross-compile mode and report the target architecture.

pytorch#177640 moved environment variable handling out of setup.py and into
cmake/EnvVarForwarding.cmake, which CMakeLists.txt includes at line 24,
after project() at line 13. That file only forwards a variable when it is
not already defined, and project() has by then defined the toolchain
variables to their host values, so target values passed via the environment
are silently dropped. The build then configures for the host: architecture
guards such as the one in cmake/Dependencies.cmake select host kernels while
cross-compiling.

This only affects true cross-compilation. Architectures that build natively
under emulation are unaffected, which is why it went unnoticed.

Forward just the toolchain-determining variables before project(). This is a
no-op for native builds, where none of these are set in the environment.
@pytorch-bot

pytorch-bot Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures, 1 Unrelated Failure

As of commit 45723b5 with merge base 2398dc2 (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@ezyang

ezyang commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

@claude Mmm, I'm not too sure about this. In particular I'm worried this is not put in the right spot and it could interfere with other build configs. Is the claimed test strategy sufficient?

@claude

claude Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 5m 12s —— View job


Assessment of @ezyang's concerns

@ezyang I dug into the placement and interference questions. Short version: the placement is correct and, I'd argue, unavoidable — but your instinct about the test strategy is right, it's the weak part. Details below.

Is it in the right spot? (yes — and it has to be)

The variables CMAKE_SYSTEM_NAME / CMAKE_SYSTEM_PROCESSOR are consumed by CMake during project() — that is when it decides cross-compile vs. native and probes the toolchain. If they aren't set before project(Torch CXX C) (CMakeLists.txt:32), the target values can't take effect at all. So "before project()" is the only spot that works; there isn't a more conservative placement available.

I confirmed the failure mode is real end-to-end:

  • The generic forwarder (cmake/EnvVarForwarding.cmake:68) guards with if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var}), and it's include()d at CMakeLists.txt:43, after project().
  • By then project() has already defined CMAKE_SYSTEM_* to host values, so the guard skips them — the env values are dropped. Verified the ordering still holds on this branch.
  • Downstream this genuinely bites: the QNNPACK/XNNPACK guard at cmake/Dependencies.cmake:383 keys off CMAKE_SYSTEM_PROCESSOR, so a dropped triplet silently selects host kernels. The claim in the PR body checks out.
Interference risk with other build configs (low — the guard is doing its job)

The new loop uses the same DEFINED ENV{...} AND NOT DEFINED ... guard, so it's a no-op unless the variable comes from the environment and isn't already set. Walking the configs CI actually uses:

  • Native builds (all normal x86/arm CI): none of these six vars are in the env → no-op. This is the vast majority of what CI exercises.
  • Android / iOS: scripts/build_android.sh / build_ios.sh pass -DCMAKE_TOOLCHAIN_FILE=... on the command line, so it's already DEFINED → skipped. No interference.
  • setup.py / scikit-build path: anything passed as -D is already defined → skipped.
  • riscv64 cross (.ci/pytorch/build.sh:97-99): exports CMAKE_SYSTEM_NAME/PROCESSOR in the env — this is exactly the case the PR fixes.
  • Reconfigure: after the first configure the values live in the CMake cache → DEFINED → skipped. Idempotent.

Two minor notes, neither blocking:

  1. The new code uses plain set() while EnvVarForwarding.cmake uses set(... CACHE STRING ... FORCE). It works (for CMAKE_SYSTEM_*, project() populates the cache itself, and the later generic loop skips them since they're now defined), but the plain-var vs. cache-var inconsistency is slightly surprising to a reader.
  2. The list of six is not exhaustive for all cross scenarios (e.g. CMAKE_SYSTEM_VERSION, CMAKE_OSX_*, CMAKE_ASM_COMPILER, CMAKE_ANDROID_*). Fine for the targeted riscv fix, but if the goal is "restore the pre-Move environment variable handling from setup.py to CMake #177640 behavior generally," those went through as -D before too. Worth a comment noting the list is intentionally the cross-compile-critical subset.
Is the test strategy sufficient? (this is the real gap)

This is where I share your skepticism. The PR's "CI here is the build gate" claim is weaker than it sounds:

  • .github/workflows/riscv64.yml only triggers on ciflow/riscv64/* tags or workflow_dispatch — it does not run on ordinary PRs. So this PR's normal CI never exercises the cross-compile path.
  • For everything CI does run (native builds), this change is a guaranteed no-op. So green CI here tells you only "didn't break native builds" — it does not verify the fix.
  • The actual fix is validated by (a) an isolated out-of-tree cmake reproduction and (b) a one-off manual riscv64 configure observation. That's reasonable evidence the mechanism works, but nothing in-repo will catch a future regression of this exact ordering bug.

Suggestions to make the change trustworthy without a full cross build:

  1. Trigger the ciflow/riscv64 job on this PR (tag it) so the cross configure at least runs and reports the QNNPACK/XNNPACK "not supported in riscv64 → disabled" message — that's the cheapest real end-to-end signal short of a full build.
  2. Consider a tiny configure-time regression guard: e.g. when cross-compiling, assert CMAKE_SYSTEM_PROCESSOR matches the requested target and message(FATAL_ERROR) otherwise. That converts the silent-host-fallback into a loud failure and would have caught the original Move environment variable handling from setup.py to CMake #177640 regression.

Bottom line: the change itself is correct and low-risk. The gap is that the automated verification is effectively absent for the code path being fixed — I'd want at least the riscv64 ciflow run to go green before merging on confidence rather than on the isolated repro alone.

Summary: Placement is correct and necessary, interference risk with other build configs is low (the guard keeps it a no-op for native/-D/toolchain-file builds). The weak spot is exactly the test strategy — this PR's regular CI never runs the cross-compile path, so green CI doesn't verify the fix; I'd recommend running the ciflow/riscv64 job and ideally adding a configure-time cross-compile sanity assert.

@janeyx99
janeyx99 requested review from atalman and zklaus July 17, 2026 21:40
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 17, 2026

@ezyang ezyang 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.

suuuuuure

@ezyang ezyang added the mergedog mergedog is watching this PR label Jul 21, 2026
@ezyang

ezyang commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 21, 2026
Clean merge with origin/main; no conflicts.
@pytorch-bot

pytorch-bot Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@ezyang

ezyang commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot 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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

@ezyang

ezyang commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

mergedog handoff

All CI is green (or skipped). Ready for human review and @pytorchbot merge.

Current PR head: 8fe9a31173ea820b470d02c18cace6b02c9e46ed.

Autonomous changes pushed

  • 45723b522df2 — merged main into the PR branch after LLM requested rebase: [MERGEDOG] Merge main into PR branch

CI notes at handoff

mergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:

  • linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64)
  • linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1)
  • linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1)

Warning: mergedog's suppressed check list differs from the latest Dr. CI summary.

Suppressed by mergedog but not marked unrelated by Dr. CI:

  • linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64)
  • linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1)
Latest Dr. CI summary
## :link: Helpful Links
### :test_tube: See artifacts and rendered test results at [hud.pytorch.org/pr/190003](https://hud.pytorch.org/pr/190003)
* :page_facing_up: Preview [Python docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/190003/index.html)
* :page_facing_up: Preview [C++ docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/190003/cppdocs/index.html)
* :question: Need help or want to give feedback on the CI? Visit the [bot commands wiki](https://github.com/pytorch/pytorch/wiki/Bot-commands)

Note: Links to docs will display an error until the docs builds have been completed.
## :heavy_exclamation_mark: 1 Active SEVs
There are 1 currently active SEVs.   If your PR is affected, please view them below:
* [Unrelated MacOS MPS test jobs time out (30 min) due to stale cpp_extension lock file poisoning self-hosted runners](https://hud.pytorch.org/pytorch/pytorch/issues/190674)



## :x: 2 New Failures, 1 Pending, 1 Unrelated Failure
As of commit 45723b522df2b052816be1c2b231ab5e27674fab with merge base 2398dc208d25137064d165f8b3d15c5a02c58383 (<sub><sub><img alt="image" width=70 src="https://img.shields.io/date/1784610416?label=&color=FFFFFF&style=flat-square"></sub></sub>):
<details open><summary><b>NEW FAILURES</b> - The following jobs have failed:</summary><p>

* [pull / linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64)](https://hud.pytorch.org/pr/pytorch/pytorch/190003#88657716077) ([gh](https://github.com/pytorch/pytorch/actions/runs/29836573490/job/88657716077))
    `[OSDC] Step script exited with code 1. This is a script/workflow error, not an infrastructure issue. Check the step logs above for the actual failure.`
  <details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/190003#88657716077"><img alt="AI verdict: infra issue" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=45723b522df2b052816be1c2b231ab5e27674fab&job=pull+%2F+linux-jammy-py3.10-gcc11+%2F+test+%28distributed%2C+8%2C+8%2C+mt-l-x86iamx-8-64%29"></a></summary><blockquote>

  The job failed due to a runner-container-hooks crash (`TypeError: Cannot read properties of null (reading &#39;jobPod&#39;)`), which is a Kubernetes CI infrastructure failure unrelated to any code change.

  <a href="https://hud.pytorch.org/pr/pytorch/pytorch/190003#88657716077">Full reasoning on HUD &rarr;</a>
  </blockquote></details>
* [trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1)](https://hud.pytorch.org/pr/pytorch/pytorch/190003#88661776940) ([gh](https://github.com/pytorch/pytorch/actions/runs/29836825978/job/88661776940))
    `test/test_ops.py::TestMathBitsCUDA::test_conj_view_masked_prod_cuda_complex64`
  <details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/190003#88661776940"><img alt="AI verdict: not related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=45723b522df2b052816be1c2b231ab5e27674fab&job=trunk+%2F+linux-jammy-rocm-py3.10-mi350+%2F+test+%28default%2C+1%2C+8%2C+linux.rocm.gpu.gfx950.1%29"></a></summary><blockquote>

  The PR only adds CMake cross-compilation variable forwarding that is explicitly a no-op for native builds. It cannot cause a numerical test failure in a ROCm complex64 math operation. The ROCm MI350/gfx950 platform shows general instability across trunk runs.

  <a href="https://hud.pytorch.org/pr/pytorch/pytorch/190003#88661776940">Full reasoning on HUD &rarr;</a>
  </blockquote></details>
</p></details>
<details ><summary><b>FLAKY</b> - The following job failed but was likely due to flakiness present on trunk:</summary><p>

* [trunk / linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1)](https://hud.pytorch.org/pr/pytorch/pytorch/190003#88661776943) ([gh](https://github.com/pytorch/pytorch/actions/runs/29836825978/job/88661776943)) ([similar failure](https://hud.pytorch.org/pytorch/pytorch/commit/c2e8f386a80ec7ca9d36f30353e479412b5bb8d1#88320062418))
    `test/test_ops.py::TestCommonCUDA::test_out_requires_grad_error_nanquantile_cuda_float32`
</p></details>


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

During shepherding, the configured LLM was invoked 4 times. If any CI shows red, it judged that failure unrelated to this PR's changes — please verify below before merging.

Session 1 — fix-CI (2026-07-21T13:53:41+00:00)

  • Before: 8fe9a31173ea
  • Verdict: exited with a contract violation — failing jobs: linux-jammy-py3.10-gcc11 / test (backwards_compat, 1, 1, mt-l-x86iavx512-8-64)
LLM transcript

Session 2 — fix-CI (2026-07-21T14:53:57+00:00)

  • Before: 45723b522df2
  • Verdict: judged failures spurious (no commit) — failing jobs: linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1); rationale: linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1): test/test_ops.py::TestCommonCUDA::test_out_requires_grad_error_nanquantile_cuda_float32 failed with CUDA driver error 401 while launching a Triton kernel. This is a transient ROCm GPU/driver failure unrelated to this PR's CMake cross-compilation variable forwarding.
LLM transcript

Session 3 — fix-CI (2026-07-21T14:58:07+00:00)

  • Before: 45723b522df2
  • Verdict: judged failures spurious (no commit) — failing jobs: linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1); rationale: linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1) is unrelated to this PR's CMake cross-compilation variable forwarding. TestMathBitsCUDA.test_conj_view_masked_prod_cuda_complex64 fails consistently with CUDA driver error 401 in a ROCm JIT reduction launch, indicating a runner/driver failure rather than an effect of the CMake-only change.
LLM transcript

Session 4 — fix-CI (2026-07-21T16:12:55+00:00)

  • Before: 45723b522df2
  • Verdict: judged failures spurious (no commit) — failing jobs: linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64); rationale: linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64): The runner pod never came online, remaining Pending with CreateContainerError until the container-hook backoff timeout. No test ran and the failure is unrelated infrastructure provisioning.
LLM transcript

@ezyang

ezyang commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 3 checks: pull / linux-jammy-py3.10-gcc11 / test (distributed, 8, 8, mt-l-x86iamx-8-64), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi350 / test (inductor, 1, 2, linux.rocm.gpu.gfx950.1)

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

youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#190003)

Fixes a cross-compilation regression: target `CMAKE_SYSTEM_NAME` / `CMAKE_SYSTEM_PROCESSOR` passed via the environment are silently dropped, so the build configures for the host architecture.

## Root cause

CMake requires `CMAKE_SYSTEM_NAME` and `CMAKE_SYSTEM_PROCESSOR` to be set **before** `project()` in order to enter cross-compile mode and report the target architecture.

pytorch#177640 moved environment variable handling out of `setup.py` into `cmake/EnvVarForwarding.cmake`. That file is included at `CMakeLists.txt:24`, which is **after** `project(Torch CXX C)` at `CMakeLists.txt:13`. It forwards a variable only when it is not already defined (`EnvVarForwarding.cmake:61,68`):

```cmake
if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var})
```

By line 24 `project()` has already defined the toolchain variables to their **host** values, so the guard skips them and the target values from the environment are lost. Architecture guards downstream (for example the `{Q,X}NNPACK` selection in `cmake/Dependencies.cmake`) then evaluate against the host and build host kernels while cross-compiling.

Before pytorch#177640 these were passed as `-D` arguments from `setup.py`, which took effect at `project()` time. This restores that behavior.

## Why it went unnoticed

This only affects **true** cross-compilation. Architectures that build natively under emulation never rely on the forwarded triplet, so their CI stays green.

## Reproduction

Minimal, isolated, mirroring the include order and the skip-if-defined guard. Host is `arm64`, environment sets `CMAKE_SYSTEM_PROCESSOR=riscv64 CMAKE_SYSTEM_NAME=Linux`:

| forwarding position | `CMAKE_SYSTEM_PROCESSOR` | `CMAKE_CROSSCOMPILING` |
| --- | --- | --- |
| after `project()` (current) | `arm64` (env dropped) | `FALSE` |
| before `project()` (this PR) | `riscv64` | `TRUE` |
| before `project()`, no env set | `arm64` | `FALSE` |

## The change

Forward only the toolchain-determining variables before `project()`. Every assignment is guarded by `DEFINED ENV{...} AND NOT DEFINED ...`, so this is a **no-op for native builds** (third row above) and does not override anything already passed via `-D` or a toolchain file. `EnvVarForwarding.cmake` keeps handling everything else, unchanged.

## Validation

Verified against current `main` that the ordering issue is still present and that no other change forwards these variables before `project()`. Mechanism verified with the isolated reproduction above (cmake 4.3.4), including the native no-op case. Downstream effect previously observed on a riscv64 cross configure: with the fix cmake correctly reports `Target architecture "riscv64" is not supported in {Q/X}NNPACK` and disables them, instead of silently selecting host kernels. A full riscv64 cross build is gated on separate, unrelated blockers, so CI here is the build gate.

Refs pytorch#180975

Pull Request resolved: pytorch#190003
Approved by: https://github.com/ezyang

Co-authored-by: Edward Z. Yang via mergedog <[email protected]>
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#190003)

Fixes a cross-compilation regression: target `CMAKE_SYSTEM_NAME` / `CMAKE_SYSTEM_PROCESSOR` passed via the environment are silently dropped, so the build configures for the host architecture.

## Root cause

CMake requires `CMAKE_SYSTEM_NAME` and `CMAKE_SYSTEM_PROCESSOR` to be set **before** `project()` in order to enter cross-compile mode and report the target architecture.

pytorch#177640 moved environment variable handling out of `setup.py` into `cmake/EnvVarForwarding.cmake`. That file is included at `CMakeLists.txt:24`, which is **after** `project(Torch CXX C)` at `CMakeLists.txt:13`. It forwards a variable only when it is not already defined (`EnvVarForwarding.cmake:61,68`):

```cmake
if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var})
```

By line 24 `project()` has already defined the toolchain variables to their **host** values, so the guard skips them and the target values from the environment are lost. Architecture guards downstream (for example the `{Q,X}NNPACK` selection in `cmake/Dependencies.cmake`) then evaluate against the host and build host kernels while cross-compiling.

Before pytorch#177640 these were passed as `-D` arguments from `setup.py`, which took effect at `project()` time. This restores that behavior.

## Why it went unnoticed

This only affects **true** cross-compilation. Architectures that build natively under emulation never rely on the forwarded triplet, so their CI stays green.

## Reproduction

Minimal, isolated, mirroring the include order and the skip-if-defined guard. Host is `arm64`, environment sets `CMAKE_SYSTEM_PROCESSOR=riscv64 CMAKE_SYSTEM_NAME=Linux`:

| forwarding position | `CMAKE_SYSTEM_PROCESSOR` | `CMAKE_CROSSCOMPILING` |
| --- | --- | --- |
| after `project()` (current) | `arm64` (env dropped) | `FALSE` |
| before `project()` (this PR) | `riscv64` | `TRUE` |
| before `project()`, no env set | `arm64` | `FALSE` |

## The change

Forward only the toolchain-determining variables before `project()`. Every assignment is guarded by `DEFINED ENV{...} AND NOT DEFINED ...`, so this is a **no-op for native builds** (third row above) and does not override anything already passed via `-D` or a toolchain file. `EnvVarForwarding.cmake` keeps handling everything else, unchanged.

## Validation

Verified against current `main` that the ordering issue is still present and that no other change forwards these variables before `project()`. Mechanism verified with the isolated reproduction above (cmake 4.3.4), including the native no-op case. Downstream effect previously observed on a riscv64 cross configure: with the fix cmake correctly reports `Target architecture "riscv64" is not supported in {Q/X}NNPACK` and disables them, instead of silently selecting host kernels. A full riscv64 cross build is gated on separate, unrelated blockers, so CI here is the build gate.

Refs pytorch#180975

Pull Request resolved: pytorch#190003
Approved by: https://github.com/ezyang

Co-authored-by: Edward Z. Yang via mergedog <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#190003)

Fixes a cross-compilation regression: target `CMAKE_SYSTEM_NAME` / `CMAKE_SYSTEM_PROCESSOR` passed via the environment are silently dropped, so the build configures for the host architecture.

## Root cause

CMake requires `CMAKE_SYSTEM_NAME` and `CMAKE_SYSTEM_PROCESSOR` to be set **before** `project()` in order to enter cross-compile mode and report the target architecture.

pytorch#177640 moved environment variable handling out of `setup.py` into `cmake/EnvVarForwarding.cmake`. That file is included at `CMakeLists.txt:24`, which is **after** `project(Torch CXX C)` at `CMakeLists.txt:13`. It forwards a variable only when it is not already defined (`EnvVarForwarding.cmake:61,68`):

```cmake
if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var})
```

By line 24 `project()` has already defined the toolchain variables to their **host** values, so the guard skips them and the target values from the environment are lost. Architecture guards downstream (for example the `{Q,X}NNPACK` selection in `cmake/Dependencies.cmake`) then evaluate against the host and build host kernels while cross-compiling.

Before pytorch#177640 these were passed as `-D` arguments from `setup.py`, which took effect at `project()` time. This restores that behavior.

## Why it went unnoticed

This only affects **true** cross-compilation. Architectures that build natively under emulation never rely on the forwarded triplet, so their CI stays green.

## Reproduction

Minimal, isolated, mirroring the include order and the skip-if-defined guard. Host is `arm64`, environment sets `CMAKE_SYSTEM_PROCESSOR=riscv64 CMAKE_SYSTEM_NAME=Linux`:

| forwarding position | `CMAKE_SYSTEM_PROCESSOR` | `CMAKE_CROSSCOMPILING` |
| --- | --- | --- |
| after `project()` (current) | `arm64` (env dropped) | `FALSE` |
| before `project()` (this PR) | `riscv64` | `TRUE` |
| before `project()`, no env set | `arm64` | `FALSE` |

## The change

Forward only the toolchain-determining variables before `project()`. Every assignment is guarded by `DEFINED ENV{...} AND NOT DEFINED ...`, so this is a **no-op for native builds** (third row above) and does not override anything already passed via `-D` or a toolchain file. `EnvVarForwarding.cmake` keeps handling everything else, unchanged.

## Validation

Verified against current `main` that the ordering issue is still present and that no other change forwards these variables before `project()`. Mechanism verified with the isolated reproduction above (cmake 4.3.4), including the native no-op case. Downstream effect previously observed on a riscv64 cross configure: with the fix cmake correctly reports `Target architecture "riscv64" is not supported in {Q/X}NNPACK` and disables them, instead of silently selecting host kernels. A full riscv64 cross build is gated on separate, unrelated blockers, so CI here is the build gate.

Refs pytorch#180975

Pull Request resolved: pytorch#190003
Approved by: https://github.com/ezyang

Co-authored-by: Edward Z. Yang via mergedog <[email protected]>
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
…ch#190003)

Fixes a cross-compilation regression: target `CMAKE_SYSTEM_NAME` / `CMAKE_SYSTEM_PROCESSOR` passed via the environment are silently dropped, so the build configures for the host architecture.

## Root cause

CMake requires `CMAKE_SYSTEM_NAME` and `CMAKE_SYSTEM_PROCESSOR` to be set **before** `project()` in order to enter cross-compile mode and report the target architecture.

pytorch#177640 moved environment variable handling out of `setup.py` into `cmake/EnvVarForwarding.cmake`. That file is included at `CMakeLists.txt:24`, which is **after** `project(Torch CXX C)` at `CMakeLists.txt:13`. It forwards a variable only when it is not already defined (`EnvVarForwarding.cmake:61,68`):

```cmake
if(DEFINED ENV{${_var}} AND NOT DEFINED ${_var})
```

By line 24 `project()` has already defined the toolchain variables to their **host** values, so the guard skips them and the target values from the environment are lost. Architecture guards downstream (for example the `{Q,X}NNPACK` selection in `cmake/Dependencies.cmake`) then evaluate against the host and build host kernels while cross-compiling.

Before pytorch#177640 these were passed as `-D` arguments from `setup.py`, which took effect at `project()` time. This restores that behavior.

## Why it went unnoticed

This only affects **true** cross-compilation. Architectures that build natively under emulation never rely on the forwarded triplet, so their CI stays green.

## Reproduction

Minimal, isolated, mirroring the include order and the skip-if-defined guard. Host is `arm64`, environment sets `CMAKE_SYSTEM_PROCESSOR=riscv64 CMAKE_SYSTEM_NAME=Linux`:

| forwarding position | `CMAKE_SYSTEM_PROCESSOR` | `CMAKE_CROSSCOMPILING` |
| --- | --- | --- |
| after `project()` (current) | `arm64` (env dropped) | `FALSE` |
| before `project()` (this PR) | `riscv64` | `TRUE` |
| before `project()`, no env set | `arm64` | `FALSE` |

## The change

Forward only the toolchain-determining variables before `project()`. Every assignment is guarded by `DEFINED ENV{...} AND NOT DEFINED ...`, so this is a **no-op for native builds** (third row above) and does not override anything already passed via `-D` or a toolchain file. `EnvVarForwarding.cmake` keeps handling everything else, unchanged.

## Validation

Verified against current `main` that the ordering issue is still present and that no other change forwards these variables before `project()`. Mechanism verified with the isolated reproduction above (cmake 4.3.4), including the native no-op case. Downstream effect previously observed on a riscv64 cross configure: with the fix cmake correctly reports `Target architecture "riscv64" is not supported in {Q/X}NNPACK` and disables them, instead of silently selecting host kernels. A full riscv64 cross build is gated on separate, unrelated blockers, so CI here is the build gate.

Refs pytorch#180975

Pull Request resolved: pytorch#190003
Approved by: https://github.com/ezyang

Co-authored-by: Edward Z. Yang via mergedog <[email protected]>
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 18, 2026
…d suffix

Since pytorch#180243 the torch._C extension is built by CMake via
Python_add_library(_C MODULE WITH_SOABI ...). WITH_SOABI names the module using
Python_SOABI, which CMake's FindPython only computes by running the interpreter
when NOT cross-compiling: under CMAKE_CROSSCOMPILING the query is skipped unless
CMAKE_CROSSCOMPILING_EMULATOR is set (policy CMP0190), so Python_SOABI is left
empty and WITH_SOABI silently emits an untagged _C.so.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so import torch._C fails. This is the conda-forge
linux-aarch64 failure in pytorch-cpu-feedstock pytorch#526. (When this was first
diagnosed the symptom was different: setup.py collected the extension via
package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}", the untagged name
did not match, and _C was dropped from the wheel entirely. pytorch#180248 has since
removed setup.py and _C is collected by install(TARGETS _C ...) in
torch/CMakeLists.txt, so it now ships under the wrong name rather than going
missing. Either way the target cannot import it.)

pytorch#190003 has since widened which builds hit this. It forwards CMAKE_SYSTEM_NAME
and CMAKE_SYSTEM_PROCESSOR from the environment before project(), so a cross
setup that passes them that way now genuinely enters cross-compile mode. Such a
build previously stayed in native mode -- CMAKE_CROSSCOMPILING FALSE, and
FindPython computed Python_SOABI normally -- and so never produced an untagged
module. It now takes the empty-SOABI path as well, which makes this fix the
completion of that one rather than a conda-forge-only concern.

CMake's sanctioned cross path (CMP0190 + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when Python_SOABI is empty while
cross-compiling, we query SOABI from the interpreter (which crossenv answers with
the target's value) and set it once, right where FindPython resolves the
Development.Module component. Every downstream WITH_SOABI consumer (_C, and the
CUDA-only _nccl_ep) then gets the correct suffix, and WITH_SOABI still composes
the platform-specific filename.

The override deliberately only fills an *empty* Python_SOABI. A non-empty value is
authoritative and left untouched: with an emulator FindPython ran the target
interpreter to compute it, whereas this bare invocation would run the wrong
interpreter (or fail to exec the target binary), so it must not second-guess a
value FindPython already produced. The empty case is both unambiguous and the
actual failure observed (an untagged _C.so).

This overrides Python_SOABI centrally rather than each target's SUFFIX because
FindPython recomputes Python_SOABI on every find_package(Python), so a manual
value only survives if nothing re-finds Python afterwards. That holds here: the
last find is in this file, the override runs right after it, and the only later
use of FindPython -- cmake/public/cuda.cmake, re-included from torch/CMakeLists.txt
under USE_CUDA to hash libnvrtc -- is short-circuited on that second entry by the
already-computed CUDA_NVRTC_SHORTHASH. So the override is not threatened by a
lingering find_package and lands independently.

An alternative considered was passing -DPython_SOABI=...; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

Authored with assistance from Claude Code.

Test Plan:
Confirmed in a standalone FindPython project that (a) a non-empty Python_SOABI is
preserved and only an empty one takes the override path, and (b) setting
Python_SOABI before the Python_add_library calls (no intervening find_package)
drives the suffix of every WITH_SOABI module:

```
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

This equals f"_C{EXT_SUFFIX}" since EXT_SUFFIX == "." + SOABI + shared-module
suffix on Linux/macOS targets. Native builds are unchanged (the CMAKE_CROSSCOMPILING
guard is not taken; FindPython's Python_SOABI already equals EXT_SUFFIX there).

The pytorch#190003 interaction was checked separately on the same standalone project
(cmake 3.28.3), reproducing the empty-SOABI condition from both directions:

```
# native, no toolchain vars
cmake -S . -B b1                                   # CROSSCOMPILING=FALSE  SOABI=cpython-310-x86_64-linux-gnu
# env vars WITHOUT the pytorch#190003 forwarding block (pre-pytorch#190003 behaviour)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
                                                   # CROSSCOMPILING=FALSE  SOABI=cpython-310-x86_64-linux-gnu
# env vars WITH the forwarding block (post-pytorch#190003)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
                                                   # CROSSCOMPILING=TRUE   SOABI=''
# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
                                                   # CROSSCOMPILING=TRUE   SOABI=''
```

End-to-end validation is a conda-forge linux-aarch64 build
(pytorch-cpu-feedstock pytorch#526), where import torch._C succeeds.
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
…d suffix (#189388)

## Summary

Since #180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of #190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since #189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The #190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT #190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

Pull Request resolved: #189388
Approved by: https://github.com/isuruf, https://github.com/jeffdaily
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…d suffix (pytorch#189388)

## Summary

Since pytorch#180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
pytorch#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

pytorch#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of pytorch#190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since pytorch#189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The pytorch#190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT pytorch#190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

Pull Request resolved: pytorch#189388
Approved by: https://github.com/isuruf, https://github.com/jeffdaily
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…d suffix (pytorch#189388)

## Summary

Since pytorch#180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
pytorch#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

pytorch#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of pytorch#190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since pytorch#189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The pytorch#190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT pytorch#190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

Pull Request resolved: pytorch#189388
Approved by: https://github.com/isuruf, https://github.com/jeffdaily
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 Merged mergedog mergedog is watching this PR open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants