Skip to content

Fix Inductor stream wrapper codegen for XPU - #183693

Closed
jansel wants to merge 9 commits into
gh/jansel/617/basefrom
gh/jansel/617/head
Closed

jansel wants to merge 9 commits into
gh/jansel/617/basefrom
gh/jansel/617/head

Conversation

@jansel

@jansel jansel commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Route Python wrapper stream operations through device op overrides so multi-stream code on XPU emits torch.xpu stream APIs instead of CUDA-only calls. This preserves CUDA codegen while allowing the disabled control-deps test to run on XPU.

Fixes #181701
Generated by my agent

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures, 3 Unrelated Failures, 2 Unclassified Failures

As of commit 5ecbfaf with merge base c230e69 (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:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@jansel

jansel commented May 14, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 14, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 15s —— View job


Review: Fix Inductor stream wrapper codegen for XPU

  • Read the PR diff and understand the changes
  • Review torch/_inductor/codegen/common.py changes
  • Review torch/_inductor/codegen/wrapper.py changes
  • Review device op overrides (CUDA, XPU, MTIA)
  • Review test changes
  • Post review feedback

Overall: Clean, well-structured change. The abstraction is the right approach — routing stream operations through DeviceOpOverrides is consistent with how set_device, synchronize, and device_guard already work.

Feedback

1. Minor: stale docstring (wrapper.py:819)

ExitDeviceContextManagerWithStreamInfoLine still says "Exit a CUDA device context" — worth updating to match the pattern of the other docstring fixes in this PR.

2. Minor: EnterCudaStreamContextLine class name

The class name still references "Cuda" even though it's now device-agnostic. The docstring was updated correctly, but renaming the class (and ExitCudaStreamContextLine) would complete the generalization. Not blocking since it's a public symbol imported in test code and likely elsewhere.

3. stream_handle for XPU/MTIA (common.py:336-337)

The base class default is f"{stream_name}.native_handle". XPU and MTIA don't override this, while CUDA overrides to .cuda_stream. This seems intentional but worth a quick sanity check that XPU stream objects expose .native_handle — if not, XPU multi-stream subgraph codegen would emit broken code. (The test doesn't exercise the stream_handle path for XPU.)

4. Test uses subTest pattern? (test_user_streams.py:215)

The for device_ops, expected in cases: loop would benefit from with self.subTest(device_ops=type(device_ops).__name__): so that a failure in one case doesn't mask the other and the test output identifies which device failed. Minor nit.

5. Looks good otherwise:

  • The V.graph.device_ops calls in wrapper.py are clean and consistent with existing usage patterns.
  • Test coverage is solid — the new test_stream_codegen_uses_device_ops test exercises both CUDA and XPU codegen paths end-to-end with exact string matching.
  • MTIA gets the methods but doesn't have a test case — acceptable given MTIA's limited CI coverage.

LGTM with the minor nits above.


@jansel jansel added the topic: not user facing topic category label May 14, 2026
[ghstack-poisoned]
jansel added a commit that referenced this pull request May 14, 2026
Route Python wrapper stream operations through device op overrides so multi-stream code on XPU emits torch.xpu stream APIs instead of CUDA-only calls. This preserves CUDA codegen while allowing the disabled control-deps test to run on XPU.

Fixes #181701
Generated by my agent

ghstack-source-id: 12ae314
Pull-Request: #183693

@guangyey guangyey left a comment

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.

Thanks!

@guangyey guangyey added the ciflow/trunk Trigger trunk jobs on your pull request label May 15, 2026
@guangyey

Copy link
Copy Markdown
Collaborator

In PyTorch, torch.Stream, torch.cuda.Stream, torch.xpu.Stream now support stream context natively, e.g.:

stream = torch.Stream()
with stream:
    pass

stream = torch.cuda.Stream()
with stream:
    pass

...

[ghstack-poisoned]
jansel added a commit that referenced this pull request May 15, 2026
Make Inductor wrapper stream codegen use device-specific current-stream lookup and native stream context managers, while using generic native_handle raw stream handles so torch.Stream works across CUDA and XPU. This removes CUDA-only wrapper paths that broke the disabled XPU control-deps test.

Fixes #181701

Generated by my agent

ghstack-source-id: 2ca0757

Pull-Request: #183693
@jansel

jansel commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 15, 2026 •

Copy link
Copy Markdown

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


  • Read the PR diff and understand the changes
  • Review torch/_inductor/codegen/common.py changes
  • Review torch/_inductor/codegen/wrapper.py changes
  • Review device op overrides (CUDA, XPU, MTIA)
  • Review test changes
  • Post review feedback

Review: Fix Inductor stream wrapper codegen for XPU

Overall: Clean change. The approach of routing stream operations through DeviceOpOverrides is consistent with the existing pattern for set_device, synchronize, and device_guard. The switch from torch.cuda.stream(stream) to with stream: is correct — the base THPStream class implements __enter__/__exit__ natively in C++ (torch/csrc/Stream.cpp:298), supporting all accelerator device types.

Key observations

1. native_handle vs cuda_stream — looks correct

The old code used .cuda_stream (a CUDA-specific attribute on torch.cuda.Stream). The new default .native_handle is defined on the C-level THPStream base class (torch/csrc/Stream.cpp:138), making it device-agnostic. Both XPU and CUDA streams inherit this. For CUDA, native_handle returns stream.native_handle() from c10::Stream, which should be equivalent to cuda_stream (both are the raw cudaStream_t pointer). Good change.

2. CUDA doesn't override stream_handle — the base default (native_handle) is used for all devices. This means existing CUDA subgraph codegen now emits stream1.native_handle instead of stream1.cuda_stream. Worth confirming this is intentional and semantically identical (I believe it is based on the C10 implementation, but it's a behavioral change for CUDA).

3. Minor: EnterCudaStreamContextLine / ExitCudaStreamContextLine class names

These class names still reference "Cuda" even though they're now device-agnostic. The docstrings were correctly updated. Not blocking — renaming public symbols is a separate cleanup.

4. Test quality is good

  • Uses self.subTest(device=device) for parametrized cases — nicely addresses isolated failure reporting.
  • The _count_generated_stream_contexts helper with the regex r"(?m)^\s*with (?:default_stream|stream\d+):" correctly matches the new with stream1: pattern.
  • Unit tests for both EnterDeviceContextManagerWithStreamInfoLine and SubgraphPythonWrapperCodegen._write_get_raw_stream cover CUDA and XPU paths with exact string matching.

5. The test_generic_stream_with_cuda_stream_context test simplification (lines 1872–1890) — good. Removing the manual torch.cuda.Stream(stream_id=..., device_index=..., device_type=...) conversion and using with stream: directly is cleaner and tests the actual codegen path.

LGTM.


View job

@jansel
jansel marked this pull request as ready for review May 17, 2026 22:55
@jansel
jansel requested a review from anijain2305 May 17, 2026 22:56
@jansel jansel added the ciflow/xpu Run XPU CI tasks label May 18, 2026
@jansel
jansel marked this pull request as draft May 18, 2026 15:43
[ghstack-poisoned]
jansel added a commit that referenced this pull request May 19, 2026
Make Inductor wrapper stream codegen use device-specific current-stream lookup and native stream context managers, while using generic native_handle raw stream handles so torch.Stream works across CUDA and XPU. This removes CUDA-only wrapper paths that broke the disabled XPU control-deps test.

Fixes #181701

Generated by my agent

ghstack-source-id: bc92e35

Pull-Request: #183693
@jansel
jansel marked this pull request as ready for review May 19, 2026 08:50
[ghstack-poisoned]
jansel added a commit that referenced this pull request May 19, 2026
Make Inductor wrapper stream codegen use device-specific current-stream lookup and native stream context managers, while using generic native_handle raw stream handles so torch.Stream works across CUDA and XPU. This removes CUDA-only wrapper paths that broke the disabled XPU control-deps test.

Fixes #181701

Generated by my agent

ghstack-source-id: f41cbaa

Pull-Request: #183693
@jansel

jansel commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

Agent, rebase and look into those XPU CI failures.

[ghstack-poisoned]
jansel added a commit that referenced this pull request May 20, 2026
Make Inductor wrapper stream codegen use device-specific current-stream lookup and native stream context managers, while using generic native_handle raw stream handles so torch.Stream works across CUDA and XPU. This removes CUDA-only wrapper paths that broke the disabled XPU control-deps test.

Fixes #181701

Generated by my agent

ghstack-source-id: 0545f66

Pull-Request: #183693
@guangyey

Copy link
Copy Markdown
Collaborator

Hi @eellison, The code change looks great to XPU. Could you please help stamp it?

@jansel

jansel commented May 25, 2026

Copy link
Copy Markdown
Contributor Author

My agent says guangyey has approved and asked for eellison to stamp the PR, so I re-requested eellison as an active reviewer. CI is complete; Dr.CI classifies the remaining failures as unrelated/flaky/broken-trunk/unstable.

[ghstack-poisoned]
jansel added a commit that referenced this pull request May 28, 2026
Root cause: Inductor wrapper stream codegen and benchmarking/profiler helpers still assumed CUDA APIs on paths exercised by XPU. The wrapper emitted CUDA current-stream/raw-stream code, and profiler benchmarking selected and synchronized through CUDA-centric helpers, so XPU-only CI failed before reaching the intended control-dependency and benchmark assertions.

Fix this by routing stream lookup and raw handles through DeviceOpOverrides, using the native Python stream context manager with stream objects, and threading device_type through profiler setup, synchronization, and cache-flush allocation. The profiler benchmarker also falls back to correlated device kernel events when a backend does not emit a device-side _CALLABLE annotation. After rebasing over the in-source disabled-test import, remove the stale XPU skip decorators for the tests this PR now fixes.

I kept the change in the existing device/backend abstraction instead of adding local XPU branches in wrapper or benchmarking code, because these paths need to keep CUDA, XPU, and MTIA behavior aligned.

Test Plan:
python test/inductor/test_benchmarking.py TestBenchmarker.test_default_profiler_benchmarker_selection_supports_xpu_only TestBenchmarker.test_profiler_benchmarker_fallback_uses_correlated_device_events -v
python test/inductor/test_benchmarking.py -k test_torch_profiler_benchmarker_reuses_inductor_helpers -v
python test/inductor/test_user_streams.py TestStreamCodegen TestWrapperCodegenStreams TestStreamUtils -v
python test/inductor/test_control_deps.py -k test_control_deps_orders_void_op_across_nested_calls -v
python test/inductor/test_benchmarking.py TestBenchmarker -v
python test/inductor/test_user_streams.py TestUserStreamCompile.test_compile_with_user_stream_context TestUserStreamCompile.test_compile_preserves_stream_semantics TestUserStreamCompile.test_multiple_stream_contexts TestUserStreamCompile.test_nested_stream_contexts TestUserStreamCompile.test_stream_context_with_data_dependency TestGenericStreamCompile.test_generic_stream_basic -v
lintrunner -a

Fixes #181701

Generated by my agent

ghstack-source-id: d5fb8cd

Pull-Request: #183693
@jansel

jansel commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

My agent says rebased onto current main after the disabled-test skips were inlined into source. The PR now also removes the stale XPU skip decorators for the control-deps and profiler benchmark tests fixed by this change; local targeted tests and lintrunner -a passed, and fresh CI is queued on the updated head.

@jansel

jansel commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 8s —— View job


Review: Fix Inductor stream wrapper codegen for XPU

  • Read the PR diff and understand the changes
  • Review torch/_inductor/codegen/common.py changes
  • Review torch/_inductor/codegen/wrapper.py changes
  • Review device op overrides (CUDA, XPU, MTIA)
  • Review benchmarking changes
  • Review test changes
  • Post review feedback

Overall: LGTM. Clean, well-structured change with two orthogonal improvements: (1) routing stream codegen through DeviceOpOverrides so XPU emits the correct stream APIs, and (2) generalizing the benchmarking infrastructure to work with non-CUDA GPU devices. Both are consistent with existing patterns.

Stream codegen — solid

The switch from with torch.cuda.stream(stream1): to with stream1: is correct — THPStream.__enter__/__exit__ handles all device types natively in C++. The new current_stream() method on DeviceOpOverrides follows the established set_device/synchronize/device_guard pattern exactly. The stream_handle() base default of .native_handle is device-agnostic and correct for all accelerator backends.

Benchmarking — clean generalization

The _make_default_benchmarker() refactoring to defer is_available() checks removes the import-time coupling to CUDA. The device_type parameter threading through benchmark_gpu and TorchProfilerBenchmarker.benchmark_gpu is clean.

One observation on get_device_cache_size cross-caching (benchmarking.py:483-484):

if "L2_cache_size" in self.__dict__:
    return self.__dict__["L2_cache_size"]

If L2_cache_size was populated via a call with device_type=None (resolving to e.g. "cuda"), a subsequent get_device_cache_size("xpu") would return the wrong value. In practice this is fine since the assert len(avail_gpus) <= 1 at line 37 enforces at most one GPU type per process — but the coupling between these two functions is non-obvious. Worth a one-line comment noting the single-device-type assumption, or just documenting it in the docstring.

_get_callable_device_kernel_time_us fallback — Good addition. The correlation-based approach for XPU (where kineto may not emit gpu_user_annotation events with the _CALLABLE name directly) is sound. The test with FakeKinetoEvent/FakeProfilerEvent validates the matching and filtering logic well.

Test changes — good coverage

  • self.subTest(device=device) for parametrized cases provides isolated failure reporting.
  • _count_generated_stream_contexts regex helper is a clean replacement for string-matching against torch.cuda.stream.
  • test_stream_codegen_uses_device_ops exercises both CUDA and XPU paths end-to-end with exact string matching.
  • test_subgraph_raw_stream_uses_device_ops_stream_handle covers the SubgraphPythonWrapperCodegen._write_get_raw_stream path.
  • test_profiler_benchmarker_fallback_uses_correlated_device_events validates the correlation fallback with exact numeric assertions.
  • The test_generic_stream_with_cuda_stream_context simplification (removing the manual torch.cuda.Stream(stream_id=..., ...) conversion and using with stream: directly) is correct and tests the actual codegen path.

Minor nits (non-blocking)

  1. EnterCudaStreamContextLine / ExitCudaStreamContextLine class names still reference "Cuda" despite being device-agnostic. Docstrings were correctly updated. Not blocking — renaming public symbols is a separate cleanup.

  2. Bare assert at benchmarking.py:37 — assert len(avail_gpus) <= 1 would benefit from a message: assert len(avail_gpus) <= 1, f"Multiple GPU device types available: {avail_gpus}". Makes debugging easier in unexpected multi-accelerator environments.

  3. Removing stale skip decorators — Good housekeeping. The @skipIfXpu removals in test_control_deps.py and test_benchmarking.py properly reflect that this PR fixes the underlying issues those skips were working around.

LGTM.


View job

@guangyey

Copy link
Copy Markdown
Collaborator

@claude xpu failure FAILED CONSISTENTLY: test/inductor/test_benchmarking.py::TestBenchmarker::test_torch_profiler_benchmarker_reuses_inductor_helpers_hip_value0_expected_buffer_size_bytes_1024 is related. Use prof.key_averages() to handle other device except cuda

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown

Claude finished @guangyey's task in 7m 36s —— View job


Fixing XPU test failure in benchmarking code

  • Understand the failing test and root cause
  • Read the benchmarking code to identify the fix location
  • Identify the solution
  • Implement the fix (blocked by sandbox permissions)

Root Cause

The test_torch_profiler_benchmarker_reuses_inductor_helpers_hip_value0_expected_buffer_size_bytes_1024 test fails on XPU because TorchProfilerBenchmarker.benchmark_gpu (benchmarking.py:766-788) extracts GPU timing from raw kineto events in two ways:

  1. Primary: Looks for _CALLABLE events with matching device type directly in prof.profiler.kineto_results.events() (line 767-774)
  2. Fallback: Uses correlation-based matching via _get_callable_device_kernel_time_us (line 777-782)

On XPU, neither approach works because XPU's kineto backend doesn't emit gpu_user_annotation events with the _CALLABLE name for the device type the same way CUDA does, and the correlation IDs don't match either. Both fail, hitting the AssertionError at line 784-788.

Fix

As @guangyey suggested, add a third fallback using prof.key_averages() which handles device-specific event correlation internally for all device types (CUDA, XPU, etc.). This is the device-agnostic approach already built into PyTorch's profiler infrastructure.

In torch/_inductor/runtime/benchmarking.py, replace lines 784-788:

        if callable_gpu_time_us <= 0:
            raise AssertionError(
                f"TorchProfilerBenchmarker: '_CALLABLE' {device_type_upper} event not found in "
                "raw kineto results, and no correlated device events were found."
            )

With:

        if callable_gpu_time_us <= 0:
            for evt in prof.key_averages():
                if evt.key == _CALLABLE_PROFILE_EVENT_NAME:
                    callable_gpu_time_us = evt.self_device_time_total
                    break

        if callable_gpu_time_us <= 0:
            raise AssertionError(
                f"TorchProfilerBenchmarker: '_CALLABLE' {device_type_upper} event not found in "
                "raw kineto results, correlated device events, or key_averages()."
            )

This preserves the fast path for CUDA (raw kineto events) and adds a robust device-agnostic fallback via key_averages() that works for XPU and any other device type. The key_averages() path is slower (triggers _parse_kineto_results + _build_tree + aggregation) but only runs when the faster paths fail, so there's no performance impact on CUDA.

Note: I was unable to push this change due to sandbox permission restrictions on file-writing operations. A patch file (benchmarking.patch) with the exact diff was created by a previous agent run and is available in the working directory.

@guangyey

guangyey commented May 28, 2026 •

Copy link
Copy Markdown
Collaborator

Hi @jansel, thanks a lot for this fix! Really appreciate your help!
I'd like to land this PR soon, and I can help take a look at test_torch_profiler_benchmarker_reuses_inductor_helpers_hip_value0_expected_buffer_size_bytes_1024 as the agent currently doesn’t have XPU machines available for debugging. This fix is quite important and very helpful for XPU, so I’d like to move it forward and land it as soon as possible.

@guangyey

Copy link
Copy Markdown
Collaborator

@pytorchbot 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

@guangyey

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

khushi-411 pushed a commit to khushi-411/pytorch that referenced this pull request Jun 1, 2026
Route Python wrapper stream operations through device op overrides so multi-stream code on XPU emits torch.xpu stream APIs instead of CUDA-only calls. This preserves CUDA codegen while allowing the disabled control-deps test to run on XPU.

Fixes pytorch#181701
Generated by my agent

Pull Request resolved: pytorch#183693
Approved by: https://github.com/guangyey, https://github.com/eellison
@github-actions
github-actions Bot deleted the gh/jansel/617/head branch June 28, 2026 02:27
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Route Python wrapper stream operations through device op overrides so multi-stream code on XPU emits torch.xpu stream APIs instead of CUDA-only calls. This preserves CUDA codegen while allowing the disabled control-deps test to run on XPU.

Fixes pytorch#181701
Generated by my agent

Pull Request resolved: pytorch#183693
Approved by: https://github.com/guangyey, https://github.com/eellison
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Route Python wrapper stream operations through device op overrides so multi-stream code on XPU emits torch.xpu stream APIs instead of CUDA-only calls. This preserves CUDA codegen while allowing the disabled control-deps test to run on XPU.

Fixes pytorch#181701
Generated by my agent

Pull Request resolved: pytorch#183693
Approved by: https://github.com/guangyey, https://github.com/eellison
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 topic: not user facing topic category

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants