Skip to content

Fix CPU-only profiler mode to avoid initializing GPU tracing - #186036

Closed
ngimel wants to merge 12 commits into
gh/ngimel/3/basefrom
gh/ngimel/3/head
Closed

ngimel wants to merge 12 commits into
gh/ngimel/3/basefrom
gh/ngimel/3/head

Conversation

@ngimel

@ngimel ngimel commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Derive the Kineto cpuOnly flag from the requested activity set rather
than from whether CUDA or another device backend is present on the
machine.

This keeps CPU-only profiling from arming GPU tracing when the user did
not request any device activities, while preserving the default behavior
when available device activities are included.

[ghstack-poisoned]
@ngimel
ngimel requested review from ryanzhang22 and scotts as code owners June 3, 2026 04:02
@pytorch-bot

pytorch-bot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit 0ff96af with merge base 3e663d6 (image):

NEW FAILURE - The following job has failed:

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

ngimel added 3 commits June 2, 2026 22:55
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
ngimel added 2 commits June 3, 2026 12:19
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@ngimel ngimel added the topic: not user facing topic category label Jun 3, 2026
ngimel added 4 commits June 3, 2026 16:02
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@huydhn

huydhn commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot drci

[ghstack-poisoned]
@ngimel

ngimel commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 4, 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-osdc (distributed, 1, 3, mt-l-x86iavx512-45-172-t4-4)

Details for Dev Infra team Raised by workflow job

@ngimel

ngimel commented Jun 5, 2026

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 1 checks: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test-osdc (distributed, 1, 3, mt-l-x86iavx512-45-172-t4-4)

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 pushed a commit that referenced this pull request Jun 5, 2026
Add a hidden experimental profiler backend that uses the CUPTI monitor
for GPU collection while reusing the existing CPU profiler path.

This commit wires the monitor into profiler scheduling and export,
constructs merged Chrome traces, recreates GPU-side user annotations for
Python record_function scopes, maps CUDA runtime events onto the same CPU
thread lanes as stock traces, and keeps eager/graph traces close to the
existing profiler behavior.
Pull Request resolved: #186037
Approved by: https://github.com/scotts
ghstack dependencies: #186034, #186036
pytorchmergebot pushed a commit that referenced this pull request Jun 5, 2026
…ck (#186295)

The experimental CUPTI monitor (torch.profiler._cupti_monitor) uses the CUPTI
Activity API, which hands completed records to us only through two callbacks
that CUPTI invokes itself: buffer-requested (asks us for an empty buffer to
fill) and buffer-completed (returns a filled one). The Activity API has no
polling alternative, so using it means registering these callbacks, and CUPTI
calls them synchronously from its own threads while holding its internal lock.

Previously the callbacks were Python/ctypes closures, so CUPTI acquired the GIL
while holding that lock. A thread that holds the GIL and then enters CUPTI/CUDA
can deadlock against such a callback (GIL <-> CUPTI lock inversion). The
callbacks are mandatory and the hazard is intrinsic to running any Python
inside them, so the only fix is to make the callback bodies native.

This moves the buffer pool and completed-buffer queue into C++
(torch/csrc/profiler/cupti_monitor_native.{h,cpp}). The buffer-requested and
buffer-completed callback bodies are now pure C++: they only touch a
mutex-guarded free list and a completed-buffer queue, never Python. The Python
decode thread pulls completed buffers via _cupti_monitor_get_completed(), which
releases the GIL while it blocks on a condition variable, and hands them back
with _cupti_monitor_return_buffer(). Registration with CUPTI still happens on
the Python side via ctypes using the callback addresses exposed in init.cpp, so
the pool/queue/callbacks stay reusable for the per-subscriber _v2 Activity APIs
later: only the registration call would gain a subscriber handle.

The free list is LIFO so a returned buffer is reused while it is still the
warmest in cache. The new torch._C._profiler symbols are added to the
_profiler.pyi stub so callers use direct attribute access instead of getattr.

 v2 (subscriber-scoped) Activity API support

  The same native pool is exposed for cuptiActivityRegisterCallbacks_v2 so a prototype can build on the v2 / user-defined-record API (CUPTI ≥ 13.2) without any
  further C++:

  - _cupti_monitor_buffer_request_callback_address(version) / _cupti_monitor_buffer_complete_callback_address(version) take a version (1 or 2, default 1) and return
  native callbacks with the v1 or v2 CUPTI ABI. Both feed the same pool/queue.
  - v2 does not deliver CUcontext/streamId to the completion callback (they become selectable record fields), so buffers completed on the v2 path report ctx/stream
  as 0.
  - The v2 completion callback snapshots the user-defined record layout — which CUPTI only makes valid for the duration of the callback — once per session (the
  layout is fixed by the field selection). It's exposed via _cupti_monitor_record_layouts() as [(kind, record_size, [(field_id, offset, size), ...]), ...] so a
  decode thread can parse field-selected records after the callback returns. The CUPTI v2 structs are mirrored by ABI in the .cpp so the build needs no v2 header.

  All registration (cuptiSubscribe / cuptiActivityRegisterCallbacks_v2 / cuptiActivityEnable_v2 / the USER_DEFINED_RECORDS attribute) stays on the Python/ctypes side
  for a future prototype.

Test Plan:
```
python test/profiler/test_profiler.py TestProfiler.test_cupti_monitor_buffer_pool_reuse
python test/profiler/test_profiler.py TestProfilerCUDA -k cupti_monitor
```
The first test drives the native callbacks directly via ctypes (no CUDA or
cupti-python) and asserts returned buffers are recycled rather than
reallocated; the second exercises the full path through real CUPTI, including a
new assertion that the native pool was actually used.

Authored-with: Claude (Anthropic AI assistant)
Pull Request resolved: #186295
Approved by: https://github.com/dolpm
ghstack dependencies: #186034, #186036, #186037
pytorchmergebot pushed a commit that referenced this pull request Jun 11, 2026
A couple changes for pytorch/kineto#1429 and pytorch/kineto#1430:

1. Add `setUpModule` to make sure Kineto is created with CUDA support. #186036 recently changed the behavior to not initialize Kineto with GPU tracing if only CPU activities are requested, which is more correct behavior. However, this changes the behavior of the following code:

```
with profile(activities=[ProfilerActivity.CPU]) as prof:
   ...

with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
   ...
```

Now Kineto is armed to only do CPU tracing. The issue is that Kineto is only registered once, so even though you added ProfilerActivity.CUDA in the second pass, the profiler still latches on to the CPU-only session, leading to no device-side activities being recorded. We need to find a more complete solution but to unblock the tests we can hack around it by forcing Kineto to instantiate with GPU-tracing before running any tests.

2. Clear KinetoStepTracker to make sure repeat runs with different activity types don't pollute `test_kineto_profiler_multiple_steppers`.
3. Make sure `test_forked_process` explicitly runs with CPU activities only.

There are a few more failures due to test pollution, but I haven't tracked those down yet.
Pull Request resolved: #186970
Approved by: https://github.com/scotts
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
A couple changes for pytorch/kineto#1429 and pytorch/kineto#1430:

1. Add `setUpModule` to make sure Kineto is created with CUDA support. pytorch#186036 recently changed the behavior to not initialize Kineto with GPU tracing if only CPU activities are requested, which is more correct behavior. However, this changes the behavior of the following code:

```
with profile(activities=[ProfilerActivity.CPU]) as prof:
   ...

with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
   ...
```

Now Kineto is armed to only do CPU tracing. The issue is that Kineto is only registered once, so even though you added ProfilerActivity.CUDA in the second pass, the profiler still latches on to the CPU-only session, leading to no device-side activities being recorded. We need to find a more complete solution but to unblock the tests we can hack around it by forcing Kineto to instantiate with GPU-tracing before running any tests.

2. Clear KinetoStepTracker to make sure repeat runs with different activity types don't pollute `test_kineto_profiler_multiple_steppers`.
3. Make sure `test_forked_process` explicitly runs with CPU activities only.

There are a few more failures due to test pollution, but I haven't tracked those down yet.
Pull Request resolved: pytorch#186970
Approved by: https://github.com/scotts
@github-actions
github-actions Bot deleted the gh/ngimel/3/head branch July 5, 2026 02:28
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…#186036)

Derive the Kineto cpuOnly flag from the requested activity set rather
than from whether CUDA or another device backend is present on the
machine.

This keeps CPU-only profiling from arming GPU tracing when the user did
not request any device activities, while preserving the default behavior
when available device activities are included.
Pull Request resolved: pytorch#186036
Approved by: https://github.com/dolpm, https://github.com/scotts
ghstack dependencies: pytorch#186034
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…186037)

Add a hidden experimental profiler backend that uses the CUPTI monitor
for GPU collection while reusing the existing CPU profiler path.

This commit wires the monitor into profiler scheduling and export,
constructs merged Chrome traces, recreates GPU-side user annotations for
Python record_function scopes, maps CUDA runtime events onto the same CPU
thread lanes as stock traces, and keeps eager/graph traces close to the
existing profiler behavior.
Pull Request resolved: pytorch#186037
Approved by: https://github.com/scotts
ghstack dependencies: pytorch#186034, pytorch#186036
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ck (pytorch#186295)

The experimental CUPTI monitor (torch.profiler._cupti_monitor) uses the CUPTI
Activity API, which hands completed records to us only through two callbacks
that CUPTI invokes itself: buffer-requested (asks us for an empty buffer to
fill) and buffer-completed (returns a filled one). The Activity API has no
polling alternative, so using it means registering these callbacks, and CUPTI
calls them synchronously from its own threads while holding its internal lock.

Previously the callbacks were Python/ctypes closures, so CUPTI acquired the GIL
while holding that lock. A thread that holds the GIL and then enters CUPTI/CUDA
can deadlock against such a callback (GIL <-> CUPTI lock inversion). The
callbacks are mandatory and the hazard is intrinsic to running any Python
inside them, so the only fix is to make the callback bodies native.

This moves the buffer pool and completed-buffer queue into C++
(torch/csrc/profiler/cupti_monitor_native.{h,cpp}). The buffer-requested and
buffer-completed callback bodies are now pure C++: they only touch a
mutex-guarded free list and a completed-buffer queue, never Python. The Python
decode thread pulls completed buffers via _cupti_monitor_get_completed(), which
releases the GIL while it blocks on a condition variable, and hands them back
with _cupti_monitor_return_buffer(). Registration with CUPTI still happens on
the Python side via ctypes using the callback addresses exposed in init.cpp, so
the pool/queue/callbacks stay reusable for the per-subscriber _v2 Activity APIs
later: only the registration call would gain a subscriber handle.

The free list is LIFO so a returned buffer is reused while it is still the
warmest in cache. The new torch._C._profiler symbols are added to the
_profiler.pyi stub so callers use direct attribute access instead of getattr.

 v2 (subscriber-scoped) Activity API support

  The same native pool is exposed for cuptiActivityRegisterCallbacks_v2 so a prototype can build on the v2 / user-defined-record API (CUPTI ≥ 13.2) without any
  further C++:

  - _cupti_monitor_buffer_request_callback_address(version) / _cupti_monitor_buffer_complete_callback_address(version) take a version (1 or 2, default 1) and return
  native callbacks with the v1 or v2 CUPTI ABI. Both feed the same pool/queue.
  - v2 does not deliver CUcontext/streamId to the completion callback (they become selectable record fields), so buffers completed on the v2 path report ctx/stream
  as 0.
  - The v2 completion callback snapshots the user-defined record layout — which CUPTI only makes valid for the duration of the callback — once per session (the
  layout is fixed by the field selection). It's exposed via _cupti_monitor_record_layouts() as [(kind, record_size, [(field_id, offset, size), ...]), ...] so a
  decode thread can parse field-selected records after the callback returns. The CUPTI v2 structs are mirrored by ABI in the .cpp so the build needs no v2 header.

  All registration (cuptiSubscribe / cuptiActivityRegisterCallbacks_v2 / cuptiActivityEnable_v2 / the USER_DEFINED_RECORDS attribute) stays on the Python/ctypes side
  for a future prototype.

Test Plan:
```
python test/profiler/test_profiler.py TestProfiler.test_cupti_monitor_buffer_pool_reuse
python test/profiler/test_profiler.py TestProfilerCUDA -k cupti_monitor
```
The first test drives the native callbacks directly via ctypes (no CUDA or
cupti-python) and asserts returned buffers are recycled rather than
reallocated; the second exercises the full path through real CUPTI, including a
new assertion that the native pool was actually used.

Authored-with: Claude (Anthropic AI assistant)
Pull Request resolved: pytorch#186295
Approved by: https://github.com/dolpm
ghstack dependencies: pytorch#186034, pytorch#186036, pytorch#186037
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
A couple changes for pytorch/kineto#1429 and pytorch/kineto#1430:

1. Add `setUpModule` to make sure Kineto is created with CUDA support. pytorch#186036 recently changed the behavior to not initialize Kineto with GPU tracing if only CPU activities are requested, which is more correct behavior. However, this changes the behavior of the following code:

```
with profile(activities=[ProfilerActivity.CPU]) as prof:
   ...

with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
   ...
```

Now Kineto is armed to only do CPU tracing. The issue is that Kineto is only registered once, so even though you added ProfilerActivity.CUDA in the second pass, the profiler still latches on to the CPU-only session, leading to no device-side activities being recorded. We need to find a more complete solution but to unblock the tests we can hack around it by forcing Kineto to instantiate with GPU-tracing before running any tests.

2. Clear KinetoStepTracker to make sure repeat runs with different activity types don't pollute `test_kineto_profiler_multiple_steppers`.
3. Make sure `test_forked_process` explicitly runs with CPU activities only.

There are a few more failures due to test pollution, but I haven't tracked those down yet.
Pull Request resolved: pytorch#186970
Approved by: https://github.com/scotts
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…#186036)

Derive the Kineto cpuOnly flag from the requested activity set rather
than from whether CUDA or another device backend is present on the
machine.

This keeps CPU-only profiling from arming GPU tracing when the user did
not request any device activities, while preserving the default behavior
when available device activities are included.
Pull Request resolved: pytorch#186036
Approved by: https://github.com/dolpm, https://github.com/scotts
ghstack dependencies: pytorch#186034
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…186037)

Add a hidden experimental profiler backend that uses the CUPTI monitor
for GPU collection while reusing the existing CPU profiler path.

This commit wires the monitor into profiler scheduling and export,
constructs merged Chrome traces, recreates GPU-side user annotations for
Python record_function scopes, maps CUDA runtime events onto the same CPU
thread lanes as stock traces, and keeps eager/graph traces close to the
existing profiler behavior.
Pull Request resolved: pytorch#186037
Approved by: https://github.com/scotts
ghstack dependencies: pytorch#186034, pytorch#186036
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ck (pytorch#186295)

The experimental CUPTI monitor (torch.profiler._cupti_monitor) uses the CUPTI
Activity API, which hands completed records to us only through two callbacks
that CUPTI invokes itself: buffer-requested (asks us for an empty buffer to
fill) and buffer-completed (returns a filled one). The Activity API has no
polling alternative, so using it means registering these callbacks, and CUPTI
calls them synchronously from its own threads while holding its internal lock.

Previously the callbacks were Python/ctypes closures, so CUPTI acquired the GIL
while holding that lock. A thread that holds the GIL and then enters CUPTI/CUDA
can deadlock against such a callback (GIL <-> CUPTI lock inversion). The
callbacks are mandatory and the hazard is intrinsic to running any Python
inside them, so the only fix is to make the callback bodies native.

This moves the buffer pool and completed-buffer queue into C++
(torch/csrc/profiler/cupti_monitor_native.{h,cpp}). The buffer-requested and
buffer-completed callback bodies are now pure C++: they only touch a
mutex-guarded free list and a completed-buffer queue, never Python. The Python
decode thread pulls completed buffers via _cupti_monitor_get_completed(), which
releases the GIL while it blocks on a condition variable, and hands them back
with _cupti_monitor_return_buffer(). Registration with CUPTI still happens on
the Python side via ctypes using the callback addresses exposed in init.cpp, so
the pool/queue/callbacks stay reusable for the per-subscriber _v2 Activity APIs
later: only the registration call would gain a subscriber handle.

The free list is LIFO so a returned buffer is reused while it is still the
warmest in cache. The new torch._C._profiler symbols are added to the
_profiler.pyi stub so callers use direct attribute access instead of getattr.

 v2 (subscriber-scoped) Activity API support

  The same native pool is exposed for cuptiActivityRegisterCallbacks_v2 so a prototype can build on the v2 / user-defined-record API (CUPTI ≥ 13.2) without any
  further C++:

  - _cupti_monitor_buffer_request_callback_address(version) / _cupti_monitor_buffer_complete_callback_address(version) take a version (1 or 2, default 1) and return
  native callbacks with the v1 or v2 CUPTI ABI. Both feed the same pool/queue.
  - v2 does not deliver CUcontext/streamId to the completion callback (they become selectable record fields), so buffers completed on the v2 path report ctx/stream
  as 0.
  - The v2 completion callback snapshots the user-defined record layout — which CUPTI only makes valid for the duration of the callback — once per session (the
  layout is fixed by the field selection). It's exposed via _cupti_monitor_record_layouts() as [(kind, record_size, [(field_id, offset, size), ...]), ...] so a
  decode thread can parse field-selected records after the callback returns. The CUPTI v2 structs are mirrored by ABI in the .cpp so the build needs no v2 header.

  All registration (cuptiSubscribe / cuptiActivityRegisterCallbacks_v2 / cuptiActivityEnable_v2 / the USER_DEFINED_RECORDS attribute) stays on the Python/ctypes side
  for a future prototype.

Test Plan:
```
python test/profiler/test_profiler.py TestProfiler.test_cupti_monitor_buffer_pool_reuse
python test/profiler/test_profiler.py TestProfilerCUDA -k cupti_monitor
```
The first test drives the native callbacks directly via ctypes (no CUDA or
cupti-python) and asserts returned buffers are recycled rather than
reallocated; the second exercises the full path through real CUPTI, including a
new assertion that the native pool was actually used.

Authored-with: Claude (Anthropic AI assistant)
Pull Request resolved: pytorch#186295
Approved by: https://github.com/dolpm
ghstack dependencies: pytorch#186034, pytorch#186036, pytorch#186037
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
A couple changes for pytorch/kineto#1429 and pytorch/kineto#1430:

1. Add `setUpModule` to make sure Kineto is created with CUDA support. pytorch#186036 recently changed the behavior to not initialize Kineto with GPU tracing if only CPU activities are requested, which is more correct behavior. However, this changes the behavior of the following code:

```
with profile(activities=[ProfilerActivity.CPU]) as prof:
   ...

with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
   ...
```

Now Kineto is armed to only do CPU tracing. The issue is that Kineto is only registered once, so even though you added ProfilerActivity.CUDA in the second pass, the profiler still latches on to the CPU-only session, leading to no device-side activities being recorded. We need to find a more complete solution but to unblock the tests we can hack around it by forcing Kineto to instantiate with GPU-tracing before running any tests.

2. Clear KinetoStepTracker to make sure repeat runs with different activity types don't pollute `test_kineto_profiler_multiple_steppers`.
3. Make sure `test_forked_process` explicitly runs with CPU activities only.

There are a few more failures due to test pollution, but I haven't tracked those down yet.
Pull Request resolved: pytorch#186970
Approved by: https://github.com/scotts
pytorchmergebot pushed a commit that referenced this pull request Nov 12, 2026
…02625)

**Problem**

On main, the first profiler session in a process was sticky in terms of what it profiled. If it profiled only CPU events, all subsequent profiler sessions would only profile CPU events even if they asked for device events. If it profiled device events, all subsequent profiler sessions would profile device events even if they asked for only CPU events.

This is because on main, Kineto is set up once per process, by the first session, and the `cpuOnly` flag it receives is fixed for the life of the process. #186036 changed that flag from "a device is present" to "this session requested a device activity", so the first session's answer sticks for every later one.

**Fix**

Separate the two concepts: device initialization if present, and "arming" device profiling if requested:

* At initialization, Kineto determines if any devices are present. If they are, they are initialized - this usually does mean calling their drivers to query their existence. That devices are present is kept for the life cycle of the process. We achieve this with the `cpuOnly` flag to `libkineto_init()`.

* Per profiling session, pay attention to the requested activities to determine if we should "arm" device profiling.  We achieve this with a new config key `DEVICE_TRACING_ENABLED` that is passed to the Kineto config. Kineto's implementation now pays attention to if device tracing was enabled in most of the places that before we checked `cpuOnly`.

Device initialization and arming are device specific actions. For CUPTI, this is particularly important because arming requires registering a subscriber, and the v1 APIs only allow one subscriber at a time. If a profiling session is CPU only, we should not prevent other tools from profiling the device.

**Behavior changes**

  1. **Each session decides device tracing for itself.** This is the intended fix.
     - A CPU-only first session no longer leaves later device sessions with no device events.
     - A device session no longer leaves later CPU-only sessions tracing the device (CUPTI, rocprofiler-sdk or XPU PTI).
  2. **CPU-only sessions never record device runtime or driver events** (CUDA, HIP on ROCm, or XPU). On main they appeared in CPU-only sessions once Kineto had been registered with GPU support: after an earlier device
  session, in daemon mode, or under CUDA injection. Filters like `{CPU: ["CUDA_RUNTIME"]}` are still accepted, but now return nothing.
  3. **`_init_for_cuda_graphs` initializes CUPTI again.** On CUDA builds it now runs a CPU+CUDA session. On main it ran a CPU-only legacy `profile()`. When that was the process's first profiler session, it registered
  Kineto without GPU support, so the CUPTI workaround did nothing and every later CUDA session recorded no device events (behavior 1). On ROCm it now returns early, since the workaround is for CUPTI.
  4. **Toggling CUDA or XPU back on starts device tracing only in a running session that traces a device.** On main, `toggle_collection_dynamic(True, [CUDA])` after a toggle off also turned CUDA tracing on in a CPU-only
  session, or after the session had stopped. This follows from 1 and breaks backwards compatibility. This API, however, is rarely used, and this is a necessary consequence of this fix.
  5. **Crash fix:** `toggle_collection_dynamic(True, [CPU])` in a session that doesn't collect CPU now logs a warning and does nothing. On main it segfaulted.
  6. **XPU:** PTI is no longer initialized in a process that only profiles the CPU. When PTI's local view is unavailable, an XPU session logs an error and records no XPU events. On main, the first such session raised
  `RuntimeError` and later ones silently recorded no XPU events. In daemon mode, `import torch` failed.
  7. **HPU and MTIA detection:** calling `profile()` or `supported_activities()` before an HPU or MTIA backend loads no longer hides that device for the rest of the process. On main those calls cached stub hooks.
  `supported_activities()` and Kineto registration now share one device list.
  8. **ROCm:** 1 to 3 apply as on CUDA, with one difference. rocprofiler-sdk must be configured before HSA creates its queues, so its tool still registers when Kineto does, even if the first session profiles only the
  CPU. Registration starts process-wide tracing of code-object loads only. HIP API and kernel tracing start per session, like CUPTI. On main, a CPU-only first session skipped registration entirely, which left later GPU
  sessions empty. Before #186036, registration worked as it does now.

**Test Plan**
Local runs on a CUDA device:

```
# libkineto C++ tests (BUILD_TEST=ON). ConfigLoaderPollThreadExceptionTest
# and InitTest run once, without --gtest_repeat.
for t in build/bin/kineto/*; do $t --gtest_shuffle --gtest_repeat=3; done
build/bin/test_mtia_activity_filter
build/bin/test_xpu_activity_filter

# Python
python test/profiler/test_kineto_registration.py --subprocess
python test/profiler/test_profiler.py
python test/profiler/test_cuspy.py

# OpenReg reference backend, built into a local root as run_test.py --openreg does
cd test/cpp_extensions/open_registration_extension/torch_openreg
python -m pip install --no-build-isolation . --root ./install
LD_LIBRARY_PATH=build/third_party/openreg:build/csrc:$TORCH_LIB build/csrc/openreg_profiler_tests
build/third_party/openreg/ortests
cd ../../.. && PYTHONPATH=$OPENREG_SITE_PACKAGES python cpp_extensions/open_registration_extension/torch_openreg/tests/test_profiler.py
```

Authored with assistance by Claude.
Pull Request resolved: #202625
Approved by: https://github.com/ryanzhang22
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 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants