torch.cuda.synchronize() syncs on device 0 when current device is not explicitly set, causing incomplete profiling results
- Dominant language
- Python
- Stars
- 103k
- Forks
- 29.6k
- PR merge metrics
- PR metrics pending
Description
### 🐛 Describe the bug
## Describe the bug
`torch.cuda.synchronize()` implicitly synchronizes on device 0 when the current device is not explicitly set. This can lead to incomplete kernel capture when profiling multi-GPU workloads.
In a multi-GPU environment, if operations are launched on a non-zero device (e.g., cuda:1) but `torch.cuda.set_device()` is not called, then `torch.cuda.synchronize()` does not wait for kernels on that device. As a result, some kernels are still running after the synchronize call, which causes profiling tools (e.g., torch.profiler, Nsight Systems) to miss them.
```
__global__ void add_kernel(float* x, float* y, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
out[i] = x[i] + y[i];
}
for(int t=0; t<10000; t++) {
float val = 0.0f;
for(int n=0; n<10000; n++){
val += 1.0f;
}
}
}
```
```
device="cuda:2"
x = torch.randn(100, device=device)
y = torch.randn(100, device=device)
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
with_stack=True
) as prof:
out = my_op.add(x, y)
# torch.cuda.synchronize(device)
print(prof.key_averages().table(row_limit=10))
prof.export_chrome_trace('./test2.json')
```
## PyTorch Internal Analysis
PATH: /pytorch/torch/autograd/profiler.py
```
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.enabled:
return
if self.use_device and hasattr(torch, self.use_device):
device_module = getattr(torch, self.use_device)
if hasattr(device_module, "synchronize"):
device_module.synchronize()
```
/torch/cuda/\_\_init\_\_.py
```
def synchronize(device: "Device" = None) -> None:
r"""Wait for all kernels in all streams on a CUDA device to complete.
Args:
device (torch.device or int, optional): device for which to synchronize.
It uses the current device, given by :func:`~torch.cuda.current_device`,
if :attr:`device` is ``None`` (default).
"""
_lazy_init()
with torch.cuda.device(device):
return torch._C._cuda_synchronize()
```
## Observed behavior
I conducted the following experiments to isolate the issue:
### Case 1: Long-running kernel, no explicit device sync
- `add_kernel` contains an additional nested loop (to make it long-running)
- No `torch.cuda.synchronize(device)` is used
Result:
- `add_kernel` is **NOT captured** by the profiler
### Case 2: Short kernel, no explicit device sync
- `add_kernel` without the extra loop (short execution time)
- No `torch.cuda.synchronize(device)` is used
Result:
- `add_kernel` **IS captured** by the profiler
---
### Case 3: Long-running kernel, explicit device sync
- `add_kernel` contains the nested loop (same as Case 1)
- Explicit `torch.cuda.synchronize(device)` is used
Result:
- `add_kernel` **IS captured** by the profiler
---
## Analysis
These results suggest:
- When the kernel is **short**, it may finish execution before `torch.cuda.synchronize()` (on device 0) becomes relevant, so it still appears in profiling.
- When the kernel is **long-running**, and runs on a device different from the current device:
- `torch.cuda.synchronize()` does **NOT wait for it**
- The program proceeds, and the profiler stops before the kernel completes
- Therefore, the kernel is missing from profiling results
This strongly indicates that:
> `torch.cuda.synchronize()` only synchronizes the current device (default: device 0), rather than the device where kernels are actually launched.
## Key Observation
The visibility of kernels in the profiler depends on:
- kernel duration
- whether the correct device is synchronized
This can lead to **non-deterministic profiling results**, which is particularly problematic.
### Versions
root@:~# curl -sL https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py | python
Collecting environment information...
PyTorch version: 2.12.0a0+git51a4e6d
Is debug build: True
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A
OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 4.3.1
Libc version: glibc-2.35
Python version: 3.10.12 (main, Mar 3 2026, 11:56:32) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-105-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.6.85
CUDA_MODULE_LOADING set to:
GPU models and configuration:
GPU 0: NVIDIA A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe
GPU 2: NVIDIA A100 80GB PCIe
GPU 3: NVIDIA A100 80GB PCIe
GPU 4: NVIDIA A100 80GB PCIe
GPU 5: NVIDIA A100 80GB PCIe
GPU 6: NVIDIA A100 80GB PCIe
GPU 7: NVIDIA A100 80GB PCIe
Nvidia driver version: 590.48.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 46 bits physical, 57 bits virtual
Byte Order: Little Endian
CPU(s): 64
On-line CPU(s) list: 0-63
Vendor ID: GenuineIntel
Model name: Intel(R) Xeon(R) Gold 6346 CPU @ 3.10GHz
CPU family: 6
Model: 106
Thread(s) per core: 2
Core(s) per socket: 16
Socket(s): 2
Stepping: 6
CPU max MHz: 3600.0000
CPU min MHz: 800.0000
BogoMIPS: 6200.00
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization: VT-x
L1d cache: 1.5 MiB (32 instances)
L1i cache: 1 MiB (32 instances)
L2 cache: 40 MiB (32 instances)
L3 cache: 72 MiB (2 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-15,32-47
NUMA node1 CPU(s): 16-31,48-63
Vulnerability Gather data sampling: Vulnerable: No microcode
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Versions of relevant libraries:
[pip3] numpy==2.2.6
[pip3] optree==0.19.0
[pip3] torch==2.12.0a0+git51a4e6d
[conda] Could not collect
root@aidev-208-7:~#
cc @robieta @chaekit @guotuofeng @guyang3532 @dzhulgakov @davidberard98 @briancoutinho @sraikund16 @sanrise @mwootton @divyanshk @jiannanWang @scotts @ryanzhang22
Contributor guide
Assessment
This issue has not been assessed yet.