Repository: pytorch
Issue: RuntimeError: out_ptr == out_accessor[thread_count_nonzero[tid + 1]].data() INTERNAL ASSERT FAILED
Labels: module: sparse,module: multiprocessing,triaged,module: assert failure

### 🐛 Describe the bug

Hi,

When converting a tensor to sparse, I get the following error:
```
RuntimeError: out_ptr == out_accessor[thread_count_nonzero[tid + 1]].data() INTERNAL ASSERT FAILED at "/home/coulombc/wheels_builder/tmp.29658/python-3.10/torch/aten/src/ATen/native/TensorAdvancedIndexing.cpp":2363, please report a bug to PyTorch.
```

The error occurs when running the `degrade_to_bounding_boxes` function below in parallel in a process pool. However, the event occurs randomly and not on specific inputs.

Please note that no Tensor is transferred between those processes and the issue was reproduced using torch's multiprocessing context. The issue arises when using big volumes (around 512 x 512 x 512)

> The code below is given as a reference, I don't think Numpy causes the issue but I may be wrong.

```python
def _3d_segmentation_to_bounding_boxes(segmentation_mask):
    """W x H x D -> N x W x H x D"""
    segmentation_mask = segmentation_mask.numpy()
    if not np.any(segmentation_mask):
        return torch.zeros((0, *segmentation_mask.shape), dtype=torch.bool)

    # Run scipy nd-image's connected components algorithm
    labels, num_features = ndimage.label(segmentation_mask)
    objects = ndimage.find_objects(labels)
    result = np.zeros((num_features, *segmentation_mask.shape), dtype=np.bool_)

    assert len(objects) == num_features  # noqa

    for component, slices in enumerate(objects):
        # Selecting component's slice and computed slices
        result[(component,) + slices] = True

    del labels
    del objects
    return torch.as_tensor(result)


def degrade_to_bounding_boxes(volume: torch.Tensor):
    hot = F.one_hot(volume.long()).permute(-1, 0, 1, 2).bool()
    classes_present = torch.flatten(hot, start_dim=-3).any(dim=-1)
    hot_few = hot[classes_present]
    del classes_present
    del hot

    classes = [
        _3d_segmentation_to_bounding_boxes(class_).to_sparse(2)
    #                          ERROR OCCURS HERE --^^^^^^^^^^^^
        for class_ in torch.unbind(hot_few, dim=0)
    ]

    ...  # Rest of function
```

Am I missing something?
Many thanks

### Versions

<details>
<summary>:boom: Issue reproduced with Python 3.10 / Pytorch 2.2.0</summary>

```sh
$ python -m torch.utils.collect_env
Collecting environment information...
PyTorch version: 2.2.0
Is debug build: False
CUDA used to build PyTorch: 12.2
ROCM used to build PyTorch: N/A

OS: Gentoo Linux (x86_64)
GCC version: (Gentoo 12.3.1_p20230526 p2) 12.3.1 20230526
Clang version: Could not collect
CMake version: version 3.27.7
Libc version: glibc-2.37

Python version: 3.10.13 (main, Sep 18 2023, 17:18:13) [GCC 12.3.1 20230526] (64-bit runtime)
Python platform: Linux-4.18.0-513.18.1.el8_9.x86_64-x86_64-AMD_EPYC_7532_32-Core_Processor-with-glibc2.37
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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
Address sizes:                      43 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             64
On-line CPU(s) list:                0-63
Vendor ID:                          AuthenticAMD
Model name:                         AMD EPYC 7532 32-Core Processor
CPU family:                         23
Model:                              49
Thread(s) per core:                 1
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           0
BogoMIPS:                           4791.12
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 pni pclmulqdq monitor ssse3 fma cx16 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 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 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 wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sme sev sev_es
Virtualization:                     AMD-V
L1d cache:                          2 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           32 MiB (64 instances)
L3 cache:                           512 MiB (32 instances)
NUMA node(s):                       8
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:             Mitigation; untrained return thunk; SMT disabled
Vulnerability Spec rstack overflow: Mitigation; SMT disabled
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines, IBPB conditional, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.25.2+computecanada
[pip3] torch==2.2.0+computecanada
[pip3] torchvision==0.17.0+computecanada
[conda] Could not collect
```

</details>

<details>
<summary>:white_check_mark: Issue not occurring in Python 3.8 / Pytorch 1.13 </summary>

```sh
$ python -m torch.utils.collect_env
Collecting environment information...
PyTorch version: 1.13.0
Is debug build: False
CUDA used to build PyTorch: 11.4
ROCM used to build PyTorch: N/A

OS: Gentoo Base System release 2.6 (x86_64)
GCC version: (GCC) 9.3.0
Clang version: Could not collect
CMake version: version 3.27.7
Libc version: glibc-2.30

Python version: 3.8.10 (default, Jun 16 2021, 14:20:20)  [GCC 9.3.0] (64-bit runtime)
Python platform: Linux-4.18.0-513.11.1.el8_9.0.1.x86_64-x86_64-with-glibc2.2.5
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

Versions of relevant libraries:
[pip3] numpy==1.24.2+computecanada
[pip3] torch==1.13.0+computecanada
[pip3] torchvision==0.14.0+computecanada
[conda] Could not collect
```

</details>

cc @alexsamardzic @nikitaved @pearu @cpuhrsch @amjames @bhosmer @jcaip @VitalyFedyunin