Repository: pytorch
Issue: CUDA error in torch.cdist with compute_mode=donot_use_mm_for_euclid_dist
Labels: module: loss,module: cuda,triaged,actionable

### 🐛 Describe the bug

I observe the following crash in `torch.cdist` under certain conditions:
```Shell
Traceback (most recent call last):
  File "/workspaces/models/notebooks/cdist.py", line 13, in <module>
    torch.cdist(
  File "/opt/venv/lib/python3.11/site-packages/torch/functional.py", line 1339, in cdist
    return _VF.cdist(x1, x2, p, 2)  # type: ignore[attr-defined]
           ^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: CUDA error: invalid configuration argument
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
```
I can trigger the crash with:
```python
import torch

a = torch.rand(32, 8192, 3).cuda()
torch.cdist(
    x1=a,
    x2=a,
    compute_mode="donot_use_mm_for_euclid_dist",
    p=2.0,
)
```
However, the crash does not occur when I reduce the size of the second dimension from `8192` (`2^13`) to `8191`:
``` Python
import torch

a = torch.rand(32, 8191, 3).cuda()
torch.cdist(
    x1=a,
    x2=a,
    compute_mode="donot_use_mm_for_euclid_dist",
    p=2.0,
)
```
The crash also does not occur when the size of the second dimension is `8192`, but I use the default `compute_mode`:
``` Python
import torch

a = torch.rand(32, 8192, 3).cuda()
torch.cdist(
    x1=a,
    x2=a,
    p=2.0,
)
```
The [docs](https://pytorch.org/docs/stable/generated/torch.cdist.html) suggest that `cdist` will fall back to using matrix multiplication if the second dim is larger than `25`, which explains the different behaviour.

However, I'm keen to avoid using matrix multiplication, since I see a significant performance improvement, and matrix multiplication is known to suffer from [numerical instabilities](https://github.com/pytorch/pytorch/issues/42479):
```
donot_use_mm_for_euclid_dist:   0.0116 seconds
use_mm_for_euclid_dist_if_necessary:  16.9030 seconds
```

From what I can see, `cdist` is implemented [here](https://github.com/pytorch/pytorch/blob/ab13980424fea6817f18cc83dac4729743348de2/aten/src/ATen/native/Distance.cpp#L81-L148), and the kernel is implemented [here](https://github.com/pytorch/pytorch/blob/a61939467a5669288ae89da781bce9645ddce1ae/aten/src/ATen/native/cuda/DistanceKernel.cu#L362)

### Versions
``` Shell
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.11.9 (main, Apr  6 2024, 17:59:24) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.10.0-28-cloud-amd64-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla T4
Nvidia driver version: 535.86.10
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             8
On-line CPU(s) list:                0-7
Vendor ID:                          GenuineIntel
BIOS Vendor ID:                     Google
Model name:                         Intel(R) Xeon(R) CPU @ 2.30GHz
CPU family:                         6
Model:                              63
Thread(s) per core:                 2
Core(s) per socket:                 4
Socket(s):                          1
Stepping:                           0
BogoMIPS:                           4599.99
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single pti ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          128 KiB (4 instances)
L1i cache:                          128 KiB (4 instances)
L2 cache:                           1 MiB (4 instances)
L3 cache:                           45 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-7
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Mitigation; PTE Inversion
Vulnerability Mds:                  Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Meltdown:             Mitigation; PTI
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:             Mitigation; IBRS
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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] pytorch-lightning==2.2.1
[pip3] torch==2.3.0
[pip3] torchmetrics==1.3.2
[pip3] triton==2.3.0
[conda] Could not collect
```

cc @ptrblck @msaroufim