如何在Google Colaboratory(Tensorflow)中不重启运行时清除GPU内存

23

我想为神经风格转换算法运行超参数调整,这会导致一个for循环,在每次迭代中,我的模型输出用不同超参数生成的图像。

它在使用GPU运行时的Google Colaboratory中运行。 在运行时,我会在某个时刻得到一个错误,说我的GPU内存几乎满了,然后程序就停止了。

所以我想也许有一种方法可以在某些特定的迭代次数之后清除或重置GPU内存,以便程序可以正常终止(通过for循环中的所有迭代,而不仅仅是1500个或3000个,因为GPU内存已满)。

我已经尝试过从网上找到的这段代码:

# Reset Keras Session
def reset_keras():
    sess = get_session()
    clear_session()
    sess.close()
    sess = get_session()

    try:
        del classifier # this is from global space - change this as you need
    except:
        pass

    #print(gc.collect()) # if it's done something you should see a number being outputted

    # use the same config as you used to create the session
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 1
    config.gpu_options.visible_device_list = "0"
    set_session(tf.Session(config=config))
3个回答

10

在TensorFlow中,您可以使用Numba库:

!pip install numba

from numba import cuda 
device = cuda.get_current_device()
device.reset()

1
这是可行的答案。 - Furkan Gözükara
2
执行此操作后,我收到了RuntimeError: CUDA error: an illegal memory access was encountered错误提示。 - Adarsh Raj
1
这将重置我的整个Colab环境,所以如果你和我一样,有一堆文件正在煮了几个小时但无法成功保存,千万不要这样做,否则会破坏你的实验! - undefined

6

您可以在笔记本的单元格中运行命令"!nvidia-smi",并像"!kill 进程ID"这样杀死GPU的进程。尝试使用更简单的数据结构,如字典、向量。

如果你在使用PyTorch,运行命令torch.cuda.clear_cache


2
有时候,没有要终止的进程ID。 - M. Riché
截至2023年6月,命令为torch.cuda.empty_cache()。 - abhishek
截至2023年6月,命令为torch.cuda.empty_cache()。 - undefined

6
如果你正在使用torch,torch.cuda.empty_cache()是一种方法,应该在执行nvidia-smi之后使用,以确保你不能直接杀死进程。

对我来说不起作用 - undefined
我试过了,但是资源使用小部件仍然是红色的。一点都没有改变。这是不是意味着它已经清除了缓存? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接