Skip to content

Replace function ptr comparator with struct comparator - #195129

Closed
lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:inline-block-comparator
Closed

lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:inline-block-comparator

Conversation

@lakshayg

Copy link
Copy Markdown
Collaborator

I see from build/bolt_profiles/libc10_cuda.yaml that the block comparator is the hottest function in libc10_cuda.so. Using a function ptr based comparator hinders inlining. Replacing it with a struct based comparator should help.

I see from bolt_profiles/libc10_cuda.yaml that the comparator
is the hottest function in libc10_cuda.so. Using a function ptr
based comparator hinders inlining by the compiler. Replacing
it with a struct based comparator should help.
@lakshayg lakshayg self-assigned this Aug 28, 2026
@lakshayg
lakshayg requested a review from eqy as a code owner August 28, 2026 09:46
@lakshayg lakshayg added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 28, 2026
@lakshayg lakshayg added the topic: not user facing topic category label Aug 28, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 4fa98e5 with merge base 4380f31 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@lakshayg
lakshayg requested review from Skylion007 and removed request for Aidyn-A, eqy and syed-ahmed August 28, 2026 09:46
static bool BlockComparatorSizeCounterAddress(const Block* a, const Block* b);
static bool BlockComparatorAddress(const Block* a, const Block* b);

struct BlockComparatorSizeCounterAddress {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Since these are hot paths shouldn't they be marked as noexcept too?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Or would this also hurt inlining perhaps?

@lakshayg lakshayg Aug 28, 2026 •

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.

Regarding noexcept, since there's nothing that can throw in here, hopefully the compiler won't generate anything exception related. I don't know if it will make a difference to performance.

Regarding inlining, I would assume it's more amenable to inlining now since we don't have to call through a function pointer.

Let me know if you would like me to change anything here!

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

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


PR Review: #195129

A clean, correct refactor that turns the indirect function-pointer comparator into a statically-known functor; the only real gap is that a performance-motivated PR ships without a before/after number, and the answer to @Skylion007's noexcept question is "harmless, but it will not change codegen."

Full review

Summary

Replaces the typedef bool (*Comparison)(const Block*, const Block*) function-pointer comparator used by BlockPool's three std::set<Block*> members with two empty stateless functor structs. The change is correct and the motivation is sound, but it is unmeasured, and there are two small code-quality points.

Performance

  • No before/after measurement for a perf-only PR. The description says a struct comparator "should help," but there is no number. Since the whole justification is the BOLT profile, the PR should include one measured data point — e.g. the same bolt_profiles/libc10_cuda.yaml hotness ranking after the change, or an allocator microbenchmark. Without it there is nothing to defend the churn with if it later shows up in a bisect.

    For what it is worth, the reasoning does hold: with std::set<Block*, bool(*)(...)> the comparator is a runtime data member of libstdc++'s _Rb_tree_key_compare, loaded from memory inside the tree-descent loop. The set objects live in heap-allocated allocator state, so indirect-call promotion cannot recover the target — every comparison was a genuine indirect call. That the comparator shows up as the hottest symbol in the BOLT profile is itself evidence it was never inlined. So the direction is right; it just needs a number.

  • inline on the two definitions (optional, low confidence). c10/cuda/CUDACachingAllocator.cpp:1203 and :1218 define the bodies out-of-class, which means they are not implicitly inline. GCC therefore classifies them under max-inline-insns-auto rather than the much larger max-inline-insns-single, and Clang does not emit InlineHint. In practice these bodies are small enough that -finline-small-functions (on at -O2) plus the internal-linkage bonus should inline them regardless, so this is unlikely to matter — but marking both definitions inline documents the intent at zero cost given inlining is the entire point of the PR. I have not measured a difference and would not block on it.

Answer to @Skylion007's review comment (noexcept on the hot-path comparators)

noexcept here is fine as a contract annotation but will not change codegen. Three independent reasons:

  1. There is no cleanup state at the comparison sites. libstdc++'s _Rb_tree::_M_insert_unique runs _M_get_insert_unique_pos — which performs all the _M_key_compare calls, with only raw _Base_ptr locals live — and only then calls _M_create_node. _M_erase_aux(const key_type&) likewise does equal_range before _M_drop_node. find/lower_bound/upper_bound allocate nothing at all. So there is no partially-constructed object to unwind and no landing pad for noexcept to elide.
  2. No libstdc++ exception specification keys off Cmp::operator(). set::swap's _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) and _Rb_tree's move constructor spec depend on swapping/copying the comparator object — an empty struct, already nothrow — never on invoking it. And this is moot anyway: BlockPool is never swapped or moved in this file (const bool is_small deletes copy-assignment, and swap does not appear anywhere in the file).
  3. The compiler already infers it. These are internal-linkage leaves consisting of pure loads and integer comparisons; GCC's ipa-pure-const sets TREE_NOTHROW from the body, and after inlining there is nothing left to reason about.

One mechanical note if it is added anyway: C++17 made noexcept part of the function type, so it must appear on both the in-class declaration (:194, :198) and the out-of-line definition (:1203, :1218) or the TU will not compile with "declaration of ... has a different exception specifier."

Code Quality

  • decltype spelling is asymmetric and less readable than what it replaced. c10/cuda/CUDACachingAllocator.cpp:216 uses decltype(blocks)::iterator while :294 uses decltype(BlockPool::blocks)::iterator for the same type. Both are harder to read than the std::set<Block*, Comparison>::iterator they replace. Since the point of Comparison was partly to name this type, consider restoring a name for it:

    using BlockSet = std::set<Block*, BlockComparatorSizeCounterAddress>;
    using BlockAddrSet = std::set<Block*, BlockComparatorAddress>;

    and spelling the return type std::pair<BlockSet::iterator, bool> in both places. Fix this →

    If you prefer to keep decltype, at least make the two spellings consistent.

  • Note, not a request: c10/xpu/XPUCachingAllocator.cpp:22-36 still uses the identical function-pointer pattern (typedef bool (*Comparison)(...), BlockComparatorSize, BlockComparatorAddress). Worth a follow-up if the measurement here pans out — leaving the two allocators divergent invites the next reader to copy the old pattern.

Testing

No new tests needed — this is a behavior-preserving refactor of a file-local implementation detail, covered by the existing CUDA allocator test suite (test/test_cuda.py, aten/src/ATen/test/cuda_allocator_test.cpp). Since the sets' ordering semantics are unchanged (the comparator bodies are byte-identical apart from the ::operator() qualification), existing coverage is sufficient.

Things I checked and found clean

  • Linkage is not regressed. The old static bool BlockComparator... declarations were already inside the anonymous namespace spanning lines 176-1420, so the static was redundant. The new structs sit in that same anonymous namespace, and members of an internally-linked class have internal linkage, so nothing becomes externally visible. libc10_cuda builds with -fvisibility=hidden regardless, and the structs are not in a header, so no C10_CUDA_API is needed.
  • Source order does not matter for inlining. Both GCC (whole-callgraph IPA-inline over GIMPLE) and Clang (whole-module CGSCC inliner; template instantiations emitted at end-of-TU) have the full TU before making inline decisions, so defining the bodies ~1000 lines after the std::set instantiations costs nothing.
  • The type split is safe, and mildly beneficial. blocks now has a different C++ type from blocks_by_addr/unmapped, where previously all three were std::set<Block*, Comparison>. Nothing in the file names that type outside lines 207-209 — no parameter, return type, assignment, or std::swap between them; get_size_block (:1961) and cache_info_aux (:4562) take const BlockPool&; the ternary at :3752 yields size_t on both arms. Previously a size-ordered iterator and an address-ordered iterator were interchangeable types and mixing them compiled silently; now it is a compile error.

Recommendation

Approve, once a measurement is added to the PR description. The refactor is correct and type-safe; the inline and alias points are optional, and noexcept can be skipped.

| Branch: [`inline-block-comparator`](https://github.com/pytorch/pytorch/tree/inline-block-comparator)

@Skylion007

Copy link
Copy Markdown
Collaborator

Could you fix the XPU identical caching allocator too to solve the same issue as well?

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@Skylion007 is it okay if I do that in a follow up PR so it's easy to revert if there are any issues on either side.

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@lakshayg
lakshayg deleted the inline-block-comparator branch August 28, 2026 17:30
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
In `CUDACachingAllocator` the `Block` comparator is a hot function. #195129 optimizes it so that the compiler can inline it. This PR brings the same change to XPUCachingAllocator.
Pull Request resolved: #195176
Approved by: https://github.com/Skylion007
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
I see from `build/bolt_profiles/libc10_cuda.yaml` that the block comparator is the hottest function in libc10_cuda.so. Using a function ptr based comparator hinders inlining. Replacing it with a struct based comparator should help.
Pull Request resolved: pytorch#195129
Approved by: https://github.com/Skylion007
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h#195176)

In `CUDACachingAllocator` the `Block` comparator is a hot function. pytorch#195129 optimizes it so that the compiler can inline it. This PR brings the same change to XPUCachingAllocator.
Pull Request resolved: pytorch#195176
Approved by: https://github.com/Skylion007
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
I see from `build/bolt_profiles/libc10_cuda.yaml` that the block comparator is the hottest function in libc10_cuda.so. Using a function ptr based comparator hinders inlining. Replacing it with a struct based comparator should help.
Pull Request resolved: pytorch#195129
Approved by: https://github.com/Skylion007
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…h#195176)

In `CUDACachingAllocator` the `Block` comparator is a hot function. pytorch#195129 optimizes it so that the compiler can inline it. This PR brings the same change to XPUCachingAllocator.
Pull Request resolved: pytorch#195176
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants