Skip to content

Try to enable LTO in OSS - #180186

Closed
Skylion007 wants to merge 13 commits into
pytorch:mainfrom
Skylion007:skylion007/exp-lto-2026-04-12
Closed

Skylion007 wants to merge 13 commits into
pytorch:mainfrom
Skylion007:skylion007/exp-lto-2026-04-12

Conversation

@Skylion007

@Skylion007 Skylion007 commented Apr 12, 2026 •

Copy link
Copy Markdown
Collaborator

@pytorch-bot

pytorch-bot Bot commented Apr 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 6 New Failures, 1 Unclassified Failure

As of commit f4fa506 with merge base 612b9a5 (image):

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • linux-binary-manywheel / manywheel-xpu-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    undefined reference to std::__cxx11::basic_string<char, std::char_traits, std::allocator >::~basic_string()'`

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

@Skylion007

Copy link
Copy Markdown
Collaborator Author

Nice, CLANG LTO seems to work. :)

@Skylion007

Skylion007 commented Apr 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Need CPUInfo submodule updated to include: pytorch/cpuinfo#344

Comment thread CMakeLists.txt
endif()

# Enable IPO for Release builds if not explicitly set
if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT DEFINED CMAKE_INTERPROCEDURAL_OPTIMIZATION)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

May need to disable on MSVC if ONE_DNN MSVC bug is not fixed

@Skylion007 Skylion007 added the ciflow/binaries Trigger all binary build and upload jobs on the PR label Apr 14, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased skylion007/exp-lto-2026-04-12 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout skylion007/exp-lto-2026-04-12 && git pull --rebase)

@Skylion007

Copy link
Copy Markdown
Collaborator Author

Okay, the blocking issue from enabling LTO is FBGEMM enabling masm=intel https://github.com/pytorch/FBGEMM/blob/9637997e5c75e4d04b0ab3afb7e64b8b33fba415/CMakeLists.txt#L154 and there being a GCC LTO bug

@Skylion007
Skylion007 force-pushed the skylion007/exp-lto-2026-04-12 branch from 023546b to e18d087 Compare April 18, 2026 19:31
Comment thread CMakeLists.txt Outdated
# Enable IPO for Release builds if not explicitly set.
# Leave it off on Windows for now, DNNL static library build fails.
if(CMAKE_BUILD_TYPE STREQUAL "Release"
AND NOT WIN32

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Alternatively disable it only on LTO on dnnl on Windows

@pytorch-bot pytorch-bot Bot added the module: cpu CPU specific problem (e.g., perf, algorithm) label Apr 19, 2026
Comment thread cmake/Dependencies.cmake
set(FBGEMM_LIBRARY_TYPE "static" CACHE STRING "")
add_subdirectory("${FBGEMM_SOURCE_DIR}")

# Fix LTO bug

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

LTO toolchain bug on manylinux.

@Skylion007
Skylion007 force-pushed the skylion007/exp-lto-2026-04-12 branch 2 times, most recently from bf94db3 to 6861428 Compare April 19, 2026 18:34
Comment thread cmake/Dependencies.cmake
# shouldn't be too bad to just disable the checks.
set_target_properties(fmt-header-only PROPERTIES INTERFACE_COMPILE_FEATURES "")

# Keep fmt's header-only type layout stable across mixed C++ modes. Otherwise

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This needs to get fixed, looks like one of the submodules is messing with it and trying to compile with CPP17?

@Skylion007 Skylion007 added release notes: releng release notes category and removed topic: not user facing topic category labels Apr 19, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator Author

I need to bump the memory available on the runners for the failing linkers. :)

@github-actions github-actions Bot added the Stale label Jul 8, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
@github-actions github-actions Bot closed this Aug 7, 2026
@Skylion007 Skylion007 reopened this Aug 19, 2026
@Skylion007
Skylion007 force-pushed the skylion007/exp-lto-2026-04-12 branch from 6464f3c to e438503 Compare August 19, 2026 16:42
@Skylion007

Copy link
Copy Markdown
Collaborator Author

@claude figure out how to fix this issue

@claude

claude Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 17m 48s —— View job


Both remaining test failures are pre-existing static-initialization-order bugs that LTO exposes — not bugs LTO introduces.

  • Gather context (PR diff, CI logs from jobs 96164967166 / 96164441501)
  • Root-cause ProfilerCollectionTest.DuplicateFlowIdHandledGracefully
  • Root-cause test_jit.py::TestJit::test_script_bool_literal_conversion
  • Propose fixes (not pushed — see "Why I didn't push" below)
Full analysis and proposed fixes

1. test_jit.py::TestJit::test_script_bool_literal_conversion (gcc11)

The failure

def foo(x): return torch.mul(x, True)   # x is torch.rand(3, 4)
RuntimeError: Cannot input a tensor of dimension other than 0 as a scalar argument

That message comes from checkImplicitTensorToNum at torch/csrc/jit/runtime/register_ops_utils.cpp:121, reached via an aten::ScalarImplicit node. So TorchScript resolved aten::mul to the prim overload aten::mul(Scalar a, Scalar b) -> Scalar and coerced the 3x4 tensor to a Scalar, instead of picking aten::mul.Scalar(Tensor self, Scalar other) -> Tensor.

Root cause: candidate order is registration order, which is unspecified across TUs

emitBuiltinCall (torch/csrc/jit/frontend/schema_matching.cpp:681) builds its candidate list from getAllOperatorsFor(name), which returns operators[sym] — a plain std::vector appended in registration order (torch/csrc/jit/runtime/operator.cpp:47-53). Two independent sources populate aten::mul:

  • the c10 ops (mul.Tensor, mul.Scalar), pushed by the dispatcher RegistrationListener in register_c10_ops.cpp:25, driven by a namespace-scope Registerer& dummy static initializer;
  • the JIT-only prim ops (aten::mul(Scalar, Scalar), mul.int, ...) from register_prim_ops.cpp:892.

matchSchemas (schema_matching.cpp:584-601) iterates candidates in vector order, first with allow_conversions=false, then true. Note that BoolType derives from Type, not NumberType (aten/src/ATen/core/jit_type.h:1429), so bool is not a subtype of Scalar — meaning neither overload matches on the no-conversions pass. Both are only viable on the allow_conversions=true pass, where tryConvertToType will happily insert aten::ScalarImplicit for a Tensor arg (schema_matching.cpp:132-134). So whichever overload sits earlier in the vector wins, and that is purely a function of static-initializer ordering between register_c10_ops.cpp and register_prim_ops.cpp. LTO reorders static init across TUs and flips it.

The codebase already knows this is a hazard — getAllSortedOperatorsFor exists precisely to make this deterministic, and its comment says so verbatim (operator.cpp:430-435):

"Depending on the order of registration, aten or jit ops may be registered first. This sorting is helpful in cases where deterministic (i.e. not dependent on build config) behavior is desired."

It sorts c10 ops ahead of JIT-only ops. torch.ops.aten.* uses it (jit/python/init.cpp:1786,1808); TorchScript's emitBuiltinCall does not.

Proposed fix: switch emitBuiltinCall to getAllSortedOperatorsFor(name) so TorchScript overload resolution stops depending on build config. This is the principled fix and aligns TorchScript with torch.ops.*, but it is a semantic change to overload resolution with a wide blast radius — it should be its own PR, landed and CI'd independently of this LTO enablement, then this PR just rebases on it.

2. ProfilerCollectionTest.DuplicateFlowIdHandledGracefully (clang21 x4)

The failure: both saw_per_id_warning and saw_summary_warning are false — i.e. the duplicate-flow branch in TransferEvents::setParents (collection.cpp:1362-1380) never executed at all. The mock's two activities (flow.id=42, flow.start=1, kLinkAsyncCpuGpu) never reached results_. The test isn't asserting the wrong thing; the mock profiler simply never ran.

Root cause: two copies of libkineto's api() singleton

kineto is built as a static library (KINETO_LIBRARY_TYPE "static", cmake/Dependencies.cmake:1803) and linked into torch_cpu PRIVATE — the comment at Dependencies.cmake:1824 states this explicitly. test/cpp/profiler/CMakeLists.txt then links kineto again, directly into the test_profiler_collection executable:

# Link libkineto explicitly. ... Needed for Windows.
target_link_libraries(test_profiler_collection PRIVATE ${PROFILER_TEST_DEPENDENCIES} kineto)

So libkineto's objects — including its api() singleton — exist in both libtorch_cpu.so and the test binary. The test calls libkineto::api().registerProfilerFactory(...) from the executable, while prepareProfiler/disableProfiler run inside torch_cpu and consult its singleton. Whether those are the same object depends entirely on how the linker dedups/internalizes the static archive's symbols — and LTO changes exactly that.

Strong corroborating evidence: the sibling test test_privateuse1_profiler exercises the same machinery, does not link kineto explicitly, and passes in the same job. Only the one test that double-links kineto fails.

Proposed fix (two options, both low-risk):

  • Restrict the extra link to where it was actually needed: $<$<PLATFORM_ID:Windows>:kineto>. The comment says the direct link exists for the GenericTraceActivity vtable on Windows; on ELF platforms it is what creates the duplicate singleton.
  • Or, more robustly, guarantee a single instance by having the test obtain the registry through torch_cpu rather than linking the archive twice.

3. Unrelated observation worth a second look

CMakeLists.txt adds -Wno-error=odr and -Wno-error=lto-type-mismatch for GCC. Those two diagnostics are how GCC reports genuine ODR violations and cross-TU type mismatches — real miscompile precursors, not style nits. The comment already scopes them as temporary ("Remove below when XNNPack/oneDNN/FBGEMM fix their GNU LTO warnings"), which is the right framing; it would be worth capturing the current warning list in a tracking issue so they don't become permanent. Note that findings #1 and #2 above are the same category as the opaque_ptr/assert_close fixes already in this PR: latent order- and UB-dependence that LTO merely made observable.

Why I didn't push a fix

Per this repo's AI_POLICY.md / CLAUDE.md, I don't push code you haven't reviewed, and neither fix is one I can validate here — verifying either requires a full LTO build (hours), and fix #1 in particular changes TorchScript overload resolution globally, so it wants its own PR and its own CI signal rather than being buried in a build-config change. Happy to implement either on your say-so.

Suggested sequencing: land the kineto double-link fix (#2) as a small standalone PR, land the getAllSortedOperatorsFor change (#1) as a second standalone PR, then rebase this one so LTO enablement lands against a green base.

Both failures are latent static-initialization-order bugs that LTO reorders into visibility: the JIT one is TorchScript picking aten::mul(Scalar, Scalar) over aten::mul.Scalar because emitBuiltinCall uses the unsorted getAllOperatorsFor instead of the existing getAllSortedOperatorsFor, and the profiler one is test_profiler_collection linking static kineto a second time and getting a different libkineto::api() singleton than torch_cpu uses.

Fix the JIT overload ordering → | Fix the kineto double-link →
| Branch: skylion007/exp-lto-2026-04-12

@github-actions github-actions Bot closed this Sep 23, 2026
@Skylion007 Skylion007 reopened this Oct 2, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebaes

@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: argument command: invalid choice: 'rebaes' (choose from 'merge', 'revert', 'rebase', 'label', 'drci', 'pre-review', 'lint', 'fix-lint', 'apply-lint', 'cherry-pick')

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,pre-review,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@Skylion007

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased skylion007/exp-lto-2026-04-12 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout skylion007/exp-lto-2026-04-12 && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the skylion007/exp-lto-2026-04-12 branch from e438503 to f4fa506 Compare October 2, 2026 17:55
@github-actions github-actions Bot closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/binaries Trigger all binary build and upload jobs on the PR module: cpu CPU specific problem (e.g., perf, algorithm) open source release notes: releng release notes category Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants