Memory leak in torch.fft.rfft
Labels: module: cuda, module: memory usage, triaged, module: fft

### 🐛 Describe the bug

Running the function `torch.fft.rfft` with tensors varying in size results in a memory leak. This does not happen when tensors stay the same size across iterations. With each iteration, additional memory is accumulated in amounts of ~2MB per run. This happens regardless of whether tensors are detached and placed on the CPU, or if the memory cache is cleared.

Below is a script to reproduce this leak on a GPU:

```
import torch
import random
import time
import subprocess

iters = 100

last_large_dim = -1
device = torch.device('cuda:2')

for i in range(iters):
    # removing the random size of this dimension removes the increase in memory on each iteration
    rand_dim = random.randint(8000, 15000)
    x = torch.randn(1, 768, rand_dim).to(device)

    # removing this line prevents memory from increasing 
    res = torch.fft.rfft(x, n=rand_dim)
    
    # even detaching and deleting does not clear the memory
    x = x.detach().cpu()
    del x
    
    res = res.detach().cpu()
    del res
    
    # regardless of whether we pass the largest dimension this happens
    if rand_dim > last_large_dim:
        last_large_dim = rand_dim
        print ('Newest largest dim created')
        
    # report from nvidia-smi
    torch.cuda.empty_cache()
    subprocess.run('nvidia-smi -g 2', shell=True)
    
    time.sleep(0.5)
```

I've also demonstrated this using a linearly decreasing dimension size by using `torch.linspace(15000, 8000, iters)`. Please let me know if you need any more information, or if there are suggestions for a quick fix! 

### Versions

PyTorch version: 1.12.1.post200
Is debug build: False
CUDA used to build PyTorch: 11.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.4.0-135-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA RTX A6000
GPU 1: NVIDIA RTX A6000
GPU 2: NVIDIA RTX A6000
GPU 3: NVIDIA RTX A6000
GPU 4: NVIDIA RTX A6000
GPU 5: NVIDIA RTX A6000
GPU 6: NVIDIA RTX A6000
GPU 7: NVIDIA RTX A6000

Nvidia driver version: 520.61.05
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
Address sizes:                   48 bits physical, 48 bits virtual
CPU(s):                          64
On-line CPU(s) list:             0-63
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       1
NUMA node(s):                    4
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7513 32-Core Processor
Stepping:                        1
Frequency boost:                 enabled
CPU MHz:                         1496.074
CPU max MHz:                     2600.0000
CPU min MHz:                     1500.0000
BogoMIPS:                        5199.51
Virtualization:                  AMD-V
L1d cache:                       1 MiB
L1i cache:                       1 MiB
L2 cache:                        16 MiB
L3 cache:                        128 MiB
NUMA node0 CPU(s):               0-7,32-39
NUMA node1 CPU(s):               8-15,40-47
NUMA node2 CPU(s):               16-23,48-55
NUMA node3 CPU(s):               24-31,56-63
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:          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; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
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 pcid sse4_1 sse4_2 x2apic 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 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 invpcid 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 arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca

Versions of relevant libraries:
[pip3] numpy==1.23.1
[pip3] pytorch-ignite==0.4.8
[pip3] pytorch-lightning==1.6.5
[pip3] pytorch-msssim==0.2.1
[pip3] torch==1.12.1.post200
[pip3] torchaudio==0.12.1
[pip3] torchio==0.18.86
[pip3] torchmetrics==0.11.0
[pip3] torchvision==0.13.0a0+8069656
[conda] cudatoolkit               11.3.1               h2bc3f7f_2    anaconda
[conda] magma                     2.5.4                hc72dce7_4    conda-forge
[conda] mkl                       2022.1.0           hc2b9512_224  
[conda] numpy                     1.23.1          py310hac523dd_0    anaconda
[conda] numpy-base                1.23.1          py310h375b286_0    anaconda
[conda] pytorch                   1.12.1          cuda112py310h51fe464_200    conda-forge
[conda] pytorch-ignite            0.4.8              pyhd8ed1ab_0    conda-forge
[conda] pytorch-lightning         1.6.5              pyhd8ed1ab_0    conda-forge
[conda] pytorch-msssim            0.2.1                    pypi_0    pypi
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                0.12.1              py310_cu113    pytorch
[conda] torchio                   0.18.86            pyhd8ed1ab_0    conda-forge
[conda] torchmetrics              0.11.0             pyhd8ed1ab_0    conda-forge
[conda] torchvision               0.13.0          cuda112py310h453157a_0    conda-forge


cc @ngimel @mruberry @peterbell10