Skip to content

[inductor] Support InductorBenchmarker for non-CUDA device - #184567

Closed
guangyey wants to merge 8 commits into
gh/guangyey/344/basefrom
gh/guangyey/344/head
Closed

guangyey wants to merge 8 commits into
gh/guangyey/344/basefrom
gh/guangyey/344/head

Conversation

@guangyey

@guangyey guangyey commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

@pytorch-bot

pytorch-bot Bot commented May 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 1 Unrelated Failure, 2 Unclassified Failures

As of commit 3a30647 with merge base 25aff58 (image):

NEW FAILURES - The following jobs have failed:

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

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@guangyey guangyey changed the title 【inductor] Generalize InductorBenchmarker to support non-CUDA device [inductor] Generalize InductorBenchmarker to support non-CUDA device May 20, 2026
guangyey added a commit that referenced this pull request May 20, 2026
@guangyey
guangyey requested a review from jansel May 20, 2026 16:24
@guangyey guangyey added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels May 20, 2026
guangyey added a commit that referenced this pull request May 20, 2026
guangyey added 3 commits May 20, 2026 23:22
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@EikanWang

Copy link
Copy Markdown
Collaborator

@guangyey , pls. fix the linter issue.

guangyey added a commit that referenced this pull request May 21, 2026
@guangyey

Copy link
Copy Markdown
Collaborator Author

@guangyey , pls. fix the linter issue.

Done.

@guangyey

Copy link
Copy Markdown
Collaborator Author

@pytorchbot drci

@jansel

jansel commented May 21, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented May 21, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 5s —— View job


Code Review: Generalize InductorBenchmarker to support non-CUDA device

  • Gather context and read the diff
  • Read the full file for broader context
  • Provide code review feedback

Overall, this is a solid change that correctly generalizes the benchmarking infrastructure from CUDA-only to support multiple accelerators (XPU, etc.) using PyTorch's generic device abstractions. The approach is sound. A few observations:

Potential Issue: current_accelerator() can return None

At lines 492 and 617, torch.accelerator.current_accelerator() is called and immediately used as acc.type. Per the API documentation, this function returns None when no accelerator is available. If that ever happens, acc.type would raise AttributeError.

This is likely safe in practice since these code paths only execute during GPU benchmarking (which implies an accelerator exists), but it explains the # pyrefly: ignore [missing-attribute] annotations — pyrefly is catching the type narrowing issue. A brief comment or assertion might help future readers understand why None is impossible here, though this is minor.

Non-CUDA profiler fallback path (lines 694-698)

else:
    for avg in prof.key_averages():
        if avg.key == "_CALLABLE":
            callable_gpu_time_us = avg.device_time_total
            break

Two observations:

  1. No error if _CALLABLE is not found: The CUDA path raises an AssertionError if the event is missing, but the non-CUDA fallback silently returns callable_gpu_time_us = 0.0 (the initial value). This asymmetry could make debugging harder on non-CUDA devices. Consider adding a similar assertion after the loop.

  2. key_averages() aggregates across all iterations: Since device_time_total sums all calls to _CALLABLE across rep iterations, this gives the total time (not per-call), which is consistent with how the CUDA path works (it also sums all matching events). This looks correct.

_dispatch_key_for_device → ProfilerActivity mapping (line 656)

dispatchkey = torch._C._dispatch_key_for_device(acc.type)
getattr(torch.profiler.ProfilerActivity, dispatchkey)

This relies on the dispatch key name (e.g., "CUDA", "XPU") exactly matching the ProfilerActivity enum member names. Looking at the enum definition (torch/_C/_profiler.pyi), the available members are: CPU, CUDA, XPU, MTIA, HPU, PrivateUse1. This should work for all currently supported devices, but the getattr will raise AttributeError for any future device where the dispatch key name doesn't match a ProfilerActivity member. This is an acceptable limitation given the current device landscape, but worth noting.

Minor: L2_cache_size uses is_available() checks (lines 405-412)

The property uses torch.cuda.is_available() / torch.xpu.is_available() for device detection, while the rest of the code uses torch.accelerator.current_accelerator(). These should be consistent in practice but represent two different patterns for device detection in the same class. Using current_accelerator() here too would be more consistent, though this is a stylistic preference.

Summary

The change is well-structured and the torch.accelerator / torch.Event APIs are the right abstractions to use here. The main actionable item is adding an error/assertion in the non-CUDA profiler fallback path when _CALLABLE is not found, to match the CUDA path's behavior and avoid silent zero-timing returns.

[ghstack-poisoned]
@guangyey

Copy link
Copy Markdown
Collaborator Author

duplicated with #183693

guangyey added a commit that referenced this pull request May 28, 2026
guangyey added a commit that referenced this pull request May 28, 2026
guangyey added a commit that referenced this pull request May 28, 2026
[ghstack-poisoned]
guangyey added 2 commits May 28, 2026 16:24
[ghstack-poisoned]
[ghstack-poisoned]
@guangyey guangyey added the ciflow/xpu Run XPU CI tasks label May 29, 2026
guangyey added a commit that referenced this pull request May 29, 2026
@guangyey

Copy link
Copy Markdown
Collaborator Author

@claude review these changes

@claude

claude Bot commented May 29, 2026 •

Copy link
Copy Markdown

Claude finished @guangyey's task in 2m 10s —— View job


Code Review: Generalize InductorBenchmarker to support non-CUDA device

  • Gather context and read the diff
  • Read the full file for broader context
  • Provide code review feedback

This PR has two changes to torch/_inductor/runtime/benchmarking.py:

1. Cache size property rename (global_mem_cache_size → last_level_cache_size)

The rename from global_mem_cache_size to last_level_cache_size at line 514 is correct. The XPU device properties expose last_level_cache_size (documented in torch/xpu/__init__.py:502), not global_mem_cache_size. global_mem_cache_size doesn't exist anywhere in the codebase, so the previous code was a dead fallback that would never match.

2. Kineto event correlation ID fix (lines 391–413)

This addresses the core bug from #184470. The profiler event tree (profiler_events) may not include all CPU dispatch events — specifically, when an op like aten::sum internally re-dispatches to another variant, the inner dispatch appears only in kineto_events but not in the profiler tree. The existing collect_cpu_event_ids traversal of event.cpu_children misses these, causing their correlated device kernels to not be counted in the benchmark time.

The fix identifies time windows of the _CALLABLE events in the kineto event stream, then includes correlation IDs of any CPU kineto events that fall within those windows. This is a reasonable heuristic.

Observations:

  1. Correctness of the window check: The condition ev_start >= win_start and ev_end <= win_end correctly checks that a CPU event is fully contained within the _CALLABLE window. This is the right semantics — partial overlaps would indicate events that started before or ended after the callable, which shouldn't be attributed to it.

  2. Performance: The nested loop (O(kineto_events × callable_windows)) is fine in practice since callable_windows is bounded by rep (typically small, e.g., 4-40), and this only runs during benchmarking, not in the hot path.

  3. Potential edge case: If a CPU event's correlation ID is already in benchmark_event_ids (from the tree traversal), adding it again is harmless since it's an OrderedSet. No duplication issue.

  4. Comment quality: The comment at lines 391–395 clearly explains the root cause and the fix strategy, which is appropriate given the non-obvious nature of the profiler tree gap.

Note on PR status

The author commented this is "duplicated with #183693". It appears neither has landed on main yet (main still has global_mem_cache_size). If #183693 lands first, this PR would need rebasing or could be closed.

Summary

Both changes look correct and well-motivated. The kineto window fix is a sound approach to capturing device kernel time from internally re-dispatched ops. No blocking issues.


@guangyey guangyey changed the title [inductor] Generalize InductorBenchmarker to support non-CUDA device [inductor] Support InductorBenchmarker for non-CUDA device May 29, 2026
# device kernel links to but which is absent from the profiler event tree.
# Include kineto corr IDs of all CPU events within the _CALLABLE time
# window to cover these hidden dispatches.
callable_kineto_windows: list[tuple[int, int]] = []

@guangyey guangyey May 29, 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.

Hi @jansel, we made a follow-up fix after your PR #183693 landed.
Problem: The fallback path in _get_callable_device_kernel_time_us fails on XPU. Unlike CUDA, XPU's record_function does not emit a GPU-side user_annotation kineto event, so the primary timing path misses and the fallback is triggered. The fallback correlates device kernels to the _CALLABLE region by matching each kernel's linked_correlation_id against profiler event IDs from the _CALLABLE subtree — but this match fails because aten::sum (no-dim overload) forwards to aten::sum (dim overload) via a second dispatcher call, producing a kineto CPU event whose corr ID the XPU kernel links to, yet which is absent from the profiler event tree.
Fix: After collecting profiler event IDs from the _CALLABLE subtree, also include kineto corr IDs of all CPU events whose timestamps fall within the _CALLABLE kineto annotation window. This covers hidden re-dispatches that don't appear in the profiler event tree.
Please let me know if you have concerns about the code change. Thanks!

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.

That seems fine to me

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.

Thanks very much~

[ghstack-poisoned]
@jansel

jansel commented May 29, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, check if they are related, and review the changes in this PR

@claude

claude Bot commented May 29, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 21s —— View job


CI Failure Analysis & Code Review

  • Investigate CI failures (Windows build failures)
  • Determine if CI failures are related to this PR
  • Review the code changes in this PR

CI Failures — Not Related to This PR

Both failing Windows jobs (win-vs2022-cpu-py3 and win-vs2022-cuda13.0-py3) fail with the identical error during environment setup, before any PyTorch build step runs:

ERROR: To modify pip, please run the following command:
C:\Jenkins\Miniconda3\envs\py_tmp\python.exe -m pip install -r .ci/docker/requirements-ci.txt

This is a pip self-protection error: the CI script is running pip install -r .ci/docker/requirements-ci.txt which includes pip==26.0.1, and pip refuses to upgrade itself without being invoked via python -m pip. This is a CI infrastructure issue on the Windows runners — likely a recent pip version change that triggers stricter self-modification checks. It has nothing to do with the changes in benchmarking.py.

The two "UNCLASSIFIED" XPU failures also show the same error pattern on Windows XPU runners.


Code Review

The PR makes two changes to torch/_inductor/runtime/benchmarking.py:

1. Cache size property fix (line 514)

for attr in ("L2_cache_size", "last_level_cache_size"):

Previously "global_mem_cache_size" — which doesn't exist anywhere in PyTorch's device property interfaces. last_level_cache_size is the correct XPU device property name (defined in torch/xpu/__init__.py). Good fix.

2. Kineto event correlation ID fix (lines 391–413)

This addresses the root cause of #184470. The profiler event tree may not include all CPU dispatch events — specifically when an op like aten::sum (no-dim) internally re-dispatches to aten::sum (dim), the inner dispatch appears in kineto_events but not in the cpu_children tree traversal. The fix identifies _CALLABLE time windows from kineto events and includes correlation IDs of all CPU events that fall within those windows.

Assessment: The fix is correct and well-motivated. A few observations:

  • Correctness: The containment check (ev_start >= win_start and ev_end <= win_end) is the right semantics — it only includes events fully within the callable window, avoiding attribution of unrelated events.
  • No double-counting risk: Adding an already-present correlation ID to the OrderedSet is a no-op.
  • Performance: O(kineto_events × rep) is fine for benchmarking code (rep is small, typically 4–40).
  • Comment quality: The 5-line comment clearly explains the non-obvious root cause, which is appropriate here.

No blocking issues. The code looks good to merge once CI infra is fixed independently.


@guangyey

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 5 checks: xpu / win-vs2022-xpu-n-py3 / build, xpu / win-vs2022-xpu-n-1-py3 / build, trunk / win-vs2022-cuda13.0-py3 / build, trunk / win-vs2022-cpu-py3 / build, inductor / unit-test / inductor-test / test-osdc (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g)

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

@github-actions
github-actions Bot deleted the gh/guangyey/344/head branch June 30, 2026 02:26
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request ciflow/xpu Run XPU CI tasks Merged module: inductor open source topic: not user facing topic category

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

5 participants