torch.OutOfMemoryError: [address=172.25.162.164:42713, pid=17493] CUDA out of memory. Tried to allocate 86.00 MiB. GPU 0 has a total capacity of 14.57 GiB of which 20.75 MiB is free. Process 11546 has 2.23 GiB memory in use. Process 11633 has 1.32 GiB memory in use. Including non-PyTorch memory, this process has 10.99 GiB memory in use. Of the allocated memory 10.88 GiB is allocated by PyTorch, and 554.00 KiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
时间: 2025-03-22 18:02:25 浏览: 94
<think>好的,我现在需要解决用户遇到的PyTorch CUDA内存不足的问题。用户提供了几个引用,我需要先仔细分析这些引用内容,然后结合自己的知识给出解决方案。
首先,用户提到的错误信息是CUDA out of memory,通常是因为显存不够。引用[1]和[2]中的例子显示,显存总容量和已分配的情况,比如总共有10GiB,但已经分配了9.25GiB,导致没有剩余空间。这时候可能需要调整内存分配策略或者释放一些内存。
接下来,引用[3]和[4]提到了设置环境变量PYTORCH_CUDA_ALLOC_CONF为expandable_segments:True,以及在Windows和Linux下的不同设置方法。这可能帮助减少内存碎片,使得显存分配更高效。此外,引用[3]还提到设置PYTORCH_NO_CUDA_MEMORY_CACHING=1,禁用内存缓存,可能有助于解决问题。
引用[5]提到在NVIDIA控制面板中调整系统内存回退政策,设置为偏好系统内存回退,这可能让程序在显存不足时使用系统内存,但可能会影响性能。
现在,我需要将这些方法整理成步骤。首先检查是否有不必要的内存占用,比如释放不需要的张量,清空缓存。然后调整批量大小或者模型精度,比如使用半精度。接着设置环境变量,如PYTORCH_CUDA_ALLOC_CONF和禁用缓存。另外,用户提到的系统内存回退设置也是一个可能的解决方案。最后,如果这些都不行,可能需要升级硬件或者优化模型结构。
需要确保建议的步骤清晰,并且针对不同情况给出不同的解决方案。同时,要注意不同操作系统下的设置方法可能不同,比如Windows和Linux的环境变量设置方式。还要提醒用户这些方法可能的效果和潜在的影响,比如性能下降。</think>以下是解决PyTorch CUDA显存不足问题的分步方案:
### 1. 基础检查与显存释放
- **手动释放显存**:在代码中及时调用`torch.cuda.empty_cache()`,尤其在删除张量或模型后。
- **检查显存占用**:使用`nvidia-smi`或`torch.cuda.memory_summary()`观察显存分配情况。
- **示例代码**:
```python
import torch
del model # 删除不再使用的模型
torch.cuda.empty_cache() # 显式清空缓存
```
### 2. 调整模型与数据
- **降低批量大小**:将`batch_size`从32改为16或8,显存需求随批量大小线性增长。
- **混合精度训练**:使用`torch.cuda.amp`自动转换精度:
```python
with torch.autocast(device_type='cuda', dtype=torch.float16):
outputs = model(inputs)
```
- **梯度累积**:通过多次小批量迭代模拟大批量:
```python
for i, batch in enumerate(data):
loss = model(batch)
loss.backward()
if (i+1) % 4 == 0: # 每4个batch更新一次参数
optimizer.step()
optimizer.zero_grad()
```
### 3. 显存分配策略优化
- **Windows系统**:
```cmd
set PYTORCH_NO_CUDA_MEMORY_CACHING=1
set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
```
- **Linux系统**:
```bash
export PYTORCH_NO_CUDA_MEMORY_CACHING=1
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
```
此配置可减少内存碎片,使显存分配更灵活[^3][^4]。
### 4. 系统级设置
- **NVIDIA控制面板**:启用"CUDA - 系统内存回退政策"(路径:管理3D设置 → CUDA - 系统内存回退政策 → 偏好系统内存回退)[^5]。
- **限制显存预分配**:
```python
torch.cuda.set_per_process_memory_fraction(0.5) # 限制为50%显存
```
### 5. 模型架构优化
```python
# 使用检查点技术(如Transformer)
from torch.utils.checkpoint import checkpoint
def forward(self, x):
return checkpoint(self._forward, x) # 分段计算保留中间结果
```
### 6. 终极解决方案
若上述方法无效:
- 使用`torch.utils.data.DataLoader`的`pin_memory=False`
- 尝试`num_workers=0`减少数据加载线程
- 升级显卡驱动或PyTorch版本
- 最终手段:更换显存更大的GPU
阅读全文
相关推荐

















