调试GPU程序错误《CUDA out of memory》

问题描述

我们在跑深度学习程序的时候,经常会遇到CUDA out of memory,一些简单的方案比如

  • 缩小Batch Size
  • 及时的把不用的变量移动到CPU
  • 执行empty_cache()
  • 避免GPU变量累积,例如涉及到GPU变量的跨轮次的加操作和append操作

如果上述的方法依然没有解决问题,可以通过分析GPU上的变量来进行相关的调试:

def debug_memory():
    import collections, gc, resource, torch
    print('maxrss = {}'.format(
        resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))
    tensors = collections.Counter((str(o.device), o.dtype, tuple(o.shape))
                                  for o in gc.get_objects()
                                  if torch.is_tensor(o))
    for line in tensors.items():
        print('{}\t{}'.format(*line))

进一步的,可以完善一下代码:

def debug_memory_sum():
    print('maxrss = {}'.format(
        resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))
    tensors = collections.Counter((str(o.device), o.dtype, tuple(o.shape))
                                  for o in gc.get_objects()
                                  if torch.is_tensor(o))
    memory_total = 0
    for line in tensors.items():
        if line[0][0] == 'cuda:0':
            _shape = line[0][2]
            _cnt = line[1]
            if len(_shape) == 2:
                memory_total = memory_total + _cnt * (_shape[0] * _shape[1])
            elif len(_shape) == 1:
                memory_total = memory_total + _cnt * _shape[0]
            else:
                pass
    print(memory_total)

需要注意的是resource库只能用在linux系统上,然后如果你的算法任务涉及到三维(如图像、视频等)以上,注意修改并添加len(_shape)的判断条件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值