Possible memory leak when using Torch and Torchvision in conjunction with XGBoost 
Labels: module: memory usage, triaged, module: vision

### 🐛 Describe the bug

I had an issue in one of the services I work on, where it would use more and more memory until crashing. After some digging around I was able to reduce it to the following script:
```python
import argparse
import logging
import math
import os

import psutil
import torch
import torchvision
import xgboost

import numpy as np


def main() -> None:
    process = psutil.Process(os.getpid())

    parser = argparse.ArgumentParser()
    parser.add_argument("xgboost_model_path")
    args = parser.parse_args()

    feature_extractor = torchvision.models.vit_b_16(num_classes=512)

    predictor = xgboost.XGBClassifier(
        base_score=0.5,
        booster=None,
        colsample_bylevel=1,
        colsample_bynode=1,
        colsample_bytree=1,
        gamma=0,
        gpu_id=-1,
        importance_type="gain",
        interaction_constraints=None,
        learning_rate=0.3,
        max_delta_step=0,
        max_depth=10,
        min_child_weight=1,
        missing=math.nan,
        monotone_constraints=None,
        n_estimators=300,
        n_jobs=32,
        num_parallel_tree=1,
        objective="multi:softprob",
        random_state=0,
        reg_alpha=0,
        reg_lambda=1,
        scale_pos_weight=None,
        subsample=1,
        tree_method=None,
        validate_parameters=False,
        verbosity=0,
    )
    predictor.load_model(args.xgboost_model_path)

    frames_torch = torch.rand((1, 3, 224, 224), device="cpu")
    i = 0
    while True:
        with torch.no_grad():
            embedding = feature_extractor(frames_torch).numpy().mean(axis=0)
        if i == 0:
            logging.warning(f"Mem usage (embedding) {process.memory_percent()}")
        features = np.expand_dims(embedding, 0)
        predictor.predict_proba(features)
        i = (i + 1) % 10

if __name__ == "__main__":
    main()
```
which uses the following xgboost model: [xgboost_classifier.txt](https://github.com/dmlc/xgboost/files/11720066/xgboost_classifier.txt) (txt format becuase github doesn't allow JSON, apparently).

I left this script running for a day and memory usage grew from 640MB to about 9GB. This issue seems to depend on the import order, if XGBoost is imported before torch and torchvision the memory usage is more or less constant (I didn't leave it to run for the same amount of time but I didn't see an upwards trend that's clearly visible otherwise).

### 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 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.26.4
Libc version: glibc-2.31

Python version: 3.9.15 (main, Jun 12 2023, 04:04:50)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-1036-aws-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.3.58
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla T4
Nvidia driver version: 510.47.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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
Stepping:                        7
CPU MHz:                         2469.691
BogoMIPS:                        4999.99
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       128 KiB
L1i cache:                       128 KiB
L2 cache:                        4 MiB
L3 cache:                        35.8 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; 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:          Vulnerable
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, STIBP disabled, 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 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke avx512_vnni

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.1
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] No relevant packages
```

cc @datumbox @vfdev-5 @pmeier