Skip to content

[Profiler] Decide Kineto GPU tracing per session, not per process - #202625

Closed
scotts wants to merge 41 commits into
pytorch:mainfrom
scotts:profiler-kineto-per-session-gpu
Closed

scotts wants to merge 41 commits into
pytorch:mainfrom
scotts:profiler-kineto-per-session-gpu

Conversation

@scotts

@scotts scotts commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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 Fix CPU-only profiler mode to avoid initializing GPU tracing #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.

**Problem**

If the first profiler session in a process requests only CPU activity, every
later CUDA session silently records no device events and no CUDA runtime
events. The legacy torch.autograd.profiler.profile() default triggers it, as do
torch.profiler._utils._init_for_cuda_graphs() and Inductor's
TorchProfilerBenchmarker, which then fails with "'_CALLABLE' CUDA event not
found".

libkineto is set up once per process, by the first session, and the cpuOnly
flag it receives is fixed for the life of the process. pytorch#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. The reverse order
leaks too: once a CUDA session has run, later CPU-only sessions arm CUPTI and
record CUDA runtime events. pytorch#186970 and pytorch#198209 worked around the first problem
by priming Kineto with a CUDA session in three test modules.

pytorch#186036's goal still stands: a session that requests no device activity must
not touch CUPTI, which Cuspy may own.

**Fix**

Split the flag in two. libkineto is again registered with GPU support whenever
a device is present. Registration touches no CUPTI, because Kineto subscribes
only when a trace enables GPU tracing. Each trace then decides whether to arm
the GPU tracer through a new libkineto config key, GPU_TRACING_ENABLED, which
kineto_shim sets from the session's requested activities.
GenericActivityProfiler::shouldTraceGpu() gates every per-trace GPU path on it,
and the XPU child profiler honors it too. The key defaults to true, so
on-demand traces behave as before.

The alternative was to register CPU-only and upgrade on the first device
session. After the upgrade, CPU-only sessions would arm CUPTI again, and the
upgrade would need new APIs to change state on the live proxy, controller, and
profiler.

_init_for_cuda_graphs now uses torch.profiler.profile(), whose default
activities include CUDA, so it initializes CUPTI as intended. The test priming
and its helper are removed. test_cuspy.py inherited its priming from
test_profiler.py; every in-process session there is a Cuspy session, which
Kineto sees as CPU-only.

Review the libkineto gate first (Config, GenericActivityProfiler), then the
PyTorch side (kineto_shim.cpp, profiler_kineto.cpp), then the tests.

**Test Plan**

test_device_tracing_decided_per_session runs CPU, CPU+CUDA, and CPU sessions in
a fresh process. It checks that only the CUDA session records device and CUDA
runtime events, and it fails before this change.
GpuTracingFollowsEachTraceConfig checks the libkineto gate with a mock GPU
profiler. test_cudagraph_profiling_workaround now asserts that its CUDA session
captured device events; before, it passed without capturing any.

```
python test/profiler/test_profiler.py -k test_device_tracing_decided_per_session -k test_cudagraph_profiling_workaround
for b in build/bin/kineto/*; do $b --gtest_shuffle --gtest_repeat=3; done
python test/profiler/test_profiler.py
python test/test_linalg.py -k test_norm_fused_type_promotion -k test_matmul_folds_viewable_size_one_dim -k test_addmm_out_distinct_c_and_d -k test_rowwise_scaled_gemm_numerics_tunableop
python test/profiler/test_cuspy.py
```

All Kineto C++ tests pass, except that ConfigLoaderPollThreadExceptionTest
passes once but not on repeats in one process, because of ConfigLoader
singleton state that predates this change. The full test_profiler.py run has
four failures that predate this change: test_disable_external_correlation_cuda,
test_kineto_cuda, test_profiler_cuda, and
test_trace_only_export_matches_default_cuda. On my devvm, Kineto drops device
records some tens of seconds into a process. Each test passes alone, and all
four pass in one process right after a CPU-only test. cupti-python is not
installed locally, so 84 test_cuspy.py tests skipped, and the XPU change was not
compiled.

This PR was authored with the assistance of an AI assistant (Claude).
@pytorch-bot pytorch-bot Bot added ciflow/xpu Run XPU CI tasks release notes: linalg_frontend release notes category labels Oct 29, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR registers Kineto with device support once per process whenever a device
is present, and a new per-session `DEVICE_TRACING_ENABLED` config key decides
whether each session arms CUPTI, rocprofiler-sdk, PTI, the PM sampler and the
child profilers. Recommendation: Approve. Nothing blocks, ryanzhang22's
maintainer comments are resolved, and every point raised is non-blocking.

Findings (6):

[minor] torch/csrc/profiler/kineto_shim.cpp:488
Non-blocking: CPU-only sessions request collectives that nothing collects on
XPU. `kineto_shim.cpp:462-464` still adds `COLLECTIVE_COMM` to CPU-only sessions
when `collectivesProfilerExists()` is true, and lines 487-489 then send
`DEVICE_TRACING_ENABLED=false` for those same sessions. On XPU, PTI collects
`COLLECTIVE_COMM` (`XpuptiActivityApi.cpp:233-234` maps it to
`PTI_VIEW_COMMUNICATION`), and `XPUActivityProfiler::configure` now returns
`nullptr` for those sessions. Before this PR, once Kineto had been registered
with XPU support, a CPU-only session did collect these events. Behavior change 2
in the description mentions only runtime and driver events. Pick one rule and
state it in the `IActivityProfiler.h:158-162` contract comment: either
collectives count as device tracing and CPU-only sessions stop requesting
`COLLECTIVE_COMM`, or collectives are exempt from the contract.

[minor] torch/csrc/profiler/kineto/libkineto/src/GenericActivityProfiler.cpp:612
Non-blocking: device toggles fail silently and the docstring doesn't say so.
`toggle_collection_dynamic(True, [CUDA/XPU])` skips `enableGpuTracing()` without
logging anything when `gpuTracingArmed_` is false, i.e. in a CPU-only session or
after the session has stopped (`GenericActivityProfiler.cpp:610-631`). The CPU
equivalent does log a warning (`profiler_kineto.cpp:699-703`). The semantics are
intended and covered by behavior change 4. What's missing is a matching
`LOG(WARNING)` and a note in the public docstring
(`torch/profiler/profiler.py:807-838`) saying a session can only re-enable
device tracing it started with.

[minor] torch/csrc/profiler/kineto_shim.h:129
Non-blocking: C++-facing change missing from the description's Behavior changes
list. The PR is labeled `topic: bc breaking`, so the release notes are where
out-of-tree owners will look. The exported `TORCH_API prepareTrace`
(`kineto_shim.h:129-134`) drops its leading `bool cpuOnly` parameter, with no
overload forwarding the old signature. This header is installed for extensions
(`caffe2/CMakeLists.txt:1503-1508` excludes only `csrc/profiler/kineto`), so
out-of-tree callers will stop compiling. The migration path appears only in the
header comment.

[minor] torch/csrc/profiler/kineto/libkineto/include/IActivityProfiler.h:158
Non-blocking: C++-facing change missing from the description's Behavior changes
list (PR is labeled `topic: bc breaking`). Device child profilers must now
return `nullptr` when `config.deviceTracingEnabled()` is false
(`IActivityProfiler.h:158-162`).
`GenericActivityProfiler::configureChildProfilers`
(`GenericActivityProfiler.cpp:447-471`) keeps any non-null session, so behavior
change 1 only holds for PrivateUse1, MTIA and HPU backends that adopt the new
rule.

[minor] test/profiler/test_profiler.py:486
Non-blocking: the no-op toggle test can't detect a lost CUDA trace. The only
assertion in `test_toggle_cpu_without_cpu_is_noop` is
`assertFalse(any(e.name.startswith("aten::") ...))`. That also passes when
`p.function_events` is empty, so the test catches the segfault but not a toggle
that turns CUDA tracing off. Adding `self.assertTrue(any(e.device_type ==
DeviceType.CUDA for e in p.function_events))` would make the "no-op" claim
checkable.

(1 more not shown, see the review run)

Reviewed commit: c31f339

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit c31f339 with merge base 4b71f17 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • User-facing behavior changes
    • CPU-only sessions now send DEVICE_TRACING_ENABLED=false from prepareTrace in kineto_shim.cpp, so filters like CUDA_RUNTIME under CPU now return nothing
    • toggleTorchOpCollectionDynamic and GenericActivityProfiler::toggleCollectionDynamic change toggle semantics, which the PR body calls a BC break
    • _init_for_cuda_graphs in torch/profiler/_utils.py now runs a CPU+CUDA session and returns early on ROCm
  • Signature and contract changes
    • TORCH_API prepareTrace in kineto_shim.h drops its cpuOnly parameter
    • IActivityProfiler::configure gains a rule that device profilers must return nullptr when deviceTracingEnabled() is false, which affects out-of-tree backends
  • Breadth
    • Touches libkineto core, CUPTI PM sampling, XPU PTI init, HPU/MTIA hook detection, _supported_activities, run_test.py, and deletes common_profiler.py
    • Removes the ptiViewGPULocalAvailable check from XPU factory registration in init.cpp and turns a raised error into a logged nullptr session

reason: not_trivial
Reviewed commit: 371ce20 (NOT the current head c31f339)

Inference job

🐛 Report a wrong verdict

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

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

…ession-gpu

# Conflicts:
#	torch/csrc/profiler/kineto/libkineto/include/Config.h
#	torch/csrc/profiler/kineto/libkineto/src/Config.cpp
…s tests

torch.profiler re-exports DeviceType publicly, and the rest of
test_profiler.py already imports it from there. The two subprocess scripts
added on this branch reached into torch.autograd for the same enum.

Test Plan:
```
python test/profiler/test_profiler.py -v -k test_device_tracing_decided_per_session -k test_cudagraph_profiling_workaround
```

This change was authored with the assistance of an AI assistant (Claude).
…cess-run file

test_device_tracing_decided_per_session needs a process where Kineto is not
yet registered. It got one by embedding a Python program in a string and
running it with subprocess, then passing results back as JSON.

Instead, the test now lives in test/profiler/test_kineto_registration.py as
ordinary test code, and run_test.py runs that file with --subprocess, which
gives each test a fresh interpreter. test_cuda_primary_ctx.py and
test_gpu_trace.py use the same mechanism for process-global state that cannot
be reset.

The move also fixes the runtime-event check on ROCm, where runtime API names
start with "hip" rather than "cuda". The new class keeps the Windows skip the
test inherited from TestProfilerCUDA.

Test Plan:
```
python test/profiler/test_kineto_registration.py -v
python test/profiler/test_kineto_registration.py --subprocess -v
```

This change was authored with the assistance of an AI assistant (Claude).
Comment thread torch/csrc/profiler/kineto_shim.cpp Outdated
// process has a device. A trace that requested no device activity must leave
// the device tracer alone, since another tool may own it.
extraConfig += has_device_activity ? "GPU_TRACING_ENABLED=true\n"
: "GPU_TRACING_ENABLED=false\n";

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like how we're passing request to Kineto here, and I don't like how extraConfig is just growing. But rather than improving that, I'm hoping this will improve when we refactor Kineto. That is, we should be able to avoid passing a string config entirely.

const bool has_device_activity =
std::any_of(activities.begin(), activities.end(), [](auto activity) {
return activity != torch::autograd::profiler::ActivityType::CPU;
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this is where we determine per-session if we have any GPU activity or not. This is inside prepareTrace().

…aths

libkineto is registered once per process, and its cpuOnly flag says whether
the process has a device Kineto could trace. Two places register it: the first
profiling session (prepareProfiler) and, when KINETO_USE_DAEMON is set,
global_kineto_init at import. Each spelled out its own device check, and they
drifted: pytorch#124818 added registered PrivateUse1 backends to the session path but
not to the daemon path.

Both now call torch::profiler::impl::kineto::isDevicePresent(). The daemon
path gains the PrivateUse1 term. In practice that changes little today:
global_kineto_init runs while torch._C initializes, before a PrivateUse1
backend normally registers its name.

Test Plan:
Not built or tested locally yet; relying on CI.

This change was authored with the assistance of an AI assistant (Claude).
Test Plan:
Comment-only change.

This change was authored with the assistance of an AI assistant (Claude).
if (c10::utils::get_env("KINETO_USE_DAEMON").has_value()) {
libkineto_init(
/*cpuOnly=*/!(at::hasCUDA() || at::hasXPU() || at::hasMTIA()),
/*cpuOnly=*/!profiler::impl::kineto::isDevicePresent(),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drive-by: it is a bug that PrivateUse1 was not included here, and we should share logic for how we determine if a device is present.

@scotts scotts added release notes: profiler release notes category and removed release notes: linalg_frontend release notes category labels Nov 2, 2026
@scotts
scotts marked this pull request as ready for review November 2, 2026 16:02
@scotts
scotts requested review from a team, lezcano, nikitaved and ryanzhang22 as code owners November 2, 2026 16:02
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 2, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 2, 2026
github-actions[bot]

This comment was marked as outdated.

…races

toggleCollectionDynamic called the GPU hooks no matter what the trace allowed.
Toggling CUDA off and back on in a CPU-only session therefore subscribed to
CUPTI and enabled the trace's activity kinds. The session's stop then skipped
disableGpuTracing, because the trace does not allow GPU tracing, so CUPTI
stayed armed after the session ended. That breaks the guarantee that CPU-only
sessions leave CUPTI to other tools such as Cuspy.

toggleCollectionDynamic now guards disableGpuTracing, synchronizeGpuDevice and
enableGpuTracing with shouldTraceGpu(). Child sessions toggle as before.

Test Plan:
```
build/bin/kineto/SyncActivityProfilerHandlerTest --gtest_shuffle --gtest_repeat=3
python test/profiler/test_profiler.py -k test_dynamic_toggle
```
Also checked end to end with KINETO_LOG_LEVEL=0: a CPU-only session that
toggles CUDA off and on no longer arms CUPTI, and neither does the next
CPU-only session.

This change was authored with the assistance of an AI assistant (Claude).
…s GPU tracing

libkineto is now registered with GPU support whenever a device is present, so
on XPU builds the first session registers the XPU child profiler even when it
only profiles the CPU. The child profiler's factory called
ptiViewGPULocalAvailable(), which initializes PTI. On main, a process that only
profiles the CPU never initializes PTI, and code that forks afterward relies
on that.

The availability check moves from the factory into
XPUActivityProfiler::configure, after the gpuTracingEnabled() check.
XpuptiScopeProfilerConfig::registerFactory() stays in the factory: it does not
touch PTI, and the first XPU trace needs its config parser.

Test Plan:
Not compiled locally (no XPU toolchain); relying on XPU CI. The XPU unit tests
configure XPUActivityProfiler with a default Config, which allows GPU tracing,
so they exercise the moved check.

This change was authored with the assistance of an AI assistant (Claude).
…comment

isDevicePresent() calls at::hasCUDA(), which ends in cudaGetDeviceCount and can
initialize the CUDA driver. Say so where it is declared.

test_forked_process's XPU skip comment pointed at setUpModule, which no longer
exists, and then at the first profiling session, which no longer initializes
PTI. The skip still applies: earlier tests in the file run XPU sessions
through their default activities. The comment now names that trigger.

Test Plan:
Comment-only change.

This change was authored with the assistance of an AI assistant (Claude).
github-actions[bot]

This comment was marked as outdated.

configure(
const std::set<ActivityType>& activity_types,
const libkineto::Config& config) {
if (!config.gpuTracingEnabled()) {

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.

I think we'll need this chunk of code in the PM sampler as well

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

if (!cpuOnly_) {
if (shouldTraceGpu()) {

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.

I was looking into this with Codex. There's a niche edge case where, if a trace previously overflowed and stopCollection was set to True, because that's only flipped back in enableCuptiActivities, a subsequent CPU-only OD trace request would incorrectly return early.

Specifically the normal flow starting from below goes, enableGpuTracing -> enabledCuptiActivities -> stopCollection = False.

But in async we return early when stopCollection=False

if (profiler_.isGpuCollectionStopped()) {
    profiler_.cancelTrace(now);
    currentRunloopState_ = RunloopState::WaitForRequest;
    break;
  }

I think we could just check profiler_.shouldTraceGpu() whenever we check profiler_.isGpuCollectionStopped() in the async handler. And obviously auto-trace CPU-only works fine since it doesn't need to go thru Kineto's lifecycle. All the more reason to move OD to Python and unify the lifecycles :D

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That should be fixed. Claude's claims why:

  • GenericActivityProfiler::isStopped() (GenericActivityProfiler.h:126) reports the GPU stop flag only while a trace that armed GPU tracing is running. It returns gpuTracingArmed_ && isGpuCollectionStopped().
    • gpuTracingArmed_ is set in configure() from shouldTraceGpu() (line 530).
    • It's cleared when the trace stops (line 658).
  • The two async checks the comment points at now call isStopped() instead of isGpuCollectionStopped():
    • the Warmup cancel at AsyncActivityProfilerHandler.cpp:342;
    • the CollectTrace end at line 388.
  • The collect path in GenericActivityProfiler.cpp:813 uses isStopped() as well.

Why an armed flag instead of checking shouldTraceGpu(), as suggested:

  • shouldTraceGpu() reads the trace's config, which outlives the trace. A check against it would still be true after a GPU trace stops.
  • The armed flag captures the decision when the trace is configured and drops it at stop.
  • It's atomic because other threads ask whether the trace stopped.

A trace that opts out of GPU tracing could still see GPU state left over
from an earlier trace, or reach a device tracer through a path that ignored
the key:

- The CUPTI stop flag is reset only when GPU tracing is armed. After a GPU
  trace ran out of buffers, every later CPU-only trace reported itself
  stopped. For Cuspy, that sends the schedule into DEVICE_STOPPED on each
  cycle. isStopped(), the async handler's Warmup and CollectTrace checks, and
  the gpu_stopped_early metadata now require that the current trace armed GPU
  tracing. configure() records that in an atomic, because isStopped() is
  called from other threads and cannot read config_.
- toggleState_ was set back to true only for traces that arm GPU tracing.
  After a GPU trace stopped, a CPU-only trace's first toggle off returned
  early and never reached its child sessions. configure() now resets it for
  every trace.
- The CUPTI PM sampling child profiler ignored the key and could start the
  CUPTI profiling API in a CPU-only trace. It now returns no session, like
  the XPU child profiler. Config.h documents this contract for child
  profilers.
- The XPU child profiler threw when PTI's local view was unavailable. On-demand
  traces configure on the profiler thread, where the exception ends the
  process. It now logs and returns no session.

The init.cpp comment about PTI also overclaimed: on-demand configs do not set
the key, so they allow GPU tracing even when the process only profiles the CPU.

Test Plan:
New SyncActivityProfilerHandlerTest cases cover the stop flag and toggle
state. GpuHookCounter now also counts setMaxGpuBufferSize, clearGpuActivities
and onResetTraceData, so the existing tests check that opt-out traces never
reach them. A new CuptiPMSamplingIntegrationTest case covers the PM sampling
gate. That test and the XPU change build only with
KINETO_ENABLE_CUPTI_PM_SAMPLING or the XPU backend, so neither was compiled
locally.
```
pip install -e . -v --no-build-isolation
for t in build/bin/kineto/*; do $t --gtest_shuffle --gtest_repeat=3; done
build/bin/kineto/ConfigLoaderPollThreadExceptionTest
```
All 19 binaries pass. ConfigLoaderPollThreadExceptionTest runs once because
its ConfigLoader singleton state times out on repeats.

This change was authored with the assistance of an AI assistant (Claude).
@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 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

…ession-gpu

# Conflicts:
#	test/profiler/test_cuspy.py
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 11, 2026
github-actions[bot]

This comment was marked as outdated.

@scotts

scotts commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 jobs have failed, first few of them are: xpu / linux-noble-xpu-n-py3.11-client / test (smoke_xpu, 1, 1, linux.client.xpu), xpu / linux-noble-xpu-n-py3.11 / test (default, 6, 12, linux.idc.xpu)

Details for Dev Infra team

Raised by workflow job

@github-actions github-actions Bot 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.

Automated review of c31f339: nothing blocking; ready for human review.

The PR registers Kineto with device support once per process whenever a device is present, and a new per-session DEVICE_TRACING_ENABLED config key decides whether each session arms CUPTI, rocprofiler-sdk, PTI, the PM sampler and the child profilers. Recommendation: Approve. Nothing blocks, ryanzhang22's maintainer comments are resolved, and every point raised is non-blocking.

⚪ 6 non-blocking findings

? "DEVICE_TRACING_ENABLED=true\n"

Non-blocking: CPU-only sessions request collectives that nothing collects on XPU. kineto_shim.cpp:462-464 still adds COLLECTIVE_COMM to CPU-only sessions when collectivesProfilerExists() is true, and lines 487-489 then send DEVICE_TRACING_ENABLED=false for those same sessions. On XPU, PTI collects COLLECTIVE_COMM (XpuptiActivityApi.cpp:233-234 maps it to PTI_VIEW_COMMUNICATION), and XPUActivityProfiler::configure now returns nullptr for those sessions. Before this PR, once Kineto had been registered with XPU support, a CPU-only session did collect these events. Behavior change 2 in the description mentions only runtime and driver events. Pick one rule and state it in the IActivityProfiler.h:158-162 contract comment: either collectives count as device tracing and CPU-only sessions stop requesting COLLECTIVE_COMM, or collectives are exempt from the contract.


const bool traceGpu = gpuTracingArmed_.load();

Non-blocking: device toggles fail silently and the docstring doesn't say so. toggle_collection_dynamic(True, \[CUDA/XPU\]) skips enableGpuTracing() without logging anything when gpuTracingArmed_ is false, i.e. in a CPU-only session or after the session has stopped (GenericActivityProfiler.cpp:610-631). The CPU equivalent does log a warning (profiler_kineto.cpp:699-703). The semantics are intended and covered by behavior change 4. What's missing is a matching LOG(WARNING) and a note in the public docstring (torch/profiler/profiler.py:807-838) saying a session can only re-enable device tracing it started with.


TORCH_API void prepareTrace(

Non-blocking: C++-facing change missing from the description's Behavior changes list. The PR is labeled topic: bc breaking, so the release notes are where out-of-tree owners will look. The exported TORCH_API prepareTrace (kineto_shim.h:129-134) drops its leading bool cpuOnly parameter, with no overload forwarding the old signature. This header is installed for extensions (caffe2/CMakeLists.txt:1503-1508 excludes only csrc/profiler/kineto), so out-of-tree callers will stop compiling. The migration path appears only in the header comment.


Non-blocking: C++-facing change missing from the description's Behavior changes list (PR is labeled topic: bc breaking). Device child profilers must now return nullptr when config.deviceTracingEnabled() is false (IActivityProfiler.h:158-162). GenericActivityProfiler::configureChildProfilers (GenericActivityProfiler.cpp:447-471) keeps any non-null session, so behavior change 1 only holds for PrivateUse1, MTIA and HPU backends that adopt the new rule.


self.assertFalse(any(e.name.startswith("aten::") for e in p.function_events))

Non-blocking: the no-op toggle test can't detect a lost CUDA trace. The only assertion in test_toggle_cpu_without_cpu_is_noop is assertFalse(any(e.name.startswith("aten::") ...)). That also passes when p.function_events is empty, so the test catches the segfault but not a toggle that turns CUDA tracing off. Adding self.assertTrue(any(e.device_type == DeviceType.CUDA for e in p.function_events)) would make the "no-op" claim checkable.


device_activity = getattr(ProfilerActivity, device_type.upper(), None)

Non-blocking: the PrivateUse1 entries in the registration test can never run. Lines 35-36 list privateuse1_runtime/privateuse1_driver. Line 51 looks up the activity with getattr(ProfilerActivity, device_type.upper(), None). For a PrivateUse1 backend, device_type is the backend name (e.g. "openreg", via PrivateUse1TestBase), and the enum member is ProfilerActivity.PrivateUse1. The lookup returns None, so the test always skips at lines 52-53. Either map PrivateUse1 backends to ProfilerActivity.PrivateUse1 or remove those entries.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@scotts

scotts commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 12, 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

zjliu-amd added a commit to zjliu-amd/pytorch that referenced this pull request Nov 18, 2026
…ineto

From the single-GPU failure-fix work package "prof".

Windows ROCm builds Kineto with the CPU backend (rocprofiler-sdk does not
exist on Windows), so kineto_available() is True while
supported_activities() is {CPU}. 152 tests that read GPU kernel, memcpy or
runtime events from torch.profiler failed there; 109 of them with "Legacy
CUDA profiling requires use_cpu=True" (torch/autograd/profiler.py:320).
They were gated on kineto_available(), which assumes that a Kineto build
traces the GPU. The baseline build (USE_KINETO=OFF) skipped them.

- torch/testing/_internal/common_profiler.py: device_tracing_supported()
  checks that the device's ProfilerActivity is in supported_activities()
  (the check test_matmul_cuda, test_linalg and test_foreach already do
  inline), plus a reason string.
- The GPU-trace tests use it: test_torch (12 tiled/strided copy dispatch
  tests), profiler/test_profiler (skipCUDAIf on 17 tests so CPU/XPU copies
  still run; class skips for TestProfilerEventsParityCudaOnly and
  TestMetadataJsonFormatCUDA, where every test reads kernel events),
  test_fx (2), python_native/test_native_aot_bmm, and inductor
  test_torchinductor (copy_non_blocking_is_pinned, also used by the
  derived dynamic-shapes/codegen/subprocess files), test_combo_kernels,
  test_select_algorithm, test_provenance_tracing, test_profiler_trace,
  test_profiler, test_inductor_utils and test_benchmarking.

Each gate replaces kineto_available() with a strictly narrower check or is
added where the test reads GPU events; no assertion changed. On CUDA builds
with CUPTI and Linux ROCm builds with roctracer the check is True, so they
run as before. On this build the tests skip; they need a Kineto GPU
backend, which is not part of this branch.

Rebase note: upstream deleted torch/testing/_internal/common_profiler.py
(de27676, pytorch#202625, which removed the initialize_kineto_with_* priming
helpers). This commit now re-creates the module with only
device_tracing_supported() and DEVICE_TRACING_UNSUPPORTED_MSG, and
test/profiler/test_profiler.py no longer imports
initialize_kineto_with_accelerator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zjliu-amd added a commit to zjliu-amd/pytorch that referenced this pull request Nov 18, 2026
…_cpu's Kineto

From the single-GPU failure-fix work package "prof".

cpp/test_xpu_activity_filter, cpp/test_mtia_activity_filter and
cpp/test_profiler_collection register a mock child profiler with
libkineto::api().registerProfilerFactory(). The test binaries link the
static kineto library themselves (test/cpp/profiler/CMakeLists.txt). On
Windows that gives the executable its own libkineto::api() singleton,
separate from the one inside torch_cpu.dll, so the factory never reached the
profiler: the parity logs show an empty set of configured activities and
no duplicate-flow warning. cpp/test_privateuse1_profiler, which registers
through the exported PrivateUse1 registry, passes.

- kineto_shim.h/.cpp: new TORCH_API registerChildProfilerFactory() that
  registers with torch_cpu's libkineto instance.
- The three tests use it.

On Linux the two singletons are the same symbol after dynamic linking, so
behavior is unchanged.

Rebase note: upstream (de27676, pytorch#202625) added a
libkineto_init(/*cpuOnly=*/true, ...) call after the factory registration in
test_xpu_activity_filter and test_mtia_activity_filter. It is kept as is.
On Windows that call initializes this binary's own static libkineto copy, not
torch_cpu's, so it needs checking when the tests are rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 ciflow/xpu Run XPU CI tasks GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: profiler release notes category topic: bc breaking topic category

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants