Repository: pytorch
Issue: Segmentation fault in RPC worker when DataLoader has num_workers > 0
Labels: oncall: distributed,module: dataloader,triaged

### 🐛 Describe the bug

RPC `worker_1` crashes with `Segmentation fault (core dumped)` error only when the `num_workers` is greater than 0. The code works fine for `num_workers` = 0.

# Code
Rank 0 code:

```
import os
import torch
import torch.distributed.rpc as rpc

from torchvision import datasets as torch_datasets
from torchvision import transforms


def init_process():
    """ Initialize the distributed environment. """
    os.environ['MASTER_ADDR'] = 'cn-b005'
    os.environ['MASTER_PORT'] = '29501'

    # rpc_backend_options = rpc.TensorPipeRpcBackendOptions(
    #     # init_method=f'tcp://localhost:52521',
    #     num_worker_threads=32, # <--- ONLY ADDED THIS LINE
    # )
    rpc.init_rpc("worker_0", rank=0, world_size=2)


if __name__ == "__main__":
    print("before init")
    init_process()
    print("after init")

    dataloader = torch.utils.data.DataLoader(
        torch_datasets.MNIST('/tmp/', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=32, shuffle=True,num_workers=1)

    payloads = {}
    sl_data = []
    req_nb_samples = 8

    for i, batch in zip(range(2), dataloader):
        fut1 = rpc.rpc_async("worker_1", torch.add, args=(torch.ones(2), 3))
        result = fut1.wait()
        print("result1: ", result)

    rpc.shutdown(graceful=True)

```

Rank 1 code:

```
 import os
import torch
import torch.distributed.rpc as rpc


def init_process():
    """ Initialize the distributed environment. """
    os.environ['MASTER_ADDR'] = 'cn-b005'
    os.environ['MASTER_PORT'] = '29501'
    # rpc.init_rpc("worker_1", rank=1, world_size=2)
    # rpc_backend_options = rpc.TensorPipeRpcBackendOptions(
    #     # init_method=f'tcp://localhost:52521',
    #     num_worker_threads=32, # <--- ONLY ADDED THIS LINE
    # )
    rpc.init_rpc("worker_1", rank=1, world_size=2)


import time
if __name__ == "__main__":
    print("before init")
    init_process()
    print("after init")

    print("Guess waiting...")
    rpc.shutdown(graceful=True)
```

# Outputs
When `num_workers`=1:

Rank 0 output:

> before init
> libibverbs: Warning: couldn't load driver 'libvmw_pvrdma-rdmav34.so': libvmw_pvrdma-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libmthca-rdmav34.so': libmthca-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libcxgb4-rdmav34.so': libcxgb4-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libi40iw-rdmav34.so': libi40iw-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'librxe-rdmav34.so': librxe-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libhfi1verbs-rdmav34.so': libhfi1verbs-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libocrdma-rdmav34.so': libocrdma-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libmlx4-rdmav34.so': libmlx4-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libipathverbs-rdmav34.so': libipathverbs-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libhns-rdmav34.so': libhns-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libbnxt_re-rdmav34.so': libbnxt_re-rdmav34.so: cannot open shared object file: No such file or directory
> libibverbs: Warning: couldn't load driver 'libqedr-rdmav34.so': libqedr-rdmav34.so: cannot open shared object file: No such file or directory
> after init
> [W tensorpipe_agent.cpp:939] RPC agent for worker_0 encountered error when reading incoming response from worker_1: eof (this error originated at tensorpipe/transport/ibv/connection_impl.cc:302)
> [W tensorpipe_agent.cpp:725] RPC agent for worker_0 encountered error when reading incoming request from worker_1: eof (this error originated at tensorpipe/transport/ibv/connection_impl.cc:302)
> Traceback (most recent call last):
>   File "/network/scratch/s/sarvjeet-singh.ghotra/git/tmp/iterlearn-vp/inference_servers/repro_test_rpc_submodules.py", line 40, in <module>
>     result = fut1.wait()
> RuntimeError: eof (this error originated at tensorpipe/transport/ibv/connection_impl.cc:302)
> 

Rank 1 output: 

> before init
after init
Guess waiting...
Segmentation fault (core dumped)

Expected outputs (when `num_workers`=0):

Rank 0:

> before init
libibverbs: Warning: couldn't load driver 'libvmw_pvrdma-rdmav34.so': libvmw_pvrdma-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libmthca-rdmav34.so': libmthca-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libcxgb4-rdmav34.so': libcxgb4-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libi40iw-rdmav34.so': libi40iw-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'librxe-rdmav34.so': librxe-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libhfi1verbs-rdmav34.so': libhfi1verbs-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libocrdma-rdmav34.so': libocrdma-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libmlx4-rdmav34.so': libmlx4-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libipathverbs-rdmav34.so': libipathverbs-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libhns-rdmav34.so': libhns-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libbnxt_re-rdmav34.so': libbnxt_re-rdmav34.so: cannot open shared object file: No such file or directory
libibverbs: Warning: couldn't load driver 'libqedr-rdmav34.so': libqedr-rdmav34.so: cannot open shared object file: No such file or directory
after init
result1:  tensor([4., 4.])
result1:  tensor([4., 4.])

Rank 1:

>  before init
after init
Guess waiting...


### Versions

Rank 0 machine / env:

> 
> Collecting environment information...
> PyTorch version: 2.0.1+cu117
> Is debug build: False
> CUDA used to build PyTorch: 11.7
> ROCM used to build PyTorch: N/A
> 
> OS: Ubuntu 18.04.6 LTS (x86_64)
> GCC version: (GCC) 7.4.0
> Clang version: Could not collect
> CMake version: version 3.27.7
> Libc version: glibc-2.27
> 
> Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
> Python platform: Linux-4.15.0-213-generic-x86_64-with-glibc2.27
> Is CUDA available: True
> CUDA runtime version: 11.6.124
> CUDA_MODULE_LOADING set to: LAZY
> GPU models and configuration: GPU 0: Tesla V100-SXM2-32GB
> Nvidia driver version: 535.104.12
> cuDNN version: Could not collect
> 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
> CPU(s):              40
> On-line CPU(s) list: 0-39
> Thread(s) per core:  1
> Core(s) per socket:  20
> Socket(s):           2
> NUMA node(s):        2
> Vendor ID:           GenuineIntel
> CPU family:          6
> Model:               85
> Model name:          Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz
> Stepping:            7
> CPU MHz:             3115.744
> CPU max MHz:         3900.0000
> CPU min MHz:         800.0000
> BogoMIPS:            4200.00
> Virtualization:      VT-x
> L1d cache:           32K
> L1i cache:           32K
> L2 cache:            1024K
> L3 cache:            28160K
> NUMA node0 CPU(s):   0-19
> NUMA node1 CPU(s):   20-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 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 hwp hwp_act_window hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
> 
> Versions of relevant libraries:
> [pip3] numpy==1.23.5
> [pip3] torch==2.0.1
> [pip3] torch-tensorrt==1.4.0
> [pip3] torchaudio==2.0.2
> [pip3] torchvision==0.15.2
> [pip3] triton==2.0.0
> [conda] blas                      1.0                         mkl    defaults
> [conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
> [conda] mkl                       2023.1.0         h213fc3f_46343    defaults
> [conda] mkl-fft                   1.3.8                    pypi_0    pypi
> [conda] mkl-random                1.2.4                    pypi_0    pypi
> [conda] mkl-service               2.4.0                    pypi_0    pypi
> [conda] mkl_fft                   1.3.8           py310h5eee18b_0    defaults
> [conda] mkl_random                1.2.4           py310hdb19cb5_0    defaults
> [conda] numpy                     1.23.5                   pypi_0    pypi
> [conda] numpy-base                1.25.2          py310hb5e798b_0    defaults
> [conda] pytorch                   1.13.1          py3.10_cuda11.6_cudnn8.3.2_0    pytorch
> [conda] pytorch-cuda              11.6                 h867d48c_1    pytorch
> [conda] pytorch-mutex             1.0                        cuda    pytorch
> [conda] torch                     2.0.1                    pypi_0    pypi
> [conda] torch-tensorrt            1.4.0                    pypi_0    pypi
> [conda] torchaudio                2.0.2                    pypi_0    pypi
> [conda] torchvision               0.15.2                   pypi_0    pypi
> [conda] triton                    2.0.0                    pypi_0    pypi

Rank 1 machine / env:

> 
> Collecting environment information...
> PyTorch version: 2.0.1+cu117
> Is debug build: False
> CUDA used to build PyTorch: 11.7
> ROCM used to build PyTorch: N/A
> 
> OS: Ubuntu 18.04.6 LTS (x86_64)
> GCC version: (GCC) 7.4.0
> Clang version: Could not collect
> CMake version: version 3.27.7
> Libc version: glibc-2.27
> 
> Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
> Python platform: Linux-4.15.0-213-generic-x86_64-with-glibc2.27
> Is CUDA available: True
> CUDA runtime version: 11.6.124
> CUDA_MODULE_LOADING set to: LAZY
> GPU models and configuration: GPU 0: Tesla V100-SXM2-32GB
> Nvidia driver version: 535.104.12
> cuDNN version: Could not collect
> 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
> CPU(s):              40
> On-line CPU(s) list: 0-39
> Thread(s) per core:  1
> Core(s) per socket:  20
> Socket(s):           2
> NUMA node(s):        2
> Vendor ID:           GenuineIntel
> CPU family:          6
> Model:               85
> Model name:          Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz
> Stepping:            7
> CPU MHz:             1713.582
> CPU max MHz:         3900.0000
> CPU min MHz:         800.0000
> BogoMIPS:            4200.00
> Virtualization:      VT-x
> L1d cache:           32K
> L1i cache:           32K
> L2 cache:            1024K
> L3 cache:            28160K
> NUMA node0 CPU(s):   0-19
> NUMA node1 CPU(s):   20-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 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 hwp hwp_act_window hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
> 
> Versions of relevant libraries:
> [pip3] numpy==1.23.5
> [pip3] torch==2.0.1
> [pip3] torch-tensorrt==1.4.0
> [pip3] torchaudio==2.0.2
> [pip3] torchvision==0.15.2
> [pip3] triton==2.0.0
> [conda] blas                      1.0                         mkl    defaults
> [conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
> [conda] mkl                       2023.1.0         h213fc3f_46343    defaults
> [conda] mkl-fft                   1.3.8                    pypi_0    pypi
> [conda] mkl-random                1.2.4                    pypi_0    pypi
> [conda] mkl-service               2.4.0                    pypi_0    pypi
> [conda] mkl_fft                   1.3.8           py310h5eee18b_0    defaults
> [conda] mkl_random                1.2.4           py310hdb19cb5_0    defaults
> [conda] numpy                     1.23.5                   pypi_0    pypi
> [conda] numpy-base                1.25.2          py310hb5e798b_0    defaults
> [conda] pytorch                   1.13.1          py3.10_cuda11.6_cudnn8.3.2_0    pytorch
> [conda] pytorch-cuda              11.6                 h867d48c_1    pytorch
> [conda] pytorch-mutex             1.0                        cuda    pytorch
> [conda] torch                     2.0.1                    pypi_0    pypi
> [conda] torch-tensorrt            1.4.0                    pypi_0    pypi
> [conda] torchaudio                2.0.2                    pypi_0    pypi
> [conda] torchvision               0.15.2                   pypi_0    pypi
> [conda] triton                    2.0.0                    pypi_0    pypi

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @SsnL @VitalyFedyunin @ejguan @dzhulgakov @kiukchung @lucasllc @d4l3k