Skip to content

Apply one precedence rule to all forwarded build env vars - #201666

Closed
zklaus wants to merge 2 commits into
pytorch:mainfrom
zklaus:build-config-precedence
Closed

zklaus wants to merge 2 commits into
pytorch:mainfrom
zklaus:build-config-precedence

Conversation

@zklaus

@zklaus zklaus commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Go through the following checklist

  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • Included benchmark results (for PRs impacting perf)

Linked issue or supporting maintainer

Part of #201664

BC-breaking?

No. One behavior change for existing build directories: a BLAS, MKL_THREADING or CUDNN_* value exported in the shell now re-applies on every build and overwrites a ccmake edit of that entry, as USE_* and BUILD_* already did since #188242.

Summary (human written only)

This PR homogenizes the treatment of configure options for the Pytorch build.
It is part of #201664, implementing most of the necessary changes that are not covered in other PRs or dependent on future changes.

Agent details (if applicable)

Drafted with Claude Code; diff and commit message reviewed by hand. The commit message follows.

cmake/EnvVarForwarding.cmake forwarded its variables with two different semantics. Names matched by prefix (BUILD_, USE_, CMAKE_) have overridden the cache on every configure since #188242, so changing USE_CUDA in the environment takes effect on the next build. The names in the passthrough and alias lists (BLAS, TORCH_CUDA_ARCH_LIST, CUDNN_, MKL_THREADING, ...) still used the original seed-only loop, guarded by NOT DEFINED, so they were written once and then ignored: changing BLAS in the environment did nothing to an existing build directory, and -D beat the environment for these names while losing to it for the prefixed ones.

This change routes the passthrough names and all aliases through the same envfwd_apply the prefix names use, so one rule holds for every knob: environment variables win over -D / cmake.define, those win over pyproject.toml, and all three win over what the build directory remembers. For developers this means a BLAS, MKL_THREADING or CUDNN* value exported in the shell now re-applies on every build, overwriting a ccmake edit of that entry, exactly as USE_* and BUILD_* already did. The _ENV_ALIASES and _LOW_PRIORITY_ALIASES lists collapse into one, with a single semantics: an alias applies only when its canonical name is not itself in the environment, and where several aliases name the same variable the first listed one wins. Among the aliases, the only observable difference is that a canonical name now beats its alias when both are set (CUDNN_LIBRARY over CUDNN_LIB_DIR); no CI job sets both. As a consequence of going through _envfwd_apply, the passthrough and alias names are now also recorded in env_forwarded.txt, so the native-AOT stage-2 drift check covers them, as its docstring already claimed.

The alternative, restoring flags-over-environment for the prefixed names instead, was rejected: scikit-build-core resolves its own and every declared config-setting as environment > -C > default, and a project cannot invert that, so flags-over-environment could not have been delivered uniformly. #200651 binds torch.blas and torch.cuda-arch-list to these names and documents that the bound environment variable takes precedence over the setting; that sentence is only true under this rule, so that PR rebases on this one.

The README "Adjust Build Options" and CONTRIBUTING "subsequent builds" paragraphs stated the old seed-only behavior and now state the rule; the EnvVarForwarding header carries it too.

Test Plan

tools/test/test_env_var_forwarding.py configures a NONE-language CMake project that includes the module and asserts the four tiers for a prefix name and for BLAS (environment over -D, environment over cache, cache kept when the environment is silent, -D over cache), plus canonical-over-alias, alias-over-cache, first-listed-alias-wins and the drift-file recording. Against the unmodified module four of the eight tests fail, exactly the BLAS and alias cases.

python -m pytest tools/test/test_env_var_forwarding.py -q
lintrunner -a cmake/EnvVarForwarding.cmake tools/test/test_env_var_forwarding.py tools/native_aot/build_stage2.py README.md CONTRIBUTING.md

Every commit that touched the module since its introduction was traced to its PR and checked against the new semantics; each CMake-side write to a forwarded variable is either a non-FORCE default or a normal-variable shadow, both of which behave the same under either semantics.

Authored with an AI assistant; the diff was reviewed by hand.

🤖 Generated with Claude Code

cc @malfet

@pytorch-bot

pytorch-bot Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

🔗 Helpful Links

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

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

✅ No Failures

As of commit 705c998 with merge base cbee633 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@zklaus
zklaus marked this pull request as ready for review October 21, 2026 21:22
@zklaus zklaus added module: build Build system issues release notes: releng release notes category labels Oct 22, 2026
@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 29, 2026
@atalman

atalman commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @atalman's task in 2m 6s —— View job


The routing change works as described. The new precedence rule doesn't hold yet for TORCH_CUDA_ARCH_LIST, the main knob #200651 builds on, so I'm recommending changes.

Full review

PR Review: #201666

Summary

This PR sends the passthrough and alias env vars through _envfwd_apply, so one precedence rule (env > -D > pyproject.toml > cache) covers every forwarded name. It also merges the two alias lists and documents the rule. No REVIEW.md applies. Problems: the documented rule is false for TORCH_CUDA_ARCH_LIST, and one docstring in build_stage2.py is stale.

API Design

  • The documented rule doesn't hold for TORCH_CUDA_ARCH_LIST.
    • The cause is cmake/Dependencies.cmake:1494, which runs set(TORCH_CUDA_ARCH_LIST $ENV{TORCH_CUDA_ARCH_LIST}) whenever NOT INTERN_BUILD_MOBILE. It does this even when the env var is unset.
    • So with no env var, -DTORCH_CUDA_ARCH_LIST=8.0 (or a cached value) is shadowed by an empty normal variable for the rest of configure. utils.cmake:315 and nccl_ep.cmake:17 then see it as defined, and Codegen.cmake:275 records the empty value.
    • That contradicts "-C flags win over pyproject.toml, and all three win over the cache" in README.md:399, CONTRIBUTING.md:981 and the header at cmake/EnvVarForwarding.cmake:9. The commit message's "one rule holds for every knob" doesn't hold either.
    • It also matters for [build] Expose common build options as PEP 517 config-settings #200651, which binds torch.cuda-arch-list to this name. A -C value with no env var would be silently dropped.
    • Suggested fix: with this PR, the forwarding already FORCEs the env value into the cache, so that line is redundant when the env var is set. Delete it, or guard it with if(DEFINED ENV{TORCH_CUDA_ARCH_LIST}). Then update the _arch_list docstring you edited (tools/native_aot/build_stage2.py:157-160, "an unset one included"), and add a -D-over-cache case for this name to the test.
    • Strictly, the bug predates this PR. But the PR is what documents a universal rule, and it already touches the docstring that describes the shadow.

Code Quality

  • tools/native_aot/build_stage2.py:574-576: the _refuse_settings_drift docstring still says "the names in its alias lists, TORCH_CUDA_ARCH_LIST among them".
    • There is now only one alias list, and TORCH_CUDA_ARCH_LIST is in _ENV_PASSTHROUGH, not in it. It should say "the names in its passthrough and alias lists".
    • The PR updates the _arch_list docstring in the same file but missed this one.

Testing

  • Low confidence: the test skips unless cmake is on PATH (tools/test/test_env_var_forwarding.py:41). It runs in the lint workflow's "Test tools" job on the pytorch-linux-jammy-linter image.
    • I couldn't confirm that image ships a CMake ≥ 3.27. cmake==3.31.6 is in requirements-ci.txt, but I'm not sure the linter image installs it.
    • If it doesn't, all eight tests are silently skipped in CI. Please check the job log for skipped.

Recommendation

Request Changes

Fix the TORCH_CUDA_ARCH_LIST shadow, or document it as an exception. As it stands, the precedence rule this PR documents (and #200651 depends on) is false for that name. Separately, the stale docstring is a small fix. I couldn't run the new test locally: the commands needed approval in this environment.

@atalman

atalman commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Also please verify that test_env_var_forwarding.py‎ is actually called from our test suite

cmake/EnvVarForwarding.cmake forwarded its variables with two different semantics. Names matched by prefix (BUILD_*, USE_*, CMAKE_*) have overridden the cache on every configure since pytorch#188242, so changing USE_CUDA in the environment takes effect on the next build. The names in the passthrough and alias lists (BLAS, TORCH_CUDA_ARCH_LIST, CUDNN_*, MKL_THREADING, ...) still used the original seed-only loop, guarded by NOT DEFINED, so they were written once and then ignored: changing BLAS in the environment did nothing to an existing build directory, and -D beat the environment for these names while losing to it for the prefixed ones.

This change routes the passthrough names and all aliases through the same _envfwd_apply the prefix names use, so one rule holds for every knob: environment variables win over -D / cmake.define, those win over pyproject.toml, and all three win over what the build directory remembers. For developers this means a BLAS, MKL_THREADING or CUDNN_* value exported in the shell now re-applies on every build, overwriting a ccmake edit of that entry, exactly as USE_* and BUILD_* already did. The _ENV_ALIASES and _LOW_PRIORITY_ALIASES lists collapse into one, with a single semantics: an alias applies only when its canonical name is not itself in the environment, and where several aliases name the same variable the first listed one wins. Among the aliases, the only observable difference is that a canonical name now beats its alias when both are set (CUDNN_LIBRARY over CUDNN_LIB_DIR); no CI job sets both. As a consequence of going through _envfwd_apply, the passthrough and alias names are now also recorded in env_forwarded.txt, so the native-AOT stage-2 drift check covers them, as its docstring already claimed.

The alternative, restoring flags-over-environment for the prefixed names instead, was rejected: scikit-build-core resolves its own and every declared config-setting as environment > -C > default, and a project cannot invert that, so flags-over-environment could not have been delivered uniformly. pytorch#200651 binds torch.blas and torch.cuda-arch-list to these names and documents that the bound environment variable takes precedence over the setting; that sentence is only true under this rule, so that PR rebases on this one.

The README "Adjust Build Options" and CONTRIBUTING "subsequent builds" paragraphs stated the old seed-only behavior and now state the rule; the EnvVarForwarding header carries it too.

Test Plan

tools/test/test_env_var_forwarding.py configures a NONE-language CMake project that includes the module and asserts the four tiers for a prefix name and for BLAS (environment over -D, environment over cache, cache kept when the environment is silent, -D over cache), plus canonical-over-alias, alias-over-cache, first-listed-alias-wins and the drift-file recording. Against the unmodified module four of the eight tests fail, exactly the BLAS and alias cases.

```
python -m pytest tools/test/test_env_var_forwarding.py -q
lintrunner -a cmake/EnvVarForwarding.cmake tools/test/test_env_var_forwarding.py tools/native_aot/build_stage2.py README.md CONTRIBUTING.md
```

Every commit that touched the module since its introduction was traced to its PR and checked against the new semantics; each CMake-side write to a forwarded variable is either a non-FORCE default or a normal-variable shadow, both of which behave the same under either semantics.

Authored with an AI assistant; the diff was reviewed by hand.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
`_arch_list` said Dependencies.cmake shadows the cache with the
environment even when the variable is unset. It does not: an unset
`$ENV{}` in `set()` unsets the normal variable and the cache value
shows through. `_refuse_settings_drift` named only the alias lists,
but TORCH_CUDA_ARCH_LIST is a passthrough name.

Both pointed out by the review atalman requested on pytorch#201666.

Test Plan: docstrings only.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@zklaus
zklaus force-pushed the build-config-precedence branch from d07ba4d to 705c998 Compare November 9, 2026 12:56
@zklaus

zklaus commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Verified the two points.

tools/test/test_env_var_forwarding.py runs in the Lint workflow's "Test tools" job (pytest tools/test -o "python_files=test*.py"). That job uses the pytorch-linux-jammy-linter image, which installs requirements-ci.txt and with it cmake==3.31.6, so the cmake skip guard does not fire. On this PR: 8 passed, 0 skipped, see https://github.com/pytorch/pytorch/actions/runs/42621112876/job/129173314223.

On the @claude review: the TORCH_CUDA_ARCH_LIST shadow it describes does not happen. With the variable unset, set(TORCH_CUDA_ARCH_LIST $ENV{TORCH_CUDA_ARCH_LIST}) expands to set(TORCH_CUDA_ARCH_LIST), which unsets the normal variable, and the cache value from -D is visible again for the rest of the configure. Checked with a two-line CMake project, cmake 3.31. The line is redundant now that forwarding FORCEs a set environment value into the cache, but removing it is outside this PR; tracked with the other direct env reads on #201664. The two docstring remarks were correct; fixed in the new commit.

@zklaus

zklaus commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 9, 2026
@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 Nov 11, 2026
The reference this PR moves into CONTRIBUTING.md kept changing in its old
place while the PR waited, so the rebase has to carry those changes over.

pytorch#201666 put every forwarded variable under one precedence rule. The "How
to set them" subsection described the earlier split, where prefix-matched
names overrode the cache and alias and passthrough names only seeded it,
and called it provisional. It now states the single rule: the environment
wins over -C flags, which win over pyproject.toml, and all three win over
the cache; an alias applies only when its canonical name is not set. The
annotations no longer say "seeds the cache only", and the forwarding rule
no longer names the removed _LOW_PRIORITY_ALIASES list. The module header
keeps the short precedence paragraph pytorch#201666 added next to the forwarding
rule.

Five variables were documented in the old comment block or the old
CONTRIBUTING list since the PR's base and are added to the reference:
USE_ROCM_CK_SDPA_GFX11, USE_ROCM_CK_SDPA_GFX12, TORCH_CK_GEMM_ARCH_LIST,
CAFFE2_CUSTOM_PROTOC_EXECUTABLE and TORCH_NATIVE_AOT. The TORCH_NATIVE_AOT
entry is the existing CONTRIBUTING text, moved, with its skip conditions
laid out as a list. The wording of each condition is unchanged, since
test_native_aot_tools.py checks CONTRIBUTING.md for it.

The `spin develop` and `spin install` help texts pointed at the module for
the list of variables, like the README did; they now point at the
reference too.

The reference told readers to delete build/CMakeCache.txt to configure
from scratch, as the old comment block did for the removed CMAKE_FRESH.
It now names `-C cmake.fresh=true`, which scikit-build-core has had since
1.1, the floor here, and which pytorch#201664 names as the reset to document.

Test Plan:

Documentation and help-text change only.

```
lintrunner -a
git grep -n "_LOW_PRIORITY_ALIASES\|seeds the cache"
python -m pytest tools/test/test_native_aot_tools.py -k documented_skip_reasons
```

The grep finds nothing and the test passes. All in-page anchors in
CONTRIBUTING.md resolve, checked with a script that compares every
`](#...)` link against the headings.

`cmake.fresh` was exercised on a toy project with scikit-build-core 1.1.2
and a persistent build-dir, with one cached option MYOPT whose default is
"default". It was not run against a PyTorch build tree.

```
python -m build --wheel --no-isolation -Ccmake.define.MYOPT=first   # first
python -m build --wheel --no-isolation                              # first
python -m build --wheel --no-isolation -Ccmake.fresh=true           # default
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Nov 12, 2026
The reference this PR moves into CONTRIBUTING.md kept changing in its old
place while the PR waited, so the rebase has to carry those changes over.

pytorch#201666 put every forwarded variable under one precedence rule. The "How
to set them" subsection described the earlier split, where prefix-matched
names overrode the cache and alias and passthrough names only seeded it,
and called it provisional. It now states the single rule: the environment
wins over -C flags, which win over pyproject.toml, and all three win over
the cache; an alias applies only when its canonical name is not set. The
annotations no longer say "seeds the cache only", and the forwarding rule
no longer names the removed _LOW_PRIORITY_ALIASES list. The module header
keeps the short precedence paragraph pytorch#201666 added next to the forwarding
rule.

Five variables were documented in the old comment block or the old
CONTRIBUTING list since the PR's base and are added to the reference:
USE_ROCM_CK_SDPA_GFX11, USE_ROCM_CK_SDPA_GFX12, TORCH_CK_GEMM_ARCH_LIST,
CAFFE2_CUSTOM_PROTOC_EXECUTABLE and TORCH_NATIVE_AOT. The TORCH_NATIVE_AOT
entry is the existing CONTRIBUTING text, moved, with its skip conditions
laid out as a list. The wording of each condition is unchanged, since
test_native_aot_tools.py checks CONTRIBUTING.md for it.

The `spin develop` and `spin install` help texts pointed at the module for
the list of variables, like the README did; they now point at the
reference too.

The reference told readers to delete build/CMakeCache.txt to configure
from scratch, as the old comment block did for the removed CMAKE_FRESH.
It now names `-C cmake.fresh=true`, which scikit-build-core has had since
1.1, the floor here, and which pytorch#201664 names as the reset to document.

Test Plan:

Documentation and help-text change only.

```
lintrunner -a
git grep -n "_LOW_PRIORITY_ALIASES\|seeds the cache"
python -m pytest tools/test/test_native_aot_tools.py -k documented_skip_reasons
```

The grep finds nothing and the test passes. All in-page anchors in
CONTRIBUTING.md resolve, checked with a script that compares every
`](#...)` link against the headings.

`cmake.fresh` was exercised on a toy project with scikit-build-core 1.1.2
and a persistent build-dir, with one cached option MYOPT whose default is
"default". It was not run against a PyTorch build tree.

```
python -m build --wheel --no-isolation -Ccmake.define.MYOPT=first   # first
python -m build --wheel --no-isolation                              # first
python -m build --wheel --no-isolation -Ccmake.fresh=true           # default
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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 module: build Build system issues open source release notes: releng release notes 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