Skip to content

Add experimental profiler integration for the CUPTI monitor - #186037

Closed
ngimel wants to merge 14 commits into
gh/ngimel/4/basefrom
gh/ngimel/4/head
Closed

ngimel wants to merge 14 commits into
gh/ngimel/4/basefrom
gh/ngimel/4/head

Conversation

@ngimel

@ngimel ngimel commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

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.

[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/186037

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

❌ 3 New Failures

As of commit 9f37f7c with merge base 3e663d6 (image):

NEW FAILURES - The following jobs have failed:

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

ngimel added 6 commits June 2, 2026 22:55
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/autograd/profiler.py Outdated
self.name
)
except Exception:
self._cupti_monitor_external_id = None

@scotts scotts Jun 3, 2026 •

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.

We're doing this on the hot path. We should be able to pull some of this up into __init__(), where we can do something like:

def __init__(self, name: str, args: str | None = None):
    # ...
    self._cupti_monitor: ModuleType | None = None
    try:
        from torch.profiler import _cupti_monitor
        self._cupti_monitor = _cupti_monitor
    except:
        pass 

And then in __enter__():

    if self._cupti_monitor is not None:
        self._cupti_monitor_external_id = self._cupti_monitor.push_user_annotation(
            self.name
        )

And then a similar thing in __exit__(). We might want to also be stricter on the exceptions. Maybe ignore the module-not-found-exceptions, but log on any other kind of exception.

Comment thread torch/profiler/_cupti_monitor_trace.py Resolved
Comment thread torch/profiler/_cupti_monitor_trace.py Resolved
Comment thread torch/profiler/_cupti_monitor_trace.py Resolved
ngimel added 3 commits June 3, 2026 16:02
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/profiler/_cupti_monitor_trace.py Resolved
Comment thread torch/profiler/_cupti_monitor_trace.py Resolved
Comment thread torch/profiler/_cupti_monitor_trace.py Outdated
if (
str(event.get("name")) == "Activity Buffer Request"
and max_non_overhead_end_ns
and _as_int(event.get("start_ns", 0)) > max_non_overhead_end_ns

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.

This exact condition is duplicated above on line 275. Probably worth pulling into a function.

[ghstack-poisoned]
@huydhn

huydhn commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot drci

ngimel added 2 commits June 4, 2026 09:19
[ghstack-poisoned]
[ghstack-poisoned]
@ngimel ngimel added the release notes: profiler release notes category label Jun 4, 2026
@ngimel ngimel added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 4, 2026
[ghstack-poisoned]
@ngimel

ngimel commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

@claude are the "new" test failures related to this PR?

@claude

claude Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 49s —— View job


Analyzing CI Failures

  • Review the reported test failures
  • Compare against PR changes to determine relevance

No, the two new failures are not related to this PR.

The failures are:

  1. inductor/test_torchinductor_dynamic_shapes on linux-jammy-rocm-py3.10-mi355 — This is a TorchInductor dynamic shapes test on ROCm (AMD GPU). This PR doesn't touch any inductor or ROCm code.
  2. test_mps.py::TestConsistencyMPS::test_group_norm_backward_large_input_bfloat16 on macos-py3-arm64 — This is an MPS (Apple Silicon) group norm backward test. This PR doesn't touch any MPS or normalization code.

This PR only modifies profiler-related files (torch/autograd/profiler.py, torch/profiler/profiler.py, torch/profiler/_cupti_monitor_trace.py) and adds profiler tests (test/profiler/test_profiler.py). Neither failure is in profiler test suites or in code paths touched by this PR.


@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 3 checks: trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 6, 10, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (distributed, 4, 4, linux.rocm.gpu.gfx950.2), trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15)

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
…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
@github-actions
github-actions Bot deleted the gh/ngimel/4/head branch July 6, 2026 02:25
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
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
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 release notes: profiler release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants