Repository: pytorch
Issue: [profiler] CUDA runtime op has wrong device time because of lazy init
Labels: module: cuda,triaged

### 🐛 Describe the bug

Hi,

We find there are wrong device time assigned to the cuda runtime op if cuda lazy init is in the profiling context scope.
Here is the reproducer:
```
import torch
from torch.profiler import profile, record_function, ProfilerActivity

input1 = torch.randn(3, 3, device='cpu')
input2 = torch.randn(3, 3, device='cpu')

with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],) as prof:
    input1 = input1.to('cuda')
    input2 = input2.to('cuda')
    output1 = input1 + 1.0
    output2 = input2 + 2.0
    output = output1 + output2
print(prof.key_averages().table(sort_by="cuda_time_total"))
```
Here is the get profiling result:
```
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                                   Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg     Self CUDA   Self CUDA %    CUDA total  CUDA time avg    # of Calls
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                              aten::add         0.04%      92.270us         3.90%       8.566ms       2.855ms      10.304us        70.31%      10.304us       3.435us             3
void at::native::vectorized_elementwise_kernel<4, at...         0.00%       0.000us         0.00%       0.000us       0.000us       7.552us        51.53%       7.552us       3.776us             2
                             cudaGetDeviceProperties_v2         0.94%       2.053ms         0.94%       2.053ms       2.053ms       4.480us        30.57%       4.480us       4.480us             1
                                               aten::to         0.01%      31.110us        94.65%     207.670ms     103.835ms       0.000us         0.00%       4.352us       2.176us             2
                                         aten::_to_copy         0.04%      82.250us        94.63%     207.639ms     103.819ms       0.000us         0.00%       4.352us       2.176us             2
                                            aten::copy_         0.02%      33.050us         0.03%      65.070us      32.535us       4.352us        29.69%       4.352us       2.176us             2
                       Memcpy HtoD (Pageable -> Device)         0.00%       0.000us         0.00%       0.000us       0.000us       4.352us        29.69%       4.352us       2.176us             2
void at::native::vectorized_elementwise_kernel<4, at...         0.00%       0.000us         0.00%       0.000us       0.000us       2.752us        18.78%       2.752us       2.752us             1
                                     cudaGetDeviceCount         0.51%       1.117ms         0.51%       1.117ms     558.541us       0.000us         0.00%       0.000us       0.000us             2
                                    aten::empty_strided         0.03%      76.450us        94.57%     207.492ms     103.746ms       0.000us         0.00%       0.000us       0.000us             2
                       cudaDeviceGetStreamPriorityRange        94.49%     207.316ms        94.49%     207.316ms     207.316ms       0.000us         0.00%       0.000us       0.000us             1
                                  cudaStreamIsCapturing         0.00%       6.540us         0.00%       6.540us       6.540us       0.000us         0.00%       0.000us       0.000us             1
                                             cudaMalloc         0.04%      92.470us         0.04%      92.470us      92.470us       0.000us         0.00%       0.000us       0.000us             1
                                        cudaMemcpyAsync         0.01%      15.420us         0.01%      15.420us       7.710us       0.000us         0.00%       0.000us       0.000us             2
                                  cudaStreamSynchronize         0.01%      16.600us         0.01%      16.600us       8.300us       0.000us         0.00%       0.000us       0.000us             2
                                       cudaLaunchKernel         3.86%       8.474ms         3.86%       8.474ms       2.825ms       0.000us         0.00%       0.000us       0.000us             3
                                  cudaDeviceSynchronize         0.00%       5.710us         0.00%       5.710us       5.710us       0.000us         0.00%       0.000us       0.000us             1
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 219.412ms
Self CUDA time total: 14.656us
```
The cudaGetDeviceProperties_v2 should not have the cuda time because it is only a runtime op instead of kernel but it has.
It is because the runtime ops in lazy init are traced by the CUPTI and have no linked activity(the first external id has not been pushed), then those runtime ops are wrongly regarded as the frontend events in profiler post processing, like aten ops. Here is the related code:
https://github.com/intel-innersource/frameworks.ai.pytorch.private-gpu/blob/pytorch-2.3.1/torch/autograd/profiler.py#L510-L511


Thank you.

### Versions

Collecting environment information...
PyTorch version: 2.5.0a0+gitc549629
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 10.5.0-1ubuntu1~20.04) 10.5.0
Clang version: Could not collect
CMake version: version 3.27.2
Libc version: glibc-2.31

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-97-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.4.131
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100-PCIE-40GB
Nvidia driver version: 550.54.15
cuDNN version: Probably one of the following:
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.6.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Byte Order:                         Little Endian
Address sizes:                      48 bits physical, 48 bits virtual
CPU(s):                             64
On-line CPU(s) list:                0-63
Thread(s) per core:                 1
Core(s) per socket:                 64
Socket(s):                          1
NUMA node(s):                       8
Vendor ID:                          AuthenticAMD
CPU family:                         25
Model:                              1
Model name:                         AMD EPYC 7713 64-Core Processor
Stepping:                           1
Frequency boost:                    enabled
CPU MHz:                            1500.000
CPU max MHz:                        3720.7029
CPU min MHz:                        1500.0000
BogoMIPS:                           4000.07
Virtualization:                     AMD-V
L1d cache:                          2 MiB
L1i cache:                          2 MiB
L2 cache:                           32 MiB
L3 cache:                           256 MiB
NUMA node0 CPU(s):                  0-7
NUMA node1 CPU(s):                  8-15
NUMA node2 CPU(s):                  16-23
NUMA node3 CPU(s):                  24-31
NUMA node4 CPU(s):                  32-39
NUMA node5 CPU(s):                  40-47
NUMA node6 CPU(s):                  48-55
NUMA node7 CPU(s):                  56-63
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Mitigation; safe RET
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] CoCa-pytorch==0.1.0
[pip3] dalle2-pytorch==1.14.2
[pip3] ema-pytorch==0.3.3
[pip3] flake8==3.8.2
[pip3] flake8-bugbear==20.1.4
[pip3] flake8-coding==1.3.3
[pip3] flake8-comprehensions==3.3.0
[pip3] flake8-executable==2.0.4
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==20.5.0
[pip3] flake8-simplify==0.19.3
[pip3] functorch==1.14.0a0+b71aa0b
[pip3] mypy==1.4.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.23.5
[pip3] onnx==1.15.0
[pip3] open-clip-torch==2.24.0
[pip3] optree==0.11.0
[pip3] pytorch-triton==3.0.0+45fff310c8
[pip3] pytorch-warmup==0.1.1
[pip3] rotary-embedding-torch==0.3.3
[pip3] torch==2.5.0a0+gitc549629
[pip3] torch-fidelity==0.3.0
[pip3] torch_geometric==2.4.0
[pip3] torchaudio==2.2.0
[pip3] torchmetrics==1.3.0.post0
[pip3] torchmultimodal==0.1.0b0
[pip3] torchvision==0.18.0
[pip3] vector_quantize_pytorch==1.12.17
[conda] blas                      1.0                         mkl    https://repo.anaconda.com/pkgs/main
[conda] clip-anytorch             2.6.0                    pypi_0    pypi
[conda] coca-pytorch              0.1.0                    pypi_0    pypi
[conda] dalle2-pytorch            1.14.2                   pypi_0    pypi
[conda] ema-pytorch               0.3.3                    pypi_0    pypi
[conda] functorch                 1.14.0a0+b71aa0b          pypi_0    pypi
[conda] mkl                       2023.1.0         h213fc3f_46343    https://repo.anaconda.com/pkgs/main
[conda] mkl-service               2.4.0            py39h5eee18b_1    https://repo.anaconda.com/pkgs/main
[conda] mkl_fft                   1.3.8            py39h5eee18b_0    https://repo.anaconda.com/pkgs/main
[conda] mkl_random                1.2.4            py39hdb19cb5_0    https://repo.anaconda.com/pkgs/main
[conda] numpy                     1.23.5                   pypi_0    pypi
[conda] numpy-base                1.26.0           py39hb5e798b_0    https://repo.anaconda.com/pkgs/main
[conda] open-clip-torch           2.24.0                   pypi_0    pypi
[conda] optree                    0.11.0                   pypi_0    pypi
[conda] pytorch-triton            3.0.0+45fff310c8          pypi_0    pypi
[conda] pytorch-warmup            0.1.1                    pypi_0    pypi
[conda] rotary-embedding-torch    0.3.3                    pypi_0    pypi
[conda] torch                     2.5.0a0+gitc549629           dev_0    <develop>
[conda] torch-fidelity            0.3.0                    pypi_0    pypi
[conda] torch-geometric           2.4.0                    pypi_0    pypi
[conda] torchaudio                2.2.0                    pypi_0    pypi
[conda] torchfix                  0.4.0                    pypi_0    pypi
[conda] torchmetrics              1.3.0.post0              pypi_0    pypi
[conda] torchmultimodal           0.1.0b0                  pypi_0    pypi
[conda] torchvision               0.18.0                   pypi_0    pypi
[conda] vector-quantize-pytorch   1.12.17                  pypi_0    pypi

cc @ptrblck @msaroufim