Repository: pytorch
Issue: RuntimeError: !block->expandable_segment_ INTERNAL ASSERT FAILED at "../c10/cuda/CUDACachingAllocator.cpp":2814, please report a bug to PyTorch. 
Labels: triaged,module: CUDACachingAllocator

### 🐛 Describe the bug

I got a GPU out-of-memory error, and thus was playing around with `PYTORCH_CUDA_ALLOC_CONF` to maybe optimize the memory allocation a bit (because my peak allocated memory usage was 8.1GB, on a 11GB GPU, so I was hoping that it should still fit by tuning mem alloc).

So, in one experiment, I did:
```
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,max_split_size_mb:32"
```

This results in the very strange error:
```
RuntimeError: !block->expandable_segment_ INTERNAL ASSERT FAILED at "../c10/cuda/CUDACachingAllocator.cpp":2814, please report a bug to PyTorch. 
```

A bit more detailed stack trace from my real-world example:
```
...
  File "/u/zeyer/setups/combined/2021-05-31/tools/espnet/espnet/nets/pytorch_backend/transformer/positionwise_feed_forward.py", line 32, in PositionwiseFeedForw
ard.forward
    line: return self.w_2(self.dropout(self.activation(self.w_1(x))))
    locals:
      self = <local> PositionwiseFeedForward(
                       (w_1): Linear(in_features=512, out_features=1024, bias=True)
                       (w_2): Linear(in_features=1024, out_features=512, bias=True)
                       (dropout): Dropout(p=0.1, inplace=False)
                       (activation): Swish()
                     )
      self.w_2 = <local> Linear(in_features=1024, out_features=512, bias=True)
      self.dropout = <local> Dropout(p=0.1, inplace=False)
      self.activation = <local> Swish()
      self.w_1 = <local> Linear(in_features=512, out_features=1024, bias=True)
      x = <local> tensor[23, 85, 512] n=1000960 (3.8Mb) x∈[-5.002, 5.912] μ=-0.000 σ=1.010 grad NativeLayerNormBackward0 cuda:3
  File "/work/tools/users/zeyer/py-envs/py3.11-torch2.1/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1518, in Module._wrapped_call_impl
    line: return self._call_impl(*args, **kwargs)
    locals:
      self = <local> Swish()
      self._call_impl = <local> <bound method Module._call_impl of Swish()>
      args = <local> (tensor[23, 85, 1024] n=2001920 (7.6Mb) x∈[-7.600, 4.125] μ=-0.307 σ=0.711 grad ViewBackward0 cuda:3,)
      kwargs = <local> {}
  File "/work/tools/users/zeyer/py-envs/py3.11-torch2.1/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1527, in Module._call_impl
    line: return forward_call(*args, **kwargs)
    locals:
      forward_call = <local> <bound method Swish.forward of Swish()>
      args = <local> (tensor[23, 85, 1024] n=2001920 (7.6Mb) x∈[-7.600, 4.125] μ=-0.307 σ=0.711 grad ViewBackward0 cuda:3,)
      kwargs = <local> {}
  File "/u/zeyer/setups/combined/2021-05-31/tools/espnet/espnet/nets/pytorch_backend/conformer/swish.py", line 18, in Swish.forward
    line: return x * torch.sigmoid(x)
    locals:
      x = <local> tensor[23, 85, 1024] n=2001920 (7.6Mb) x∈[-7.600, 4.125] μ=-0.307 σ=0.711 grad ViewBackward0 cuda:3
      torch = <global> <module 'torch' from '/work/tools/users/zeyer/py-envs/py3.11-torch2.1/lib/python3.11/site-packages/torch/__init__.py'>
      torch.sigmoid = <global> <built-in method sigmoid of type object at 0x7fa6eddaeaa0>
RuntimeError: !block->expandable_segment_ INTERNAL ASSERT FAILED at "../c10/cuda/CUDACachingAllocator.cpp":2814, please report a bug to PyTorch. 

Module call stack:
(DistributedDataParallel.forward) (unknown)
(_WrappedModuleRunStep.forward) (unknown)
(ESPnetASRModel.forward) (root)
(ESPnetASRModel.encode) (root)
(EBranchformerEncoder.forward) encoder
(MultiSequential.forward) encoder.encoders
(EBranchformerEncoderLayer.forward) encoder.encoders.13
(PositionwiseFeedForward.forward) encoder.encoders.13.feed_forward_macaron
(Swish.forward) encoder.encoders.0.feed_forward.activation
```

I also created a simple script which reproduces the issue below. Set `PYTORCH_CUDA_ALLOC_CONF` as above before you run this.

```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)
    while True:
        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 = x * x.sigmoid()
        print("y:", y)


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

    try:
        main()
    except KeyboardInterrupt:
        print("KeyboardInterrupt")
        sys.exit(1)
```

Output:
```
PyTorch: 2.1.0+cu121 
GPU: NVIDIA GeForce GTX 1080 Ti
Total GPU memory 10.9GB, alloc 381.5MB, free 10.4GB (95.0%) 
Total GPU memory 10.9GB, alloc 762.9MB, free 10.0GB (91.6%)
Total GPU memory 10.9GB, alloc 1.1GB, free 9.6GB (88.2%) 
Total GPU memory 10.9GB, alloc 1.5GB, free 9.3GB (84.8%)
Total GPU memory 10.9GB, alloc 1.9GB, free 8.9GB (81.4%) 
Total GPU memory 10.9GB, alloc 2.2GB, free 8.5GB (78.0%)
Total GPU memory 10.9GB, alloc 2.6GB, free 8.1GB (74.6%)
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.2%) 
Total GPU memory 10.9GB, alloc 5.2GB, free 5.5GB (50.6%)
Total GPU memory 10.9GB, alloc 5.6GB, free 5.2GB (47.2%)
Total GPU memory 10.9GB, alloc 6.0GB, free 4.8GB (43.8%) 
Total GPU memory 10.9GB, alloc 6.3GB, free 4.4GB (40.4%)
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.6GB (23.4%)
Total GPU memory 10.9GB, alloc 8.6GB, free 2.2GB (20.0%) 
Total GPU memory 10.9GB, alloc 8.9GB, free 1.8GB (16.6%)
Total GPU memory 10.9GB, alloc 9.3GB, free 1.4GB (13.2%)
Total GPU memory 10.9GB, alloc 9.7GB, free 1.1GB (9.8%)
Total GPU memory 10.9GB, alloc 10.1GB, free 714.1MB (6.4%) 
Total GPU memory 10.9GB, alloc 10.4GB, free 314.1MB (2.8%)
Total GPU memory 10.9GB, alloc 10.7GB, free 74.1MB (0.7%) 
x: tensor[65, 44252] n=2876380 (11Mb) x∈[-4.764, 5.217] μ=-0.000 σ=1.000 cuda:0
y: tensor[65, 44252] n=2876380 (11Mb) x∈[-0.278, 5.189] μ=0.206 σ=0.559 cuda:0 
x: tensor[60, 67919] n=4075140 (16Mb) x∈[-4.990, 5.044] μ=2.652e-05 σ=1.000 cuda:0
y: tensor[60, 67919] n=4075140 (16Mb) x∈[-0.278, 5.012] μ=0.207 σ=0.559 cuda:0
Traceback (most recent call last):
  File "/u/zeyer/code/playground/torch-make-oom.py", line 89, in <module> 
    main()
  File "/u/zeyer/code/playground/torch-make-oom.py", line 44, in main
    x = torch.randn(n_batch, n_time, device=dev)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: !block->expandable_segment_ INTERNAL ASSERT FAILED at "../c10/cuda/CUDACachingAllocator.cpp":2814, please report a bug to PyTorch. 
```

### 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 @ezyang @gchanan @zou3519 @kadeng