首页 > 解决方案 > 为什么不使用 torch.cuda.empty_cache() 释放 CUDA 内存

问题描述

在我的 Windows 10 上,如果我直接创建一个 GPU 张量,我可以成功释放它的内存。

import torch
a = torch.zeros(300000000, dtype=torch.int8, device='cuda')
del a
torch.cuda.empty_cache()

但是如果我创建一个普通张量并将其转换为 GPU 张量,我将无法再释放它的内存。

import torch
a = torch.zeros(300000000, dtype=torch.int8)
a.cuda()
del a
torch.cuda.empty_cache()

为什么会这样。

标签: pytorch

解决方案


至少在 Ubuntu 中,您的脚本在交互式 shell 中运行时不会释放内存,并且在作为脚本运行时按预期工作。我认为就地通话中存在一些参考问题。以下将在交互式 shell 和脚本中工作。

import torch
a = torch.zeros(300000000, dtype=torch.int8)
a = a.cuda()
del a
torch.cuda.empty_cache()

推荐阅读