pytorch - 💡(How to fix) Fix `nanosleep()` call in `socket.cpp` delay method cannot handle signal interrupts (e.g. from sampling-based profilers) [4 comments, 3 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#177730Fetched 2026-04-08 00:58:05
View on GitHub
Comments
4
Participants
3
Timeline
62
Reactions
0
Timeline (top)
subscribed ×26mentioned ×24labeled ×5commented ×4

Error Message

[W312 16:22:03.011446043 TCPStore.cpp:340] [c10d] TCP client failed to connect/validate to host localhost:12355 - retrying (try=0, timeout=600000ms, delay=800ms): Interrupted system call Exception raised from delay at /pytorch/torch/csrc/distributed/c10d/socket.cpp:113 (most recent call first): frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x9d (0x7f70fd50bfdd in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0x16b8004 (0x7f713c31f004 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so) frame #2: <unknown function> + 0x6ac35f6 (0x7f714172a5f6 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so) ...

Code Example

if (::nanosleep(&req, nullptr) != 0) {
  std::error_code err = getSocketError();
  // We don't care about error conditions other than EINTR since a failure
  // here is not critical.
  if (err == std::errc::interrupted) {
    C10_THROW_ERROR(DistNetworkError, c10::utils::str_error(err.value()));
  }
}

---

[W312 16:22:03.011446043 TCPStore.cpp:340] [c10d] TCP client failed to connect/validate to host localhost:12355 - retrying (try=0, timeout=600000ms, delay=800ms): Interrupted system call
Exception raised from delay at /pytorch/torch/csrc/distributed/c10d/socket.cpp:113 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x9d (0x7f70fd50bfdd in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0x16b8004 (0x7f713c31f004 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so)
frame #2: <unknown function> + 0x6ac35f6 (0x7f714172a5f6 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so) 
...
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description:

It appears as though sending a returning signal, such as SIGPROF, at the start of a distributed PyTorch run can cause the associated thread to exit early. In practice, this issue has been seen to cause profilers which rely on signals to deadlock/hang in a distributed scenario when attempting to profile PyTorch/Python. We believe this is due to the handling of interrupts with the nanosleep() call in the delay() method in socket.cpp:

if (::nanosleep(&req, nullptr) != 0) {
  std::error_code err = getSocketError();
  // We don't care about error conditions other than EINTR since a failure
  // here is not critical.
  if (err == std::errc::interrupted) {
    C10_THROW_ERROR(DistNetworkError, c10::utils::str_error(err.value()));
  }
}

This error capturing may need expanding in order to be able to loop-retry the nanosleep() call.

To reproduce

[Link removed - external file downloads are not permitted for security reasons]

Compile the provided thread_profiler library by running make -f thread-profiler.makefile. This will create a library which intercepts the main process and any pthread_create calls to setup signal timers which send SIGPROF for the main and spawned threads. If you run a distributed PyTorch application, for example pytorch/examples/distributed/ddp-tutorial-series/multigpu.py and preload this library via LD_PRELOAD=libthreadprofiler.so, you will be able to see the following output (or similar):

[W312 16:22:03.011446043 TCPStore.cpp:340] [c10d] TCP client failed to connect/validate to host localhost:12355 - retrying (try=0, timeout=600000ms, delay=800ms): Interrupted system call
Exception raised from delay at /pytorch/torch/csrc/distributed/c10d/socket.cpp:113 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x9d (0x7f70fd50bfdd in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0x16b8004 (0x7f713c31f004 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so)
frame #2: <unknown function> + 0x6ac35f6 (0x7f714172a5f6 in <test_dir>/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so) 
...

This then causes the thread which sent the signal to hang.

Expected behaviour

The thread is able to gracefully handle signal interrupts.

Environment

Tested using PyTorch 2.10.0+cu128 (CUDA 12.8+NCCL 2.27.5).

Versions

PyTorch version: 2.10.0+cu128 Is debug build: False CUDA used to build PyTorch: 12.8 ROCM used to build PyTorch: N/A

OS: Red Hat Enterprise Linux release 8.8 (Ootpa) (x86_64) GCC version: (GCC) 11.1.0 Clang version: Could not collect CMake version: version 4.2.0 Libc version: glibc-2.28

Python version: 3.10.2 (main, Feb 3 2022, 18:02:44) [GCC 8.5.0 20210514 (Red Hat 8.5.0-4)] (64-bit runtime) Python platform: Linux-4.18.0-477.13.1.el8_8.x86_64-x86_64-with-glibc2.28 Is CUDA available: True CUDA runtime version: 12.8.93 CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: Tesla T4 GPU 1: Tesla T4

Nvidia driver version: 570.124.06 cuDNN version: Could not collect 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 Byte Order: Little Endian CPU(s): 40 On-line CPU(s) list: 0-39 Thread(s) per core: 2 Core(s) per socket: 10 Socket(s): 2 NUMA node(s): 2 Vendor ID: GenuineIntel CPU family: 6 Model: 85 Model name: Intel(R) Xeon(R) Silver 4210 CPU @ 2.20GHz Stepping: 7 CPU MHz: 999.987 BogoMIPS: 4400.00 Virtualization: VT-x L1d cache: 32K L1i cache: 32K L2 cache: 1024K L3 cache: 14080K NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38 NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39 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 monitor 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 cdp_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 mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries: [pip3] numpy==2.2.6 [pip3] nvidia-cublas-cu12==12.8.4.1 [pip3] nvidia-cuda-cupti-cu12==12.8.90 [pip3] nvidia-cuda-nvrtc-cu12==12.8.93 [pip3] nvidia-cuda-runtime-cu12==12.8.90 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cufft-cu12==11.3.3.83 [pip3] nvidia-curand-cu12==10.3.9.90 [pip3] nvidia-cusolver-cu12==11.7.3.90 [pip3] nvidia-cusparse-cu12==12.5.8.93 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.5 [pip3] nvidia-nvjitlink-cu12==12.8.93 [pip3] nvidia-nvtx-cu12==12.8.90 [pip3] torch==2.10.0+cu128 [pip3] torchaudio==2.10.0+cu128 [pip3] torchvision==0.25.0+cu128 [pip3] triton==3.6.0 [conda] Could not collect

cc @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @pragupta @msaroufim @dcci @aditvenk @xmfan

extent analysis

Fix Plan

To address the issue of the thread hanging due to signal interrupts, we need to modify the delay() method in socket.cpp to handle EINTR errors and retry the nanosleep() call.

Step-by-Step Solution:

  1. Modify the delay() method: Update the error handling in the delay() method to catch EINTR errors and retry the nanosleep() call.
  2. Implement retry logic: Add a retry mechanism to handle EINTR errors and ensure the nanosleep() call is retried until it succeeds or a maximum retry limit is reached.

Example Code:

void delay(int64_t milliseconds) {
    struct timespec req;
    req.tv_sec = milliseconds / 1000;
    req.tv_nsec = (milliseconds % 1000) * 1000000;

    int retry_count = 0;
    const int max_retries = 5;

    while (retry_count < max_retries) {
        if (::nanosleep(&req, nullptr) == 0) {
            break; // nanosleep succeeded
        }

        std::error_code err = getSocketError();
        if (err == std::errc::interrupted) {
            retry_count++;
            continue; // retry on EINTR error
        }

        // Handle other error conditions
        C10_THROW_ERROR(DistNetworkError, c10::utils::str_error(err.value()));
    }

    if (retry_count == max_retries) {
        // Handle maximum retry limit reached
        C10_THROW_ERROR(DistNetworkError, "Maximum retry limit reached");
    }
}

Verification

To verify the fix, run the distributed PyTorch application with the modified delay() method and check for any hangs or deadlocks. You can also use tools like gdb or valgrind to debug and profile the application.

Extra Tips

  • Ensure that the max_retries limit is set to a reasonable value to avoid infinite loops.
  • Consider adding logging or monitoring to track the number of retries and detect potential issues.
  • Review the error handling in other parts of the code to ensure consistency and robustness.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING