Skip to content

[ROCm][kineto] Check rocprofiler-sdk return codes and fix RocprofLogger teardown - #199973

Closed
itrowbri wants to merge 5 commits into
pytorch:mainfrom
itrowbri:rocprof-logger-improvements
Closed

itrowbri wants to merge 5 commits into
pytorch:mainfrom
itrowbri:rocprof-logger-improvements

Conversation

@itrowbri

@itrowbri itrowbri commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Supported by @jeffdaily

BC-breaking?

No

Summary (human written only)

Porting over from pytorch/kineto#1421 since previous repository was archived. Description from that PR below:

  • Check return codes of rocprofiler-sdk API calls and log errors
  • Avoid using .handle for opaque types directly
  • Improve finalization variable lifetime and ordering
    • use placement new into buffer in .bss section to prevent destruction of GlobalContext singleton
    • Implement RocprofLogger::endTracing() to force invocation of finalization function
  • Remove superfluous logging_ and registered_ variables
    • can be handled by queries to rocprofiler-sdk API

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Oct 6, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit a0facc9 with merge base b5a6f98 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: itrowbri / name: itrowbri (daf206f)
  • ✅ login: mwootton / name: Michael Wootton (3c3c559)

@mwootton

mwootton commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

I would like to rework this to add the following before merge:

  • Move the check macros into DeviceUtil.h as ROCPROF_CALL / ROCPROF_CALL_THROW, matching the existing CUDA_CALL / CUPTI_CALL / CUPTI_CALL_THROW convention instead of defining a new ad-hoc macro in RocprofLogger.cpp.
  • Propagate failures in toolInit (via the _THROW variant): today a failed create/configure only logs, and init still returns success — registering a tool that traces nothing.
  • Drop or demote the checked stop_context/flush_buffer calls in toolFinalize: the SDK already stops contexts and flushes buffers before invoking fini, so stop_context returns CONTEXT_NOT_FOUND and we log two ERROR lines on every clean shutdown.
  • Remove the context_is_active pre-checks in startLogging/stopLogging: start_context is idempotent and stop_context's NOT_FOUND is the "already stopped" signal, so the query-then-act only adds a race window.
  • Set externalCorrelationEnabled_ unconditionally in startLogging — it currently stays disabled if the context was already active.
  • Justify or restore __hipPushCallConfiguration/__hipPopCallConfiguration in the omitted-API list — removing them will noticeably inflate event volume unless they no longer emit callbacks.

The rest of the features are good as is: kernel_names lock, placement new, etc.

@itrowbri
itrowbri marked this pull request as ready for review October 7, 2026 17:08
Copilot AI balanced review requested due to automatic review settings October 7, 2026 17:08
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot missing actionable issue A PR without a linked actionable issue or maintainer sponsor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 7, 2026

Copilot AI left a comment

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.

🟡 Changes recommended

The changed singleton construction order can destroy logger state before profiler threads finish using it.

2 open findings
What changed in this PR

Updates Kineto’s ROCm profiler logging with SDK error handling, opaque-handle usage, and revised shutdown management.

Changes:

  • Adds status-checking macros and initialization failure handling.
  • Reworks context lifetime and explicit finalization.
  • Synchronizes kernel-name lookup and removes redundant state flags.
File Description
third_party/​kineto/​libkineto/​src/​RocprofLogger.h Adds SDK declarations and removes redundant flags.
third_party/​kineto/​libkineto/​src/​RocprofLogger.cpp Updates initialization, shutdown, handle usage, and locking.
third_party/​kineto/​libkineto/​src/​DeviceUtil.h Adds logging and throwing wrappers for SDK calls.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@mwootton
mwootton force-pushed the rocprof-logger-improvements branch from 3c3c559 to 2f86b22 Compare October 7, 2026 17:25
@jeffdaily jeffdaily changed the title Improvements to RocprofLogger - #1421 [ROCm][kineto] Check rocprofiler-sdk return codes and fix RocprofLogger teardown Oct 9, 2026
@jeffdaily jeffdaily added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 9, 2026
@pytorch-bot pytorch-bot Bot added the module: rocm AMD GPU support for Pytorch label Oct 9, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@jeffdaily jeffdaily added open source and removed missing actionable issue A PR without a linked actionable issue or maintainer sponsor bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module open source labels Oct 9, 2026
@github-actions
github-actions Bot requested a review from jeffdaily October 9, 2026 21:58

@jeffdaily jeffdaily 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.

My agent came up with this analysis, but I've read and approved it.

  1. Please add a test plan: at minimum python test/profiler/test_profiler.py passing on a ROCm 7.x host, plus confirmation that process exit is clean (no rocprofiler-sdk ERROR logs from toolFinalize/endTracing). The finalizer and teardown changes are not covered by any existing assertion.
  2. Nit: scope the new kernel_lock in buffer_callback to the kernel_names lookup instead of holding it across row construction and insert_row_to_buffer.

@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 12, 2026
@itrowbri

Copy link
Copy Markdown
Contributor Author

Rebased, which is why I think the new code owner review request was added. I'll hit the last two comments I missed in a separate push

@itrowbri

Copy link
Copy Markdown
Contributor Author

The remaining comments have been addressed if you a re-review is desired now as an update

Guard a null rocprofiler_get_status_string() result in ROCPROF_CALL, ROCPROF_CALL_THROW and the stopLogging() warning, as CUPTI_CALL_THROW does; fmt::format throws on a null const char*.

Remove the isValid == 0 check after the main context's rocprofiler_context_is_valid(). The SDK sets isValid to 1 exactly when it returns SUCCESS (ROCm 6.2 through current develop), and ROCPROF_CALL_THROW already throws on any other status, so the branch was unreachable.

Correct the stopLogging() comments: rocprofiler_stop_context() does not finalize or wait for in-flight kernel dispatch records (a dispatch is bound to the contexts active at enqueue and its record is written when the kernel completes), and the logger singletons are now leaky, so no destructor calls stopLogging().

Authored with Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator

My agent came up with this analysis, but I've read and approved it.

I pushed a0facc9 to address the remaining review comments: rocprofStatusString() null-guards rocprofiler_get_status_string() in ROCPROF_CALL, ROCPROF_CALL_THROW and the stopLogging() warning; the isValid == 0 check is removed (the SDK sets isValid to 1 exactly when it returns SUCCESS, in every release from ROCm 6.2 through develop, and ROCPROF_CALL_THROW already throws otherwise); and the stopLogging() comments now say that stopping the context does not wait for in-flight kernel dispatch records.

Test plan, run on gfx90a (MI250X) and gfx1100 (W7800) with ROCm 10.1 (rocprofiler-sdk 1.4.1):

  • test/profiler/test_profiler.py: 162 passed, 12 failed, 18 skipped. The 12 failures (test_source_multithreaded_* and test_kernel_metadata_*, which expect a grid field) fail identically on the PR's merge-base and on current main, so none are new.
  • test/profiler/test_kineto.py, test_profiler_tree.py and test_execution_trace.py: all pass.
  • Process exit after a profiled session, after two sessions, after CPU-only profiling and with no profiler: exit code 0 and no rocprofiler-sdk or kineto error output on either GPU.
  • Exiting with a profiler session still open segfaults on gfx90a, in api_callback's thread_local timestamps map during hipBLASLt's static teardown. It does the same on the merge-base, so it is not caused by this PR; I will follow up separately.

The stop-then-flush reorder does not change ROCm/TheRock#9008. In an A/B on the same build the miss rate was unchanged (gfx90a, rocprofiler-sdk 1.4.1: 13 to 21 of 64 sessions on the merge-base, 12 to 19 with this PR). That race needs a bounded wait for outstanding kernel-dispatch records, which I will put up on top of this PR.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

This PR has pending changes requested. Please address the comments and update the PR before merging.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@scotts your remaining comments (the null rocprofiler_get_status_string() result and the dead isValid branch) are addressed in a0facc9, and the test plan results are in the comment above. Could you re-review? Your earlier changes-requested review is what blocks the merge now.

@jeffdaily
jeffdaily dismissed scotts’s stale review October 28, 2026 20:49

All requested changes are addressed in a0facc9 (see the comments above); dismissing to unblock the merge.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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 Oct 30, 2026
#202665)

## Linked issue or supporting maintainer

Related: #199973 (found while testing it)

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

The torch.profiler for ROCm could segfault at process exit if a profiling session was still running, because it used thread-local state that had already been destroyed.

## Agent details (if applicable)

My agent came up with this analysis, but I've read and approved it.

**Problem.** A process that exits while a `torch.profiler` session with GPU activity is still running can segfault on ROCm. On gfx90a with hipBLASLt it crashes on every exit; on other archs and on the rocBLAS path it depends on what is left in freed memory (`MALLOC_PERTURB_=165` makes those crash too).

**Cause.** `exit()` destroys the main thread's thread_locals before the static destructors of rocBLAS and hipBLASLt run. Those destructors call `hipModuleUnload`, which rocprofiler-sdk still traces, so `RocprofLogger::api_callback` indexes its destroyed `thread_local` timestamp map. Per-thread-buffer mode and the correlation-id stacks touch destroyed thread_locals the same way.

**Change.** `api_callback` keeps the ENTER timestamp in the SDK's per-call `user_data`, which rocprofiler-sdk retains from the ENTER to the EXIT phase of one call, so the map is gone (and with it a hash insert and erase per traced HIP call). The remaining per-thread state (correlation-id stacks and the per-thread buffer) moves into one `thread_local ThreadState` whose destructor sets a trivially destructible `t_threadExiting` flag before its members are destroyed; once set, `api_callback` and the correlation push/pop return early and rows go to the shared buffer. The HIP calls dropped this way are those a thread makes after its kineto state is gone: for the main thread that is inside `exit()`, where no session can collect them; a worker thread exiting during a session loses its last such calls, which were undefined behaviour before. The new `test_profiler_left_running_at_exit_cuda` exits a subprocess with the profiler running under `MALLOC_PERTURB_=165`.

**Test plan.**

gfx90a (MI250X) and gfx1100 (W7800), TheRock ROCm 10.1 (rocprofiler-sdk 1.4.1), on main 9c0fed7, A/B by reverting `RocprofLogger.cpp`. Exit codes of a script that starts a CPU+CUDA profile, runs a matmul and exits without stopping (139 = SIGSEGV):

| BLAS path | env | gfx90a without fix | gfx1100 without fix | with fix (both GPUs) |
|---|---|---|---|---|
| hipBLASLt | plain | 139 x3 | 139 x3 | 0 x15 |
| hipBLASLt | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |
| rocBLAS | plain | 0 x3 | 0 x3 | 0 x15 |
| rocBLAS | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |

The backtrace without the fix is `api_callback` -> destroyed `thread_local` map, called from `hipModuleUnload` in hipBLASLt's or rocBLAS's `TensileHost` destructor inside `exit()`.

```
python test/profiler/test_profiler.py -k test_profiler_left_running_at_exit_cuda
python test/profiler/test_profiler.py
python test/profiler/test_kineto.py
python test/profiler/test_profiler_tree.py
```

- The new test fails 6/6 without the fix (`Expected 0 but got -11`) and passes 6/6 with it on both GPUs, with hipBLASLt and with `TORCH_BLAS_PREFER_HIPBLASLT=0`.
- With the fix, `KINETO_USE_DAEMON=1` and per-thread buffers (`ROCPROF_PER_THREAD_BUFFER_ENABLED=true`, confirmed active) also exit 0 under `MALLOC_PERTURB_=165`.
- `test_profiler.py`, `test_kineto.py`, `test_profiler_tree.py`: no new failures (the two `TestMetadataJsonFormatCUDA` `grid` failures fail the same way without the fix).

Pull Request resolved: #202665
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…er teardown (pytorch#199973)

## Linked issue or supporting maintainer

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

Porting over from pytorch/kineto#1421 since previous repository was archived. Description from that PR below:

- Check return codes of rocprofiler-sdk API calls and log errors
- Avoid using .handle for opaque types directly
- Improve finalization variable lifetime and ordering
   - use placement new into buffer in .bss section to prevent destruction of GlobalContext singleton
   - Implement RocprofLogger::endTracing() to force invocation of finalization function
- Remove superfluous logging_ and registered_ variables
   - can be handled by queries to rocprofiler-sdk API

Pull Request resolved: pytorch#199973
Approved by: https://github.com/jeffdaily

Co-authored-by: Michael Wootton <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
pytorch#202665)

## Linked issue or supporting maintainer

Related: pytorch#199973 (found while testing it)

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

The torch.profiler for ROCm could segfault at process exit if a profiling session was still running, because it used thread-local state that had already been destroyed.

## Agent details (if applicable)

My agent came up with this analysis, but I've read and approved it.

**Problem.** A process that exits while a `torch.profiler` session with GPU activity is still running can segfault on ROCm. On gfx90a with hipBLASLt it crashes on every exit; on other archs and on the rocBLAS path it depends on what is left in freed memory (`MALLOC_PERTURB_=165` makes those crash too).

**Cause.** `exit()` destroys the main thread's thread_locals before the static destructors of rocBLAS and hipBLASLt run. Those destructors call `hipModuleUnload`, which rocprofiler-sdk still traces, so `RocprofLogger::api_callback` indexes its destroyed `thread_local` timestamp map. Per-thread-buffer mode and the correlation-id stacks touch destroyed thread_locals the same way.

**Change.** `api_callback` keeps the ENTER timestamp in the SDK's per-call `user_data`, which rocprofiler-sdk retains from the ENTER to the EXIT phase of one call, so the map is gone (and with it a hash insert and erase per traced HIP call). The remaining per-thread state (correlation-id stacks and the per-thread buffer) moves into one `thread_local ThreadState` whose destructor sets a trivially destructible `t_threadExiting` flag before its members are destroyed; once set, `api_callback` and the correlation push/pop return early and rows go to the shared buffer. The HIP calls dropped this way are those a thread makes after its kineto state is gone: for the main thread that is inside `exit()`, where no session can collect them; a worker thread exiting during a session loses its last such calls, which were undefined behaviour before. The new `test_profiler_left_running_at_exit_cuda` exits a subprocess with the profiler running under `MALLOC_PERTURB_=165`.

**Test plan.**

gfx90a (MI250X) and gfx1100 (W7800), TheRock ROCm 10.1 (rocprofiler-sdk 1.4.1), on main 9c0fed7, A/B by reverting `RocprofLogger.cpp`. Exit codes of a script that starts a CPU+CUDA profile, runs a matmul and exits without stopping (139 = SIGSEGV):

| BLAS path | env | gfx90a without fix | gfx1100 without fix | with fix (both GPUs) |
|---|---|---|---|---|
| hipBLASLt | plain | 139 x3 | 139 x3 | 0 x15 |
| hipBLASLt | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |
| rocBLAS | plain | 0 x3 | 0 x3 | 0 x15 |
| rocBLAS | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |

The backtrace without the fix is `api_callback` -> destroyed `thread_local` map, called from `hipModuleUnload` in hipBLASLt's or rocBLAS's `TensileHost` destructor inside `exit()`.

```
python test/profiler/test_profiler.py -k test_profiler_left_running_at_exit_cuda
python test/profiler/test_profiler.py
python test/profiler/test_kineto.py
python test/profiler/test_profiler_tree.py
```

- The new test fails 6/6 without the fix (`Expected 0 but got -11`) and passes 6/6 with it on both GPUs, with hipBLASLt and with `TORCH_BLAS_PREFER_HIPBLASLT=0`.
- With the fix, `KINETO_USE_DAEMON=1` and per-thread buffers (`ROCPROF_PER_THREAD_BUFFER_ENABLED=true`, confirmed active) also exit 0 under `MALLOC_PERTURB_=165`.
- `test_profiler.py`, `test_kineto.py`, `test_profiler_tree.py`: no new failures (the two `TestMetadataJsonFormatCUDA` `grid` failures fail the same way without the fix).

Pull Request resolved: pytorch#202665
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…er teardown (pytorch#199973)

## Linked issue or supporting maintainer

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

Porting over from pytorch/kineto#1421 since previous repository was archived. Description from that PR below:

- Check return codes of rocprofiler-sdk API calls and log errors
- Avoid using .handle for opaque types directly
- Improve finalization variable lifetime and ordering
   - use placement new into buffer in .bss section to prevent destruction of GlobalContext singleton
   - Implement RocprofLogger::endTracing() to force invocation of finalization function
- Remove superfluous logging_ and registered_ variables
   - can be handled by queries to rocprofiler-sdk API

Pull Request resolved: pytorch#199973
Approved by: https://github.com/jeffdaily

Co-authored-by: Michael Wootton <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
pytorch#202665)

## Linked issue or supporting maintainer

Related: pytorch#199973 (found while testing it)

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

The torch.profiler for ROCm could segfault at process exit if a profiling session was still running, because it used thread-local state that had already been destroyed.

## Agent details (if applicable)

My agent came up with this analysis, but I've read and approved it.

**Problem.** A process that exits while a `torch.profiler` session with GPU activity is still running can segfault on ROCm. On gfx90a with hipBLASLt it crashes on every exit; on other archs and on the rocBLAS path it depends on what is left in freed memory (`MALLOC_PERTURB_=165` makes those crash too).

**Cause.** `exit()` destroys the main thread's thread_locals before the static destructors of rocBLAS and hipBLASLt run. Those destructors call `hipModuleUnload`, which rocprofiler-sdk still traces, so `RocprofLogger::api_callback` indexes its destroyed `thread_local` timestamp map. Per-thread-buffer mode and the correlation-id stacks touch destroyed thread_locals the same way.

**Change.** `api_callback` keeps the ENTER timestamp in the SDK's per-call `user_data`, which rocprofiler-sdk retains from the ENTER to the EXIT phase of one call, so the map is gone (and with it a hash insert and erase per traced HIP call). The remaining per-thread state (correlation-id stacks and the per-thread buffer) moves into one `thread_local ThreadState` whose destructor sets a trivially destructible `t_threadExiting` flag before its members are destroyed; once set, `api_callback` and the correlation push/pop return early and rows go to the shared buffer. The HIP calls dropped this way are those a thread makes after its kineto state is gone: for the main thread that is inside `exit()`, where no session can collect them; a worker thread exiting during a session loses its last such calls, which were undefined behaviour before. The new `test_profiler_left_running_at_exit_cuda` exits a subprocess with the profiler running under `MALLOC_PERTURB_=165`.

**Test plan.**

gfx90a (MI250X) and gfx1100 (W7800), TheRock ROCm 10.1 (rocprofiler-sdk 1.4.1), on main 9c0fed7, A/B by reverting `RocprofLogger.cpp`. Exit codes of a script that starts a CPU+CUDA profile, runs a matmul and exits without stopping (139 = SIGSEGV):

| BLAS path | env | gfx90a without fix | gfx1100 without fix | with fix (both GPUs) |
|---|---|---|---|---|
| hipBLASLt | plain | 139 x3 | 139 x3 | 0 x15 |
| hipBLASLt | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |
| rocBLAS | plain | 0 x3 | 0 x3 | 0 x15 |
| rocBLAS | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |

The backtrace without the fix is `api_callback` -> destroyed `thread_local` map, called from `hipModuleUnload` in hipBLASLt's or rocBLAS's `TensileHost` destructor inside `exit()`.

```
python test/profiler/test_profiler.py -k test_profiler_left_running_at_exit_cuda
python test/profiler/test_profiler.py
python test/profiler/test_kineto.py
python test/profiler/test_profiler_tree.py
```

- The new test fails 6/6 without the fix (`Expected 0 but got -11`) and passes 6/6 with it on both GPUs, with hipBLASLt and with `TORCH_BLAS_PREFER_HIPBLASLT=0`.
- With the fix, `KINETO_USE_DAEMON=1` and per-thread buffers (`ROCPROF_PER_THREAD_BUFFER_ENABLED=true`, confirmed active) also exit 0 under `MALLOC_PERTURB_=165`.
- `test_profiler.py`, `test_kineto.py`, `test_profiler_tree.py`: no new failures (the two `TestMetadataJsonFormatCUDA` `grid` failures fail the same way without the fix).

Pull Request resolved: pytorch#202665
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
jeffdaily added a commit to ROCm/pytorch that referenced this pull request Dec 3, 2026
…er teardown (pytorch#199973)

## Linked issue or supporting maintainer

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

Porting over from pytorch/kineto#1421 since previous repository was archived. Description from that PR below:

- Check return codes of rocprofiler-sdk API calls and log errors
- Avoid using .handle for opaque types directly
- Improve finalization variable lifetime and ordering
   - use placement new into buffer in .bss section to prevent destruction of GlobalContext singleton
   - Implement RocprofLogger::endTracing() to force invocation of finalization function
- Remove superfluous logging_ and registered_ variables
   - can be handled by queries to rocprofiler-sdk API

Pull Request resolved: pytorch#199973
Approved by: https://github.com/jeffdaily

Co-authored-by: Michael Wootton <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
(cherry picked from commit a25f5e0)
jeffdaily added a commit to ROCm/pytorch that referenced this pull request Dec 3, 2026
pytorch#202665)

Related: pytorch#199973 (found while testing it)

Supported by @jeffdaily

No

The torch.profiler for ROCm could segfault at process exit if a profiling session was still running, because it used thread-local state that had already been destroyed.

My agent came up with this analysis, but I've read and approved it.

**Problem.** A process that exits while a `torch.profiler` session with GPU activity is still running can segfault on ROCm. On gfx90a with hipBLASLt it crashes on every exit; on other archs and on the rocBLAS path it depends on what is left in freed memory (`MALLOC_PERTURB_=165` makes those crash too).

**Cause.** `exit()` destroys the main thread's thread_locals before the static destructors of rocBLAS and hipBLASLt run. Those destructors call `hipModuleUnload`, which rocprofiler-sdk still traces, so `RocprofLogger::api_callback` indexes its destroyed `thread_local` timestamp map. Per-thread-buffer mode and the correlation-id stacks touch destroyed thread_locals the same way.

**Change.** `api_callback` keeps the ENTER timestamp in the SDK's per-call `user_data`, which rocprofiler-sdk retains from the ENTER to the EXIT phase of one call, so the map is gone (and with it a hash insert and erase per traced HIP call). The remaining per-thread state (correlation-id stacks and the per-thread buffer) moves into one `thread_local ThreadState` whose destructor sets a trivially destructible `t_threadExiting` flag before its members are destroyed; once set, `api_callback` and the correlation push/pop return early and rows go to the shared buffer. The HIP calls dropped this way are those a thread makes after its kineto state is gone: for the main thread that is inside `exit()`, where no session can collect them; a worker thread exiting during a session loses its last such calls, which were undefined behaviour before. The new `test_profiler_left_running_at_exit_cuda` exits a subprocess with the profiler running under `MALLOC_PERTURB_=165`.

**Test plan.**

gfx90a (MI250X) and gfx1100 (W7800), TheRock ROCm 10.1 (rocprofiler-sdk 1.4.1), on main 9c0fed7, A/B by reverting `RocprofLogger.cpp`. Exit codes of a script that starts a CPU+CUDA profile, runs a matmul and exits without stopping (139 = SIGSEGV):

| BLAS path | env | gfx90a without fix | gfx1100 without fix | with fix (both GPUs) |
|---|---|---|---|---|
| hipBLASLt | plain | 139 x3 | 139 x3 | 0 x15 |
| hipBLASLt | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |
| rocBLAS | plain | 0 x3 | 0 x3 | 0 x15 |
| rocBLAS | `MALLOC_PERTURB_=165` | 139 x3 | 139 x3 | 0 x15 |

The backtrace without the fix is `api_callback` -> destroyed `thread_local` map, called from `hipModuleUnload` in hipBLASLt's or rocBLAS's `TensileHost` destructor inside `exit()`.

```
python test/profiler/test_profiler.py -k test_profiler_left_running_at_exit_cuda
python test/profiler/test_profiler.py
python test/profiler/test_kineto.py
python test/profiler/test_profiler_tree.py
```

- The new test fails 6/6 without the fix (`Expected 0 but got -11`) and passes 6/6 with it on both GPUs, with hipBLASLt and with `TORCH_BLAS_PREFER_HIPBLASLT=0`.
- With the fix, `KINETO_USE_DAEMON=1` and per-thread buffers (`ROCPROF_PER_THREAD_BUFFER_ENABLED=true`, confirmed active) also exit 0 under `MALLOC_PERTURB_=165`.
- `test_profiler.py`, `test_kineto.py`, `test_profiler_tree.py`: no new failures (the two `TestMetadataJsonFormatCUDA` `grid` failures fail the same way without the fix).

Pull Request resolved: pytorch#202665
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
(cherry picked from commit 45b310d)
jeffdaily pushed a commit to ROCm/pytorch that referenced this pull request Dec 3, 2026
…me fill/copy kernels as memset/memcpy (pytorch#200296)

Supported by @jeffdaily

Continuation of pytorch/kineto#1418
Fixes: pytorch#198442
Fixes: pytorch#187119
Fixes: pytorch#180072
Fixes: pytorch#179944

No API change. On ROCm, trace outputs change for the same workload:

- The runtime's fill/copy dispatches (`__amd_rocclr_fill*`/`__amd_rocclr_copyBuffer*`) move from `cat: "kernel"` to `gpu_memset`/`gpu_memcpy` events, as on CUDA. They are renamed, which changes `key_averages()` keys and `FunctionEvent.name`; they lose grid/block and gain bytes; the `kind` goes from "Dispatch Kernel" to none (memset) or a copy direction (memcpy); and they are now filtered by the GPU_MEMSET/GPU_MEMCPY masks instead of CONCURRENT_KERNEL.
- hipExtModuleLaunchKernel/hipHccModuleLaunchKernel runtime events (Tensile `Cijk*` GEMMs) report `grid` in workgroups instead of the global work size, matching the kernel event.
- A fill or copy that the runtime splits into several GPU records reports its bytes on the first record only, and none of the records reports a bandwidth.

Some unit tests were still missing metadata for some kernels.  This was due to a combination of bad test implementation and a unique feature of rocprofiler-sdk.  Often the runtime use blit kernels for memcpy, memset, etc.  Roctracer and Cupti report these as opaque memory operations, rocprofiler-sdk faithfully report the underlying kernels, e.g. __amd_rocclr_copyBuffer.kd.

The flawed tests were grabbing those implicit kernels, and not finding the metadata they were expecting.

Fix:

- Mark those blit kernels as gpu_memset/gpu_memcpy GPU ops instead of kernel
- Collect grid/block from the dispatch (KERNEL_DISPATCH buffer) record itself

My agent came up with this analysis, but I've read and approved it.

On the rocprofiler-sdk path, kernel grid/block came only from correlating a HIP launch-API record, so kernels with no launch API (hipGraphLaunch replays, and the rocclr fill/copy kernels behind hipMemset*/hipMemcpy*) had no dims, which is why TestMetadataJsonFormat could not find `grid` on ROCm. This PR reads grid/block from the KERNEL_DISPATCH record (global size converted to workgroups, rounding up); the hipExtModuleLaunchKernel and hipHccModuleLaunchKernel runtime events now also report workgroups instead of the global work size, so the launch and the kernel agree.

hipMemset* calls now produce a runtime row that carries their byte count (sizeBytes, width x height x depth, or count x element size) and stream. Dispatches that share the correlation id of a hipMemset*/hipMemcpy* call are reported as gpu_memset/gpu_memcpy, as CUPTI reports them, with the call's byte count and stream, and every memset/copy call starts an ac2g flow. Kernel-implemented copies emit no MEMORY_COPY record, so nothing is counted twice. When the runtime splits one call into several GPU records, one of them carries the bytes and none reports a bandwidth. The byte count of SDMA MEMORY_COPY records also comes from the copy call's row now, so the thread_local correlation maps (grid, block and size) are all removed. Copy byte counts now cover 2D copies (width x height) and array copies (count), and the `_spt` variants of the copy APIs are classified like the memset `_spt` variants already were.

Tests: test_kineto now requires a device-side memcpy event on CUDA/ROCm (the CPU runtime call is also named memcpy, so the old check could not fail); new TestMetadataJsonFormatCUDA tests cover kernel dims for eager and graph-replayed kernels (and, on ROCm, equality with the launch API's grid/block), memcpy and memset reclassification with byte totals, and memset flows, each profiling after one discarded warmup session; RocmActivityProfilerTest covers copy direction, memset and copy byte counts, classification (including SDMA records, split calls and a second classification pass), the emitted name/type/metadata of reclassified rows, the output filter, and flow starts.

Not covered, and unchanged from before (these dispatches were kernels or lacked the field before this PR too): memset and copy nodes replayed by hipGraphLaunch are still reported as kernels, because their dispatches carry the graph launch's correlation id and classifying them would need the kernel name; hipMemcpy3D* and hipMemcpyParam2D* copies have no byte count (their sizes are inside a struct argument); copies issued with hipMemcpyDefault through hipMemcpy/hipMemcpyAsync are named `Memcpy <unknown> (? -> ?)` because the direction is not in the call's arguments. Only the copy APIs listed in `isCopyApi` are classified; the array copies added in HIP_RUNTIME_API_TABLE_STEP_VERSION 3 (hipMemcpyAtoD, DtoA, AtoA, AtoHAsync, HtoAAsync, 2DArrayToArray) and hipDrvMemcpy* are not, and PyTorch issues none of them.

The first landing was reverted because the `hipMemsetD2D*` rocprofiler IDs do not exist in ROCm 7.0's SDK; 6c79b5b guards them on `HIP_RUNTIME_API_TABLE_STEP_VERSION >= 14`. This update merges viable/strict (kineto moved to torch/csrc/profiler/kineto; the changes carried over unchanged) and removes the two remaining ROCm skips the `Fixes` lines refer to: `test_kineto_kernel_metadata_in_trace` (pytorch#180072) and `test_structured_metadata_matches_chrome_trace` (pytorch#179944, whose skip was re-added by the pytorch#198324 test move after pytorch#196487 fixed it).

Test plan (done with Claude): built and ran on MI300X with ROCm 7.0.0 (rocprofiler-sdk 1.0.0, STEP_VERSION 13, so the guard drops the labels) and MI300X with ROCm 10.1. On both, every kineto source compiles with no warnings, the full test_profiler.py runs 207 tests OK with 16 skipped, RocmActivityProfilerTest passes 20/20, and each new or changed test passes when run alone in a fresh process. On a V100 with a CUDA 12.6 nightly, the changed TestMetadataJsonFormatCUDA tests and test_kineto_cuda pass alone in a fresh process. Without the change, `test_kernel_metadata_has_expected_fields` / `test_kernel_metadata_field_types` fail (`'grid' not found`) and so do the new tests. Sessions that got no kernel dispatch record at all on MI300X with ROCm 10.1 (rocprofiler-sdk delivering late dispatch records, ROCm/TheRock#9008) are fixed by pytorch#202758.
```
python test/profiler/test_profiler.py -k TestMetadataJsonFormatCUDA
python test/profiler/test_profiler.py -k test_kineto_cuda
python test/profiler/test_profiler.py -k test_kineto_kernel_metadata_in_trace
python test/profiler/test_profiler.py -k test_structured_metadata_matches_chrome_trace
python test/profiler/test_profiler.py
```

Pull Request resolved: pytorch#200296
Approved by: https://github.com/jeffdaily

Co-authored-by: Jithun Nair <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
(cherry picked from commit 1ab6780)

[release/2.15 adaptation, by mwootton]
- Kineto paths landed under third_party/kineto (2.15 predates the vendoring
  move to torch/csrc/profiler/kineto).
- The three prerequisite ROCm kineto fixes (pytorch#199973, pytorch#202665, pytorch#202758) were
  cherry-picked ahead of this commit; this branch's kineto snapshot (Oct 2)
  predates them.
- test_profiler.py: kept on the pre-split TestMetadataJsonFormat class (the
  CUDA split landed after the branch cut); added @instantiate_parametrized_tests
  to that class so the new parameterized test is collected; dropped the
  skipXPUIf decorator hunk (added upstream after the cut).

Fixes ROCM-31589
Fixes ROCM-29809
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triage-error ciflow/trunk Trigger trunk jobs on your pull request Merged module: rocm AMD GPU support for Pytorch open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants