Repository: pytorch
Issue: torch.stft sometimes raises RuntimeError: cuFFT error: CUFFT_INTERNAL_ERROR on low free memory
Labels: module: cuda,module: memory usage,triaged,module: fft

### 🐛 Describe the bug

When a lot of GPU memory is already allocated/reserved, `torch.stft` can sometimes raise the exception:
```
RuntimeError: cuFFT error: CUFFT_INTERNAL_ERROR
```
It's not necessarily the first call to `torch.stft`. I had training runs which run fine for many hours until I got this. Sometimes (often) it never happens, but sometimes when free memory is low, it happens more often. Often after restarting, it happens exactly in the same step, thus it's somewhat deterministic.

I think it's different from https://github.com/pytorch/pytorch/issues/88038 or #89556 where the exception is raised right at the beginning without being close to OOM.

Also reported here:
https://github.com/rwth-i6/returnn/issues/1465

I have here some demo code, which first allocates a lot of memory, close to the limit, and then tries a few `torch.stft` calls with random input sizes. There are a number of hardcoded constants in this script, and when playing around with them, and also with the random seed, sometimes I get the error very early, sometimes later, sometimes not at all.

Code:
```python
import torch
import sys


def main():
    """main"""
    print("PyTorch:", torch.__version__)
    dev = torch.device("cuda")
    print("GPU:", torch.cuda.get_device_name())

    window = torch.hann_window(512, device=dev)

    mem = []
    blob_size = 100_000_000
    while True:
        blob = torch.rand(blob_size, device=dev)
        mem.append(blob)
        free, total = torch.cuda.mem_get_info()
        alloc = torch.cuda.max_memory_allocated()
        print(
            f"Total GPU memory {human_bytes_size(total)},"
            f" alloc {human_bytes_size(alloc)},"
            f" free {human_bytes_size(free)} ({free / total * 100:.1f}%)"
        )
        blob_size = min(int(free * 0.8 / 4), blob_size)
        if free / total < 0.01:
            break

    torch.manual_seed(1337)
    step = 0
    count_oom = 0
    while True:
        try:
            n_batch = torch.randint(1, 100, ())
            # n_time = torch.randint(1_000, 500_000, ())
            max_time = min(int(blob_size / n_batch / 2), 500_000)
            # n_time = torch.randint(min(1_000, max_time // 2), min(max_time, 500_000), ())
            n_time = torch.randint(max_time // 100, max_time, ())
            x = torch.randn(n_batch, n_time, device=dev)
            print("x:", x)
            y = torch.stft(
                x,
                n_fft=512,
                hop_length=160,
                window=window,
                center=True,
                normalized=False,
                onesided=True,
                return_complex=True,
            )
            y = y.real
            print("y:", y)
            step += 1
        except torch.cuda.OutOfMemoryError:
            count_oom += 1
            continue
        except RuntimeError as exc:
            print("RuntimeError:", exc)
            print(f"(step {step}, count OOM {count_oom})")
            sys.exit(1)
        except KeyboardInterrupt:
            print("KeyboardInterrupt")
            sys.exit(1)


def human_size(n, factor=1000, frac=0.8, prec=1):
    """
    :param int|float n:
    :param int factor: for each of the units K, M, G, T
    :param float frac: when to go over to the next bigger unit
    :param int prec: how much decimals after the dot
    :return: human readable size, using K, M, G, T
    :rtype: str
    """
    postfixes = ["", "K", "M", "G", "T"]
    i = 0
    while i < len(postfixes) - 1 and n > (factor ** (i + 1)) * frac:
        i += 1
    if i == 0:
        return str(n)
    return ("%." + str(prec) + "f") % (float(n) / (factor**i)) + postfixes[i]


def human_bytes_size(n, factor=1024, frac=0.8, prec=1):
    """
    :param int|float n:
    :param int factor: see :func:`human_size`. 1024 by default for bytes
    :param float frac: see :func:`human_size`
    :param int prec: how much decimals after the dot
    :return: human readable byte size, using K, M, G, T, with "B" at the end
    :rtype: str
    """
    return human_size(n, factor=factor, frac=frac, prec=prec) + "B"


if __name__ == "__main__":
    try:
        import lovely_tensors

        lovely_tensors.monkey_patch()
    except ImportError:
        pass

    main()
```

This gives the output:
```
PyTorch: 2.1.0+cu121  
GPU: NVIDIA GeForce GTX 1080 Ti 
Total GPU memory 10.9GB, alloc 382.0MB, free 10.4GB (95.2%) 
Total GPU memory 10.9GB, alloc 764.0MB, free 10.0GB (91.7%)  
Total GPU memory 10.9GB, alloc 1.1GB, free 9.6GB (88.3%)    
Total GPU memory 10.9GB, alloc 1.5GB, free 9.3GB (84.9%)                                                                                                        
Total GPU memory 10.9GB, alloc 1.9GB, free 8.9GB (81.5%)                                                                                                        
Total GPU memory 10.9GB, alloc 2.2GB, free 8.5GB (78.1%)                        
Total GPU memory 10.9GB, alloc 2.6GB, free 8.1GB (74.7%)                                                                                                        
Total GPU memory 10.9GB, alloc 3.0GB, free 7.8GB (71.2%)                        
Total GPU memory 10.9GB, alloc 3.4GB, free 7.4GB (67.8%)                                                                                                        
Total GPU memory 10.9GB, alloc 3.7GB, free 7.0GB (64.4%)                                                                                                        
Total GPU memory 10.9GB, alloc 4.1GB, free 6.7GB (61.0%)                                                                                                        
Total GPU memory 10.9GB, alloc 4.5GB, free 6.3GB (57.6%)                                                                                                        
Total GPU memory 10.9GB, alloc 4.8GB, free 5.9GB (54.1%)                                                                                                        
Total GPU memory 10.9GB, alloc 5.2GB, free 5.5GB (50.7%)                                                                                                        
Total GPU memory 10.9GB, alloc 5.6GB, free 5.2GB (47.3%)                        
Total GPU memory 10.9GB, alloc 6.0GB, free 4.8GB (43.9%)                                                                                                        
Total GPU memory 10.9GB, alloc 6.3GB, free 4.4GB (40.5%)                                                                                                        
Total GPU memory 10.9GB, alloc 6.7GB, free 4.0GB (37.0%)                                                                                                        
Total GPU memory 10.9GB, alloc 7.1GB, free 3.7GB (33.6%)                                                                                                        
Total GPU memory 10.9GB, alloc 7.5GB, free 3.3GB (30.2%)                                                                                                        
Total GPU memory 10.9GB, alloc 7.8GB, free 2.9GB (26.8%)                                                                                                        
Total GPU memory 10.9GB, alloc 8.2GB, free 2.5GB (23.4%)                                                                                                        
Total GPU memory 10.9GB, alloc 8.6GB, free 2.2GB (19.9%)                                                                                                        
Total GPU memory 10.9GB, alloc 9.0GB, free 1.8GB (16.5%)                                                                                                        
Total GPU memory 10.9GB, alloc 9.3GB, free 1.4GB (13.1%)                                                                                                        
Total GPU memory 10.9GB, alloc 9.7GB, free 1.1GB (9.7%)                                                                                                         
Total GPU memory 10.9GB, alloc 10.1GB, free 700.1MB (6.3%)                                                                                                      
Total GPU memory 10.9GB, alloc 10.4GB, free 318.1MB (2.8%)                                                                                                      
Total GPU memory 10.9GB, alloc 10.7GB, free 62.1MB (0.6%)                                                                                                       
x: tensor[65, 5145] n=334425 (1.3Mb) x∈[-4.378, 4.788] μ=0.003 σ=1.001 cuda:0                                                                                   
y: tensor[65, 257, 33] n=551265 (2.1Mb) x∈[-60.855, 54.777] μ=0.001 σ=10.006 cuda:0
x: tensor[60, 22950] n=1377000 (5.3Mb) x∈[-4.718, 4.979] μ=-0.002 σ=1.000 cuda:0                                                                                
x: tensor[99, 24576] n=2433024 (9.3Mb) x∈[-4.990, 4.923] μ=-0.000 σ=1.000 cuda:0
x: tensor[93, 11453] n=1065129 (4.1Mb) x∈[-4.972, 5.044] μ=-0.000 σ=1.000 cuda:0                                                                                
x: tensor[64, 90092] n=5765888 (22Mb) x∈[-4.895, 5.362] μ=-8.342e-05 σ=1.000 cuda:0
x: tensor[1, 464286] 1.8Mb x∈[-4.675, 4.634] μ=-0.001 σ=0.999 cuda:0          
y: tensor[1, 257, 2902] n=745814 (2.8Mb) x∈[-54.185, 51.748] μ=-0.000 σ=9.846 cuda:0
...
x: tensor[93, 63197] n=5877321 (22Mb) x∈[-5.470, 5.326] μ=0.000 σ=1.000 cuda:0                                                                                  
x: tensor[29, 50807] n=1473403 (5.6Mb) x∈[-5.173, 5.432] μ=-0.000 σ=1.000 cuda:0                                                                                
x: tensor[2, 84832] n=169664 (0.6Mb) x∈[-4.449, 4.633] μ=1.887e-05 σ=0.999 cuda:0                                                                               
RuntimeError: cuFFT error: CUFFT_INTERNAL_ERROR                                                                                                                 
(step 39, count OOM 266)                                                                                                                                        
```


### Versions

Collecting environment information...                                           
PyTorch version: 2.1.0+cu121                                                                                                                                    
Is debug build: False                                                                                                                                           
CUDA used to build PyTorch: 12.1                                                                                                                                
ROCM used to build PyTorch: N/A                                                                                                                                 
                                                                                
OS: Ubuntu 22.04.3 LTS (x86_64)                                                                                                                                 
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0                                                                                                              
Clang version: 15.0.7                                                                                                                                           
CMake version: Could not collect                                                
Libc version: glibc-2.35                                                                                                                                        
                                                                                
Python version: 3.11.2 (main, Feb  7 2023, 13:52:42) [GCC 11.3.0] (64-bit runtime)                                                                              
Python platform: Linux-5.15.0-39-generic-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: NVIDIA GeForce GTX 1080 Ti                                               
GPU 1: NVIDIA GeForce GTX 1080 Ti                                                                                                                               
GPU 2: NVIDIA GeForce GTX 1080 Ti                                               
GPU 3: NVIDIA GeForce GTX 1080 Ti                                                                                                                               
                                                                                                                                                                
Nvidia driver version: 530.41.03                                                                                                                                
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):                          16
On-line CPU(s) list:             0-15
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz
CPU family:                      6
Model:                           79
Thread(s) per core:              1
Core(s) per socket:              8
Socket(s):                       2
Stepping:                        1
CPU(s) scaling MHz:              55%
CPU max MHz:                     3000.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        4199.56 
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 arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm
2 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 ep
b cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms
 invpcid rtm cqm rdt_a rdseed adx smap intel_pt xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts md_clear flush_l1d
Virtualization:                  VT-x
L1d cache:                       512 KiB (16 instances)
L1i cache:                       512 KiB (16 instances)
L2 cache:                        4 MiB (16 instances)
L3 cache:                        40 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-7
NUMA node1 CPU(s):               8-15
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT disabled
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT disabled
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT disabled
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; Retpolines, IBPB conditional, IBRS_FW, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; Clear CPU buffers; SMT disabled

Versions of relevant libraries:
[pip3] lovely-numpy==0.2.10
[pip3] numpy==1.26.1
[pip3] torch==2.1.0
[pip3] torch-complex==0.4.3
[pip3] torchaudio==2.1.0
[pip3] triton==2.1.0
[conda] Could not collect


cc @ptrblck @mruberry @peterbell10