Skip to content

Set the C++ standard on the exported CMake target. - #190784

Closed
AnthonyBarbier wants to merge 10 commits into
pytorch:mainfrom
graphcore:anthonyb/fix_cpp20
Closed

AnthonyBarbier wants to merge 10 commits into
pytorch:mainfrom
graphcore:anthonyb/fix_cpp20

Conversation

@AnthonyBarbier

@AnthonyBarbier AnthonyBarbier commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

This is needed so that downstream targets inherits the c++20 requirement.

This change propagates the required standard only to CXX translation units; downstream consumers compiling CUDA sources must explicitly set CMAKE_CUDA_STANDARD (for example, to 20), because the Torch target does not propagate a CUDA standard.

Without it, downstream C++ code fails with for example:

pytorch/torch/include/ATen/core/TensorBase.h:1041:5: note: ‘requires’ only available with ‘-std=c++20’ or ‘-fconcepts’ pytorch/torch/include/ATen/core/TensorBase.h:1044:5: error: ‘requires’ does not name a type
1044 |     requires std::is_same_v<T, int64_t>
     |     ^~~~~~~~

This is needed so that downstream targets inherits the c++20 requirement. Without it it fails with for example:

pytorch/torch/include/ATen/core/TensorBase.h:1041:5: note: ‘requires’ only available with ‘-std=c++20’ or ‘-fconcepts’
pytorch/torch/include/ATen/core/TensorBase.h:1044:5: error: ‘requires’ does not name a type
1044 |     requires std::is_same_v<T, int64_t>
     |     ^~~~~~~~
@pytorch-bot

pytorch-bot Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

Copilot AI 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.

Pull request overview

This PR updates the exported CMake package config so downstream projects that consume find_package(Torch) inherit PyTorch’s C++20 requirement via target usage requirements.

Changes:

  • Adds target_compile_features(torch INTERFACE cxx_std_20) to the exported torch CMake target to propagate the C++20 requirement to dependents.

Comment thread cmake/TorchConfig.cmake.in Resolved
@liangel-02
liangel-02 requested review from atalman and malfet July 22, 2026 17:48
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 22, 2026
…E ...), since that is also not ideal for older CMake/imported

  targets. It now uses the older set_property(TARGET torch APPEND PROPERTY INTERFACE_COMPILE_OPTIONS ...) form.
Comment thread cmake/TorchConfig.cmake.in Resolved
@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@Skylion007 Could you please have another look at this PR?

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 21m 6s —— View job


Reviewed — the core change (propagating C++20 via the imported target's INTERFACE properties) is the right fix, but the silent -std=c++20 fallback can downgrade consumers that build at a newer standard, and nothing in CI exercises the new propagation because every in-repo libtorch consumer already pins CXX_STANDARD 20 itself.

Full review of #190784

PR Review: #190784

Summary

Makes the exported torch imported target carry the C++20 requirement as a usage requirement, so downstream find_package(Torch) consumers no longer have to set the standard themselves. The mechanism is correct in the target_compile_features path, but the fallback path changes the semantics from "minimum standard" to "exact pin" and can silently downgrade consumers; and there is no test coverage for the propagation.

Answering the open question in this thread (@Skylion007's "what is our actual minimum CMake?")

The repo minimum (CMakeLists.txt:1, cmake_minimum_required(VERSION 3.27)) is not the constraint that matters here. TorchConfig.cmake is executed by the consumer's CMake, which is whatever version the downstream project uses — PyTorch has no control over it. The relevant in-repo signals for what consumers are expected to run:

  • docs/cpp/source/installing.md:40 — cmake_minimum_required(VERSION 3.18) (the documented example)
  • .ci/pytorch/test_example_code/CMakeLists.txt:1 and aten/src/ATen/test/test_install/CMakeLists.txt:1 — 3.10
  • test/{custom_operator,custom_backend,jit_hooks}/CMakeLists.txt:2 — 3.15

So the guard is genuinely needed, and Copilot's "3.10" is the right floor to design against, not an out-of-date example. Worth noting the guard is implicitly self-consistent: cxx_std_20 and the relaxation that lets target_compile_features be called on an IMPORTED target with INTERFACE both landed in early-3.1x CMake, so any CMake that passes the IN_LIST test also accepts the call on an imported target. That coupling is load-bearing but undocumented — please add a one-line comment saying the IN_LIST guard doubles as the "CMake new enough to accept target_compile_features on an IMPORTED target" check, so a future edit doesn't split them apart. (I was unable to fetch cmake.org from this sandbox to cite exact versionadded numbers — please confirm the two version numbers before relying on this paragraph.)

Code Quality

cmake/TorchConfig.cmake.in:158 — CXX_STANDARD 20 is dead code and now actively misleading. CXX_STANDARD governs how a target's own sources are compiled and is not a usage requirement, so it does nothing on an IMPORTED target, which has no sources. It was already dead before this PR, but the PR adds the real propagation mechanism directly beneath it, so a reader now sees two apparently-redundant standard settings three lines apart and cannot tell which one is load-bearing. Since the fallback chain below exists precisely because CXX_STANDARD does not propagate, keeping both encodes a contradiction. Delete it as part of this PR.

Fix this →

API Design

cmake/TorchConfig.cmake.in:162-166 — the fallback is an exact pin, not a minimum, and can silently downgrade a consumer. target_compile_features(torch INTERFACE cxx_std_20) requests a minimum standard: a consumer that sets CXX_STANDARD 23 keeps C++23. The fallback instead appends a literal -std=c++20 to INTERFACE_COMPILE_OPTIONS, which for such a consumer puts both -std=c++23 (from their CXX_STANDARD) and -std=c++20 (from the interface option) on the same command line. With GCC/Clang the last -std= wins, and COMPILE_OPTIONS are emitted after the CXX_STANDARD-derived language flag — so the consumer is silently dropped to C++20 and any C++23 construct in their own code stops compiling, with no diagnostic pointing at libtorch. That is a worse failure mode than the one this PR fixes, because it is silent rather than a hard error. (I could not reach cmake.org to cite the flag-ordering rule; please verify with make VERBOSE=1 on a C++23 consumer before dismissing this.)

Two behaviours are also conflated in one branch: "CMake is too old to know cxx_std_20" and "cxx_std_20 is absent from CMAKE_CXX_COMPILE_FEATURES for some other reason." At minimum the fallback should be observable — emit a message(STATUS ...) (or AUTHOR_WARNING) saying the standard is being pinned rather than requested, so a downgraded consumer has something to grep for.

cmake/TorchConfig.cmake.in:160-166 — the IN_LIST test also fails when the CXX language is not enabled, and then the MSVC branch is wrong. CMAKE_CXX_COMPILE_FEATURES is only populated once CXX has been enabled by project()/enable_language(CXX). A consumer that calls find_package(Torch) before enabling CXX (or from a C-only project that enables CXX later) gets an empty list on a perfectly modern CMake, so it takes the fallback path — and in that same situation MSVC is also not yet set, so a Windows consumer falls through to else() and gets -std=c++20 handed to cl.exe. Guard the whole block on CXX actually being enabled, e.g. check CMAKE_CXX_COMPILER_LOADED first and skip (or warn) otherwise, rather than falling through to a flag that is wrong for the toolchain.

Consumers compiling .cu translation units are not covered. Both the cxx_std_20 feature and the $<COMPILE_LANGUAGE:CXX>-guarded flag apply only to the CXX language, so a downstream .cu file that includes ATen/core/TensorBase.h still gets nvcc's default host standard and reproduces exactly the error in the PR description. This may be deliberate scope-limiting, but since the PR's stated goal is "downstream targets inherit the c++20 requirement," please either set the CUDA side too (cuda_std_20 / a $<COMPILE_LANGUAGE:CUDA>-guarded -std=c++20) or note the gap in the PR description so the next person hitting it does not assume it is a regression.

Testing

No test exercises the new propagation. Every libtorch consumer built in CI pins the standard itself, so all of them would keep passing if this propagation were reverted or silently broken:

Consumer cmake_minimum_required Pins standard itself? Built in CI
.ci/pytorch/test_example_code/CMakeLists.txt 3.10 CXX_STANDARD 20 (:11) yes (check_binary.sh:153)
test/custom_operator/CMakeLists.txt 3.15 CXX_STANDARD 20 (:17, :24) yes (build.sh:379)
test/jit_hooks/CMakeLists.txt 3.15 CXX_STANDARD 20 (:17) yes (build.sh:392)
test/custom_backend/CMakeLists.txt 3.15 CXX_STANDARD 20 (:17, :21) yes (build.sh:404)
aten/src/ATen/test/test_install/CMakeLists.txt 3.10 CMAKE_CXX_STANDARD 20 not found in CI
test/mobile/custom_build/CMakeLists.txt 3.15 CMAKE_CXX_STANDARD 20 not found in CI

test/jit_hooks is the cheapest lever: drop set_property(TARGET test_jit_hooks PROPERTY CXX_STANDARD 20) at test/jit_hooks/CMakeLists.txt:17 so the target relies solely on what find_package(Torch) propagates. It is a single small executable, it is already built in CI (.ci/pytorch/build.sh:385-396), and its source uses C++20 features via the torch headers, so a broken interface would fail the build immediately. This also converts the PR from "trust me, it works" into something a reverting bisect will catch.

Fix this →

Backward Compatibility

The set_property(... PROPERTY ...) → APPEND PROPERTY change at :167-169 is required — without it the TORCH_CXX_FLAGS block would clobber the standard flag the new block just set. Note that the pre-existing quoting bug is preserved: "${TORCH_CXX_FLAGS}" is appended as a single list element, so if it ever holds more than one space-separated flag the whole string is passed to the compiler as one argument. Nothing in the tree sets TORCH_CXX_FLAGS today (it is only ever consumed, in docs/cpp/source/installing.md:44, docs/cpp/source/faq.md:243, .ci/pytorch/test_example_code/CMakeLists.txt:5), so this is latent rather than live — worth a follow-up, not a blocker for this PR.

Separately: adding a hard C++20 usage requirement will now break consumers who deliberately compile at a lower standard against libtorch headers that happen to work for them. That breakage is intentional and correct (those builds are already UB-adjacent), but it is a behaviour change for anyone currently relying on find_package(Torch) not touching their standard, so it belongs in the PR description.

Recommendation

Request Changes

Blocking: no test exercises the propagation (all CI consumers self-pin), and the fallback silently downgrades a C++23 consumer to C++20 instead of expressing a minimum. Also please drop the dead CXX_STANDARD 20 at :158 and handle the "CXX not yet enabled" case, where the current code hands -std=c++20 to MSVC.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@claude review this again, are the prior issues fixed?

@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Claude finished @AnthonyBarbier's task in 11m 39s —— View job


Re-reviewed: all four blocking items from my previous pass are addressed, and I verified in the CI log that test_jit_hooks.cpp now compiles with -std=gnu++20 purely from the propagated usage requirement — the remaining notes (CUDA .cu consumers, static-libtorch consumers) are documentation-level and non-blocking.

Re-review of #190784 — status of prior issues

Checklist

  • Fetch and diff the current branch state against the merge base
  • Re-check each prior finding against the new code
  • Verify the new test coverage actually exercises the propagation (CI log inspection)
  • Look for issues introduced by the fixes

Prior issues: status

Prior finding Status
Dead/misleading CXX_STANDARD 20 on the imported target Fixed — removed from the set_target_properties call (cmake/TorchConfig.cmake.in:156-158)
Fallback silently downgrades a C++23 consumer with no diagnostic Addressed — message(STATUS ...) at :167 makes the pin observable
IN_LIST test also fails when CXX isn't enabled, and the MSVC branch was then wrong Fixed — CMAKE_CXX_COMPILER_LOADED guard at :161, plus a real /std:c++20 MSVC branch at :169
No test exercises the propagation (all CI consumers self-pinned) Fixed and verified — see below
Consumers compiling .cu TUs not covered Not addressed (non-blocking, see below)
"${TORCH_CXX_FLAGS}" list-quoting bug Pre-existing, untouched, still latent (nothing in-tree sets it) — correctly left for a follow-up

Verification of the new test coverage

test/jit_hooks/CMakeLists.txt:19-20 no longer sets CXX_STANDARD, so the target's standard now comes only from find_package(Torch). This is a genuine regression test: test_jit_hooks.cpp includes torch/script.h, which pulls in aten/src/ATen/core/TensorBase.h:1030-1054 where eight requires-clauses live — exactly the construct in the PR description. Revert the propagation and this build fails.

I confirmed it works rather than assuming it, by reading the linux-jammy-py3.10-gcc11 / build log for commit 45e855c8 (job 94837413098):

7095: [ 50%] Building CXX object CMakeFiles/test_jit_hooks.dir/test_jit_hooks.cpp.o
7096: ... -std=gnu++20 ...

-std=gnu++20 on that line, with no CXX_STANDARD anywhere in that project, is direct evidence the target_compile_features(torch INTERFACE cxx_std_20) path fired and propagated. The full pull workflow is green (4/4 runs, 0 failures).

The IN_LIST guard's dual role is now documented at :162, which was my other ask. On the two version numbers in that comment: I still can't reach cmake.org from this sandbox to cite the versionadded notes, but they match my recollection (cxx_std_20 in 3.12; INTERFACE-scope target_* on IMPORTED targets in 3.11), and the ordering claim — that the feature name is the later addition, so testing for it also proves the call is accepted — holds either way. Treat the parenthetical numbers as unverified-but-plausible; the logic doesn't depend on them being exact.

Remaining gaps (non-blocking, but worth a line in the PR description)

1. .cu translation units in downstream projects are still uncovered. Both cxx_std_20 and the $<COMPILE_LANGUAGE:CXX>-guarded fallback apply only to CXX, so a downstream .cu file including ATen/core/TensorBase.h still gets nvcc's default host standard and reproduces the original error. Note that in-repo this is masked: cmake/public/cuda.cmake:56-60 sets CMAKE_CUDA_STANDARD from CMAKE_CXX_STANDARD and is pulled in via Caffe2Config.cmake.in:84 — but that reads the consumer's CMAKE_CXX_STANDARD, which is now exactly the variable consumers no longer have to set. So a consumer who drops their own CXX_STANDARD (as test/jit_hooks just did) and compiles CUDA gets CMAKE_CUDA_STANDARD set from an empty value. That interaction is the sharper edge here, not the missing cuda_std_20 per se.

Fix this →

2. Static libtorch consumers get nothing. The propagation only reaches consumers who link the torch target. In the shared path that happens (TorchConfig.cmake.in:63, set(TORCH_LIBRARIES torch ...)), but the static path at :65-116 never puts torch into TORCH_LIBRARIES — it appends resolved archive paths via append_wholearchive_lib_if_found. A static-libtorch consumer doing the documented target_link_libraries(app "${TORCH_LIBRARIES}") still needs to set the standard by hand. Pre-existing asymmetry (INTERFACE_INCLUDE_DIRECTORIES is equally unused there), so not this PR's job to fix, but the PR description shouldn't imply static consumers are covered.

3. find_package(Torch) before enable_language(CXX) now silently no-ops. Strictly better than the old behaviour of handing -std=c++20 to cl.exe, but the consumer gets the original hard error with no hint as to why. An AUTHOR_WARNING in the else() of the CMAKE_CXX_COMPILER_LOADED check would close that, and it costs nothing for the overwhelmingly common case. Your call.

Also worth doing separately

docs/cpp/source/faq.md:237 still tells users to set_property(TARGET my_app PROPERTY CXX_STANDARD 17) in the "undefined references" fix. That was already wrong (libtorch headers need C++20), and now it is actively harmful advice: with this PR a consumer who follows it downgrades themselves to 17 and reintroduces the exact requires error. docs/cpp/source/installing.md:48 correctly says 20 but is now redundant. Both are docs-only and could go in this PR or a follow-up.

Fix this →

Recommendation

Prior blocking issues resolved. The mechanism is right, the fallback is now observable and toolchain-correct, and there is real CI coverage that a revert would break. Nothing left that I'd block on — I'd just ask you to note the CUDA and static-libtorch scope limits in the PR description so the next person hitting either doesn't file it as a regression.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@Skylion007 All the comments should now have been addressed.

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review

@claude

claude Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 10m 22s —— View job


Re-reviewed the current branch state: the mechanism is right and the prior blocking items stay fixed, but the fallback else() branch misdiagnoses a C++20-incapable compiler as an old CMake, and the two documentation/CUDA gaps flagged last round are still open.

Review of #190784

PR Review: #190784

Summary

Makes the exported torch imported target carry C++20 as a usage requirement so find_package(Torch) consumers inherit it, with test/jit_hooks converted into a regression test by dropping its own CXX_STANDARD. The mechanism is correct; remaining problems are a misdiagnosing fallback branch, an unaddressed CUDA-standard interaction that this PR's premise makes newly reachable, and docs that now actively contradict the propagated requirement.

Code Quality

cmake/TorchConfig.cmake.in:163-172 — the guard tests compiler capability, but the diagnostic and comment both blame CMake's version. CMAKE_CXX_COMPILE_FEATURES is populated from the detected compiler's capabilities, not from CMake's own vocabulary alone. So cxx_std_20 is missing from that list in two distinct situations: CMake too old to know the name, and a compiler that genuinely cannot do C++20 (e.g. GCC 8 under a current CMake). The comment at :162 and the message at :167 ("CMake does not report cxx_std_20 support") only describe the first. In the second case the else() branch pins -std=c++20 onto a compiler that will reject the flag outright, so the consumer gets error: unrecognized command line option '-std=c++20' attributed to a torch usage requirement, rather than a clear "your compiler is too old for libtorch."

Since you are already emitting a message() here, make it say what was actually observed and what the consequence is — something like "the CXX compiler does not report cxx_std_20; forcing -std=c++20. If your compiler predates C++20 support this build will fail." That costs one line and turns a confusing compiler error into a self-explanatory one. Note this is a reasoning-from-semantics finding, not a doc-cited one: I could not reach cmake.org from this sandbox to quote cmake-compile-features(7), so please sanity-check the "compiler-capability-dependent" premise before rewording.

Fix this →

Infrastructure

Downstream CUDA consumers now get an unset CUDA standard — this is sharper than it was before the PR. cmake/public/cuda.cmake:57-59, reached from cmake/Caffe2Config.cmake.in:84, does:

if("X${CMAKE_CUDA_STANDARD}" STREQUAL "X" )
  set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD})
endif()
set(CMAKE_CUDA_STANDARD_REQUIRED ON)

It derives the CUDA standard from the consumer's CMAKE_CXX_STANDARD — which is exactly the variable this PR's whole purpose is to stop requiring consumers to set. When it is unset, set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD}) expands to set(CMAKE_CUDA_STANDARD), which unsets the variable rather than assigning an empty string, so .cu translation units silently fall back to nvcc's default host standard (C++17 for CUDA 12.6+, per the floor at cuda.cmake:73-75) and reproduce the exact requires-clause error in the PR description. test/jit_hooks demonstrates the pattern: it just dropped its CXX_STANDARD, and any consumer who follows that example while compiling CUDA lands here.

Both the cxx_std_20 feature and the $<COMPILE_LANGUAGE:CXX>-guarded fallback are CXX-only, so nothing in this PR covers it. This was raised last round and is still open. Either extend the block to CUDA (cuda_std_20 when present in CMAKE_CUDA_COMPILE_FEATURES, else a $<COMPILE_LANGUAGE:CUDA>-guarded flag), or state the CXX-only scope in the PR description so the next person to hit it doesn't file it as a regression caused by this change.

Fix this →

API Design

docs/cpp/source/faq.md:237 tells consumers to do the one thing that now breaks them. The "Linker errors with undefined references" fix block still recommends set_property(TARGET my_app PROPERTY CXX_STANDARD 17). That was already wrong given the requires-clauses in aten/src/ATen/core/TensorBase.h, but this PR makes it worse: the documented remedy for one problem now downgrades the consumer below the standard the torch target propagates, reintroducing the precise error this PR exists to fix. docs/cpp/source/installing.md:48's CXX_STANDARD 20 is merely redundant now, but leaving it in place while test/jit_hooks/CMakeLists.txt:15-16 tells readers the opposite ("intentionally doesn't set CXX_STANDARD") is an inconsistency a consumer will trip over. This is a two-line docs change and belongs in this PR, since it is this PR that turns stale advice into harmful advice.

Fix this →

Testing

The else() fallback at :166-172 has no CI coverage on any path. Every consumer build in CI runs a CMake new enough and a compiler capable enough that cxx_std_20 is present, so only the target_compile_features branch is ever taken — I confirmed the three consumer projects are configured identically at .ci/pytorch/build.sh:370, :383, :395 (all against the shared wheel via CMAKE_PREFIX_PATH="$SITE_PACKAGES"), and Windows never builds jit_hooks at all (.ci/pytorch/win-test.sh:60,70 runs only test_custom_backend.bat). So the new /std:c++20 MSVC line in particular is written-but-never-executed. Not blocking — deliberately exercising a stale-CMake path isn't worth a CI job — but it does mean the correctness of both fallback lines rests entirely on review, which is worth knowing when weighing the diagnostic wording above.

For the propagation path itself the new coverage is real: test/jit_hooks/CMakeLists.txt no longer sets a standard and test_jit_hooks.cpp includes torch/script.h, so a broken interface fails that build. I also verified the removal cannot break the static-libtorch case, because the static branch at cmake/TorchConfig.cmake.in:65-116 never puts the torch target into TORCH_LIBRARIES (it appends resolved archive paths), so jit_hooks never received INTERFACE_INCLUDE_DIRECTORIES there either and that combination does not occur in CI.

Backward Compatibility

"${TORCH_CXX_FLAGS}" at :176 is still appended as a single list element, so a multi-flag value would reach the compiler as one argument. Nothing in the tree assigns TORCH_CXX_FLAGS (it is only ever consumed — docs/cpp/source/installing.md:44, docs/cpp/source/faq.md:243, .ci/pytorch/test_example_code/CMakeLists.txt:5), so this stays latent and pre-existing. Worth noting only for the new adjacency: because the block now runs after the standard is set and uses APPEND, a consumer who puts a -std= into TORCH_CXX_FLAGS wins over the propagated C++20. Follow-up, not this PR.

Recommendation

Approve

The prior blocking items remain resolved and CI is green (4/4 runs, 0 failures). Nothing here blocks merge, but I'd ask for the two cheap changes before landing: reword the fallback diagnostic at :167 so it names the compiler rather than CMake, and fix docs/cpp/source/faq.md:237, which this PR converts from stale into actively harmful. The CUDA scope limit needs either a fix or a line in the PR description.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

Comment thread cmake/TorchConfig.cmake.in Resolved
TorchConfig hardcoded C++20 even though the standard used to configure
PyTorch can be overridden. Substitute the build-time CMAKE_CXX_STANDARD in
the exported compile feature, diagnostic, and compatibility flags so the
package consistently propagates the configured requirement.

Test Plan:

```
spin quicklint
lintrunner -a
cmake -P agent_space/check_torch_config_standard.cmake
git diff --check
```

Authored with assistance from Codex, an AI coding assistant.
CMAKE_CXX_COMPILE_FEATURES depends on both CMake's feature vocabulary and
the detected compiler's capabilities. Describe both reasons that the
configured standard may be absent and warn that forcing the standard flag
will fail when the compiler is too old.

Test Plan:

```
spin quicklint
lintrunner -a
git diff --check
```

Authored with assistance from Codex, an AI coding assistant.
The FAQ forced consumers to C++17, which conflicts with Torch's C++20
header requirements, while the installation guide redundantly forced
C++20. Remove both overrides now that the exported Torch target propagates
its configured minimum standard.

Test Plan:

```
spin quicklint
lintrunner -a
git diff --check
```

Authored with assistance from Codex, an AI coding assistant.
@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@claude review this again, are the prior issues fixed?

@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Claude finished @AnthonyBarbier's task in 5m 10s —— View job


Re-reviewed: all four items I flagged last round are fixed, and the new @CMAKE_CXX_STANDARD@ templating is a correct answer to @Skylion007's "don't hardcode it" question — the one thing left is torch.compiler_aot_inductor.md:151, which still carries the same stale CXX_STANDARD 17 advice that this PR just removed from faq.md.

Re-review of #190784 — status of prior issues

Checklist

  • Diff current branch against origin/main
  • Re-check each prior finding against the new code
  • Verify the new standard-configurability mechanism (answering @Skylion007's latest comment)
  • Look for issues introduced by the fixes
  • Post verdict

Prior issues: status

Prior finding Status
Fallback diagnostic blamed CMake's version when the guard actually tests compiler capability Fixed — comment at :162 now names both causes; message at :167 says "The CXX compiler does not report cxx_std_20 support" and warns the build will fail on a pre-C++20 compiler
docs/cpp/source/faq.md:237 recommended CXX_STANDARD 17 — advice this PR made wrong Fixed — removed; installing.md:48's redundant CXX_STANDARD 20 also removed
CUDA .cu consumers uncovered Addressed as documented scope — PR description now states consumers compiling CUDA must set CMAKE_CUDA_STANDARD themselves. That was the ask (fix or document); see the note below on why documenting is defensible here
Hardcoded 20 (@Skylion007's review comment) Fixed — see next section
Dead CXX_STANDARD 20 on the imported target; CMAKE_CXX_COMPILER_LOADED guard; MSVC /std:c++20 branch; test/jit_hooks regression coverage Still fixed from earlier rounds — no regressions in this diff
"${TORCH_CXX_FLAGS}" single-list-element quoting Pre-existing, untouched, still latent (nothing in-tree assigns it) — correctly left for a follow-up

Answering @Skylion007's review comment: "instead of hard coding can we set it to whatever torch is currently set to?"

Yes, and that is what b97f8ff1 now does. I traced the substitution end to end:

  • CMakeLists.txt:128-131 sets CMAKE_CXX_STANDARD as a CACHE STRING defaulting to 20, so a builder can override it with -DCMAKE_CXX_STANDARD=23.
  • caffe2/CMakeLists.txt:1483-1486 runs configure_file(... TorchConfig.cmake.in ... @ONLY), and because the root sets the cache variable before add_subdirectory(caffe2), the value is visible there.
  • Every occurrence in cmake/TorchConfig.cmake.in:163-171 — the IN_LIST probe, the target_compile_features call, the diagnostic text, and both fallback flags — is now @CMAKE_CXX_STANDARD@, so the exported config always reports the standard PyTorch was actually built with. grep confirms caffe2/CMakeLists.txt is the only place this template is configured, so there is no second path that could bake in a different value.

To your parenthetical ("or that doesn't work because these are out-of-tree usages?") — the distinction that matters is when the value is captured. Reading the consumer's CMake cache would not work, since it is a different cache; but capturing PyTorch's value at its configure time and freezing it into the generated TorchConfig.cmake does, and that is the standard mechanism for exported package configs. Substitution, not runtime lookup, is the right tool here.

One edge case, non-blocking: if CMAKE_CXX_STANDARD were ever empty at configure time, the template would emit a bare cxx_std_ and -std=c++. That cannot currently happen because line 128 always assigns a default, so no guard is needed — worth knowing only if someone later converts that to a plain set(... CACHE ...) without a default.

New observations from this diff

docs/source/user_guide/torch_compiler/torch.compiler_aot_inductor.md:151 still has the pattern you just deleted from faq.md. That AOTInductor example does find_package(Torch REQUIRED) (:140), target_link_libraries(aoti_example "${TORCH_LIBRARIES}") (:150), then set_property(TARGET aoti_example PROPERTY CXX_STANDARD 17). It is the same shape as the faq.md:237 line this PR removes, for the same reason, and it is the last copy left in the docs.

To be precise about severity — and to correct an overstatement in my earlier reviews: on the target_compile_features path this is not a live break. cxx_std_20 is a minimum, and CMake raises a target whose CXX_STANDARD is lower than a required feature, so the consumer still compiles at C++20 and the set_property is simply inert and misleading. It only becomes wrong-looking rather than wrong. (I could not reach cmake.org from this sandbox to quote cmake-compile-features(7) on the raise-to-satisfy rule, so treat that as reasoning from semantics.) Still worth deleting in this PR, since leaving one doc telling readers to pin 17 while test/jit_hooks/CMakeLists.txt:15-16 tells them the standard is deliberately inherited is exactly the inconsistency the other two doc edits set out to remove.

Fix this →

On documenting rather than fixing the CUDA gap — I think that is the right call, and here is the reason it is safe. cmake/public/cuda.cmake:57-59 (reached via cmake/Caffe2Config.cmake.in:84) does if("X${CMAKE_CUDA_STANDARD}" STREQUAL "X") set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD}), i.e. it derives the CUDA standard from the consumer's CMAKE_CXX_STANDARD — now expected to be unset. But that if guard means a consumer who does set CMAKE_CUDA_STANDARD, exactly as the PR description now instructs, is never overwritten. So the documented workaround is actually load-bearing and not just a disclaimer. Extending the block to cuda_std_@CMAKE_CXX_STANDARD@ would still be a nicer end state, but it is a strictly additive follow-up, not a gap this PR opens.

Fallback still has no CI coverage on any path (every CI consumer runs a CMake and compiler where cxx_std_20 is present, and Windows never builds jit_hooks — .ci/pytorch/win-test.sh runs only test_custom_backend.bat). Unchanged from last round and still not worth a CI job; noted only because the correctness of the two set_property lines rests entirely on review.

find_package(Torch) before enable_language(CXX) still silently no-ops (the else() of :161 is empty). You marked this "your call" last round and left it — fine by me; a no-op is strictly better than the old behaviour of handing -std=c++20 to cl.exe.

CI

The regression test is intact: test/jit_hooks/CMakeLists.txt sets no standard and test_jit_hooks.cpp includes torch/script.h, which pulls in the eight requires-clauses at aten/src/ATen/core/TensorBase.h:1029-1054, so a broken interface fails that build. I previously confirmed -std=gnu++20 on the test_jit_hooks.cpp.o compile line for commit 45e855c8 with no CXX_STANDARD in that project. The current push is still running (BC Lint green; pull, Lint, docs-build in progress) — the three commits since then touch only the template's substituted values and two doc lines, so I would expect it to stay green, but the pull result is the thing to confirm before landing.

Recommendation

Approve — all prior blocking items are resolved and the hardcoding question is answered properly. The only thing I would still ask for in this PR is deleting CXX_STANDARD 17 from torch.compiler_aot_inductor.md:151, since it is the last doc that contradicts the other two you just fixed. Wait for pull to finish before merging.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@claude review this again, are the prior issues fixed?

@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Claude finished @AnthonyBarbier's task in 2m 33s —— View job


Re-reviewed: the one item I asked for last round is done, and the whole pull run is now green — nothing blocking left, just one nit about a rationale comment that got dropped in 040b6c48.

Re-review of #190784 — status of prior issues

Checklist

  • Diff current branch against the merge base (67abb0be)
  • Re-check each prior finding against the new code
  • Look for issues introduced by the fixes
  • Check CI status
  • Post verdict

Prior issues: status

Prior finding Status
torch.compiler_aot_inductor.md:151 still pinned CXX_STANDARD 17 — the last doc contradicting the other two Fixed (dd2239b7) — line removed; target_link_libraries(aoti_example "${TORCH_LIBRARIES}") at :150 is now the last line of the example
Fallback diagnostic blamed CMake's version when the guard tests compiler capability Fixed (040b6c48) — message at :167 now says "The CXX compiler does not report cxx_std_@CMAKE_CXX_STANDARD@ support" and warns the build will fail on a pre-C++20 compiler
faq.md:237 / installing.md:48 stale CXX_STANDARD advice Fixed (ea4fd940)
Hardcoded 20 (@Skylion007's ask) Fixed (b97f8ff1) — all five occurrences templated
Dead CXX_STANDARD 20 on the imported target; CMAKE_CXX_COMPILER_LOADED guard; MSVC /std: branch; test/jit_hooks regression coverage Still fixed from earlier rounds; untouched by this diff
"${TORCH_CXX_FLAGS}" single-list-element quoting (:176) Pre-existing, untouched, still latent — nothing in-tree assigns it; correctly left for a follow-up

I also swept for any remaining doc/test example that pins a standard while consuming find_package(Torch). The only surviving CXX_STANDARD in a .md file is CONTRIBUTING.md:1176, and that one is correct as-is — it is a standalone two-library MSVC linking demo (project(myproject CXX), no find_package(Torch)), so it needs to set its own standard and is unaffected by this PR. test/custom_operator, test/custom_backend, test/mobile/custom_build and torch_openreg still self-pin, which is fine: test/jit_hooks is the deliberate canary and keeping the others pinned means a propagation break produces one clearly-attributable failure rather than four.

One nit introduced by 040b6c48

cmake/TorchConfig.cmake.in:162 — the reworded comment gained the two-causes explanation but lost the reason the IN_LIST guard is load-bearing. It previously read:

# cxx_std_20 (CMake 3.12) postdates INTERFACE support on IMPORTED targets (3.11), so this also guards the call below.

and now reads only:

# The feature can be absent because CMake does not recognize it or the compiler does not support the standard.

Both sentences are true and neither subsumes the other. The deleted one documents why the guard cannot be simplified or reordered — the IN_LIST test is doubling as the "CMake is new enough to accept target_compile_features on an IMPORTED target" check, which is exactly the kind of non-local coupling a comment should preserve. The templating doesn't invalidate it either: every plausible @CMAKE_CXX_STANDARD@ here (20/23/26) has a feature name postdating 3.11, so the argument still holds. Worth restoring as a second line. (As before, I can't reach cmake.org from this sandbox to cite the exact versionadded numbers, so treat the 3.11/3.12 parenthetical as unverified-but-plausible — the ordering claim is what matters and it holds either way.)

Fix this →

On the @CMAKE_CXX_STANDARD@ templating

I traced the substitution again after the reword and it is still sound: CMakeLists.txt:128-131 sets the cache default to 20, the root sets it before add_subdirectory(caffe2), and caffe2/CMakeLists.txt:1483-1486 is the only configure_file for this template (grep confirms no second path), so the exported config always reports the standard PyTorch was actually built with.

Two consequences worth being aware of, neither blocking:

  • A builder who configures with -DCMAKE_CXX_STANDARD=23 now exports cxx_std_23 as a usage requirement, i.e. consumers are raised to the standard torch was built with rather than the minimum its headers need (20). Given ABI coupling between libtorch and its consumers that is arguably the safer default, and it is exactly what was asked for — just noting the requirement is "match the build" not "at least 20".
  • The degenerate -DCMAKE_CXX_STANDARD= (explicitly empty) case would emit a bare cxx_std_ / -std=c++. Unreachable today because line 128 always supplies a default; only relevant if someone later removes it.

CI

All 4 workflow runs green (pull, Lint, BC Lint, docs-build, 0 failures) as of run 33162820184 — this is the pull result I asked you to wait for last round, so that condition is now satisfied.

The regression test is intact: test/jit_hooks/CMakeLists.txt sets no standard (with the intent documented at :15-16) and test_jit_hooks.cpp includes torch/script.h, which pulls in the requires-clauses in aten/src/ATen/core/TensorBase.h, so a broken interface fails that build. I previously confirmed -std=gnu++20 on the test_jit_hooks.cpp.o compile line with no CXX_STANDARD in that project; the four commits since then only change the template's substituted values and three doc lines, so that evidence still applies.

Unchanged and still fine: the fallback else() branch has no CI coverage on any path (every CI consumer has a CMake and compiler where cxx_std_20 is present, and Windows never builds jit_hooks), and find_package(Torch) before enable_language(CXX) silently no-ops. Both were noted and consciously accepted in earlier rounds.

Recommendation

Approve. Every prior blocking item is resolved, the hardcoding question is answered properly, and CI is fully green. The only outstanding thing is the optional comment restoration at :162 — a one-line docs-in-code change I'd be happy to see either in this PR or not at all.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@Skylion007 Should be all good now I think?

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 1, 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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (pr_time_benchmarks, 1, 1, mt-l-bx86iavx512-94-344-t4-8)

Details for Dev Infra team Raised by workflow job

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@claude identify merge failure. Is it related to this PR?

@claude

claude Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Claude finished @AnthonyBarbier's task in 2m 9s —— View job


Merge failure: unrelated to this PR

  • Pull the failing job's log (pr_time_benchmarks on trunk / linux-jammy-cuda13.0-py3.10-gcc11)
  • Determine the failure mode
  • Assess whether this PR's changes could plausibly cause it
  • Post verdict

Short answer: no, it is not related. The merge was blocked by a stale pr_time_benchmarks baseline — a compile-time benchmark came in faster than its recorded expectation by 10.01%, tripping a ±10.00% window by one hundredth of a percent.

Analysis of the merge failure

The failing check

trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (pr_time_benchmarks, 1, 1) exited 1. Exactly one assertion in the whole job failed (log line 8072):

WIN: benchmark ('add_loop_eager_dynamic', 'compile_time_instruction_count') failed,
actual result 4920824903 is -10.01% lower than expected 5468000000 +/-10.00%
please OPEN THE TEST RESULTS update ALL BENCHMARKS RESULT with the new printed expected results.

Every other benchmark in the job passed, and the job reported Compilation failures 0 (log lines 8340, 8368). The trailing ##[error]Executing the custom container implementation failed at line 8387 is the runner's generic wrapper message after the script's exit 1, not a separate infra failure — the preceding line explicitly says "This is a script/workflow error".

Why this is a "WIN", not a regression

benchmarks/dynamo/pr_time_benchmarks/check_results.py:158-170 fails the job in the result < low branch as well as the result > high one. A WIN means the measured Dynamo compile-time instruction count dropped below the recorded baseline — i.e. compilation got cheaper than expected_results.csv claims it should be. The harness treats that as a failure purely to force the baseline to be refreshed, so the noise window doesn't silently widen and mask a future regression.

The margin is as thin as it gets: -10.01% against a ±10.00% window. One more instruction and it would have passed.

Why it cannot be caused by this PR

This PR touches four files, and none of them are on any code path the benchmark executes:

cmake/TorchConfig.cmake.in                                          (exported CMake package config)
docs/cpp/source/faq.md                                              (markdown)
docs/cpp/source/installing.md                                       (markdown)
docs/source/user_guide/torch_compiler/torch.compiler_aot_inductor.md (markdown)

cmake/TorchConfig.cmake.in is configure_file-d into the installed TorchConfig.cmake and is only ever read by a downstream find_package(Torch). It contributes nothing to PyTorch's own compilation — no source file, no compile flag on any PyTorch translation unit, no Python bytecode. add_loop_eager_dynamic measures instruction counts inside torch._dynamo while tracing an eager loop; there is no mechanism by which an exported CMake usage requirement or three deleted markdown lines could move that number at all, let alone by 10%.

What actually happened

benchmarks/dynamo/pr_time_benchmarks/expected_results.csv:5 still reads:

add_loop_eager_dynamic,compile_time_instruction_count,5468000000,0.1

and git log shows that file was last touched on 2026-08-24 (63e23d59), well before this PR's merge base (b4bd4b79). So a genuine compile-time improvement landed on main in the intervening week and nobody refreshed this row. The baseline drifted just far enough that any PR merging through that window has a coin-flip chance of tripping it. The job itself prints the corrected value it wants (log line 8173): add_loop_eager_dynamic,compile_time_instruction_count,4920000000,0.1.

That also explains the timing: this same PR's pull run was fully green in the earlier round, and pr_time_benchmarks runs on trunk, not pull, so it was first exercised by the merge attempt rather than by the PR's own CI.

Suggested next step

Two options, both cheap:

  1. Retry the merge ignoring the unrelated failure — @pytorchbot merge -i. Appropriate here since the failure is a stale-baseline WIN in a benchmark this PR cannot influence.
  2. Wait and retry plain @pytorchbot merge — someone will land the expected_results.csv refresh on main (these get updated routinely), after which the check goes green on its own.

I would not add the CSV update to this PR: check_results.py tells you to update all significantly-changed rows, not just the failing one, and doing that from an unrelated CMake PR would mix a benchmark-baseline change into a packaging fix, and its correctness would depend on this one job's measurement.

| Branch: [`anthonyb/fix_cpp20`](https://github.com/pytorch/pytorch/tree/anthonyb/fix_cpp20)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
This is needed so that downstream targets inherits the c++20 requirement.

This change propagates the required standard only to CXX translation units; downstream consumers compiling CUDA sources must explicitly set CMAKE_CUDA_STANDARD (for example, to 20), because the Torch target does not propagate a CUDA standard.

Without it, downstream C++ code fails with for example:

```
pytorch/torch/include/ATen/core/TensorBase.h:1041:5: note: ‘requires’ only available with ‘-std=c++20’ or ‘-fconcepts’ pytorch/torch/include/ATen/core/TensorBase.h:1044:5: error: ‘requires’ does not name a type
1044 |     requires std::is_same_v<T, int64_t>
     |     ^~~~~~~~
```
Pull Request resolved: pytorch#190784
Approved by: https://github.com/Skylion007
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 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.

6 participants