System memory leak when using different input size of torch.nn.Conv3d
Labels: module: cudnn, module: nn, module: cuda, module: memory usage, triaged

### 🐛 Describe the bug

There is a system memory leak when using different input sizes to `torch.nn.Conv3d` on the GPU. A very simple script to reproduce the issue is:

```python
import gc

import psutil
import torch
import torch._C
import torch._dynamo
import torch.backends.cudnn as cudnn


class Model(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()

        self.convolution = torch.nn.Sequential(
            torch.nn.Conv3d(
                in_channels=1,
                out_channels=32,
                kernel_size=1,
                dilation=1,
                bias=False,
            ),
            torch.nn.Conv3d(
                in_channels=32,
                out_channels=1,
                kernel_size=1,
                dilation=1,
                bias=False,
            ),
        )

    def forward(self, input, labels):
        output = self.convolution(input)

        loss = torch.abs(output - labels).mean()

        return loss


class Trainer:
    def train(self) -> None:
        # Set our device.
        device = torch.device("cuda:0")

        # Set some training flags.
        cudnn.benchmark = False
        cudnn.deterministic = False

        # Create module.
        module = Model()
        module.to(device=device)

        # Put model in train mode.
        module.train()

        # Create optimizer.
        optimizer = torch.optim.Adam(module.parameters(), lr=1e-5)
        optimizer.zero_grad()

        # Train for a number of steps.
        for step in range(1, 1_000_000):
            if step % 10 == 0:
                self._report_leak_stats(step)

            input, labels = self._get_example(device)

            # Run model.
            loss = module(input, labels)

            # Raise on nan.
            if torch.isnan(loss).item():
                raise RuntimeError("Encountered nan loss during training.")

            # Do backwards pass.
            loss.backward()

            # Step optimizer and zero gradients after.
            optimizer.step()
            optimizer.zero_grad()

    def _get_example(self, device):
        depth = int(torch.randint(10, 80, size=()))
        height = int(torch.randint(10, 80, size=()))
        width = int(torch.randint(10, 80, size=()))

        return (
            torch.rand((1, 1, depth, height, width), dtype=torch.float32, device=device),
            torch.rand((1, 1, depth, height, width), dtype=torch.float32, device=device),
        )

    def _report_leak_stats(self, step):
        gc.collect()
        torch._C._cuda_clearCublasWorkspaces()
        torch._dynamo.reset()
        gc.collect()
        torch.cuda.empty_cache()
        gc.collect()

        print(
            "step",
            step,
            "residual memory",
            psutil.Process().memory_info().rss / 1e6,
            "MB",
        )


def main():
    Trainer().train()


if __name__ == "__main__":
    main()
```

When running it will show the residual memory of the process which keeps increasing over time. This is not the case for fixed inputs. The memory leak does not appear to be Python objects (I checked using various profilers). The memory leak seems to be affected by the filter size (and corresponding padding). Bigger filter sizes create bigger leaks.

The leak is fairly small per step (about 4 MB is leaked per 10 steps) but is really problematic when using DDP with multiple processes as it multiplies. Also the leak seems to be bigger for more convolutions.

Took me a very long time to track this leak down to make a minimal example :sweat_smile: . It restricts us from training a 3D model to convergence that takes variable sized inputs (3D scans). I feel like there could be other use cases where the input is variable.

### Versions

```                                                                                                                                                                                                                                  
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 22.04.1 LTS (x86_64)                                                                                                                                                                                                                                                
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0                                                                                                                                                                                                                           
Clang version: 14.0.0-1ubuntu1                                                                                                                                                                                                                                                 
CMake version: version 3.26.0                                                                                                                                                                                                                                                  
Libc version: glibc-2.35                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                                               
Python version: 3.10.9 (main, Mar 29 2023, 10:13:28) [GCC 11.3.0] (64-bit runtime)                                                                                                                                                                                             
Python platform: Linux-5.15.0-56-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 RTX 3090                                                                                                                                                                                                                                                 
GPU 1: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 2: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 3: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 4: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 5: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 6: NVIDIA GeForce RTX 3090                                                                                                                                                                                                                                                 
GPU 7: NVIDIA GeForce RTX 3090

Nvidia driver version: 525.60.11
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.6.0
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 7302 16-Core Processor
CPU family:                      23
Model:                           49
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       2
Stepping:                        0
Frequency boost:                 enabled
CPU max MHz:                     3000.0000
CPU min MHz:                     1500.0000
BogoMIPS:                        5999.84
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 rapl 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 rdpru 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:                       1 MiB (32 instances)
L1i cache:                       1 MiB (32 instances)
L2 cache:                        16 MiB (32 instances)
L3 cache:                        256 MiB (16 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-15,32-47
NUMA node1 CPU(s):               16-31,48-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:          Mitigation; untrained return thunk; SMT enabled with STIBP protection
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, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] mypy==1.1.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.2
[pip3] torch==2.0.1
[pip3] torch-summary==1.4.5
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[conda] Could not collect
```

cc @csarofeen @ptrblck @xwang233 @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki