【问题标题】:How to save GPU memory usage in PyTorch如何在 PyTorch 中节省 GPU 内存使用量
【发布时间】:2020-01-16 10:39:54
【问题描述】:

我在 PyTorch 中编写了一个非常简单的 CNN 判别器并对其进行了训练。现在我需要部署它来进行预测。但是目标机器的 GPU 内存很小,并且出现内存不足错误。所以我认为我可以设置requires_grad = False 来防止PyTorch 存储梯度值。但是我没有发现它有什么不同。

我的模型中有大约 500 万个参数。但是在预测单批输入时,它会消耗大约 1.2GB 的内存。我认为应该不需要这么大的内存。

问题是当我只想使用我的模型进行预测时如何节省 GPU 内存使用量?


这是一个演示,我使用discriminator.requires_grad_ 来禁用/启用所有参数的自动分级。不过好像没什么用。

import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as functional

from pynvml.smi import nvidia_smi
nvsmi = nvidia_smi.getInstance()

def getMemoryUsage():
    usage = nvsmi.DeviceQuery("memory.used")["gpu"][0]["fb_memory_usage"]
    return "%d %s" % (usage["used"], usage["unit"])

print("Before GPU Memory: %s" % getMemoryUsage())

class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        # trainable layers
        # input: 2x256x256
        self.conv1 = nn.Conv2d(2, 8, 5, padding=2) # 8x256x256
        self.pool1 = nn.MaxPool2d(2) # 8x128x128
        self.conv2 = nn.Conv2d(8, 32, 5, padding=2) # 32x128x128
        self.pool2 = nn.MaxPool2d(2) # 32x64x64
        self.conv3 = nn.Conv2d(32, 96, 5, padding=2) # 96x64x64
        self.pool3 = nn.MaxPool2d(4) # 96x16x16
        self.conv4 = nn.Conv2d(96, 256, 5, padding=2) # 256x16x16
        self.pool4 = nn.MaxPool2d(4) # 256x4x4
        self.num_flat_features = 4096
        self.fc1 = nn.Linear(4096, 1024)
        self.fc2 = nn.Linear(1024, 256)
        self.fc3 = nn.Linear(256, 1)
        # loss function
        self.loss = nn.MSELoss()
        # other properties
        self.requires_grad = True
    def forward(self, x):
        y = x
        y = self.conv1(y)
        y = self.pool1(y)
        y = functional.relu(y)
        y = self.conv2(y)
        y = self.pool2(y)
        y = functional.relu(y)
        y = self.conv3(y)
        y = self.pool3(y)
        y = functional.relu(y)
        y = self.conv4(y)
        y = self.pool4(y)
        y = functional.relu(y)
        y = y.view((-1,self.num_flat_features))
        y = self.fc1(y)
        y = functional.relu(y)
        y = self.fc2(y)
        y = functional.relu(y)
        y = self.fc3(y)
        y = torch.sigmoid(y)
        return y
    def predict(self, x, score_th=0.5):
        if len(x.shape) == 3:
            singlebatch = True
            x = x.view([1]+list(x.shape))
        else:
            singlebatch = False
        y = self.forward(x)
        label = (y > float(score_th))
        if singlebatch:
            y = y.view(list(y.shape)[1:])
        return label, y
    def requires_grad_(self, requires_grad=True):
        for parameter in self.parameters():
            parameter.requires_grad_(requires_grad)
        self.requires_grad = requires_grad


x = torch.cuda.FloatTensor(np.zeros([2, 256, 256]))
discriminator = Discriminator()
discriminator.to("cuda:0")

# comment/uncomment this line to make difference
discriminator.requires_grad_(False)

discriminator.predict(x)

print("Requires grad", discriminator.requires_grad)
print("After GPU Memory: %s" % getMemoryUsage())

通过注释掉discriminator.requires_grad_(False)这一行,我得到了输出:

Before GPU Memory: 6350MiB
Requires grad True
After GPU Memory: 7547MiB

通过取消注释该行,我得到:

Before GPU Memory: 6350MiB
Requires grad False
After GPU Memory: 7543MiB

【问题讨论】:

  • 当我运行您的代码时,“之前”和“之后”的 GPU 内存使用量都在 900MB 左右。为什么你的内存使用率这么高?

标签: out-of-memory pytorch


【解决方案1】:

在进行预测时,请尝试在您的目标机器上使用 model.eval()torch.no_grad()model.eval() 将模型层切换到评估模式。 torch.no_grad() 将停用 autograd 引擎,从而减少内存使用量。

x = torch.cuda.FloatTensor(np.zeros([2, 256, 256]))
discriminator = Discriminator()
discriminator.to("cuda:0")

discriminator.eval()
with torch.no_grad():
    discriminator.predict(x)

【讨论】:

  • 谢谢,但似乎没有什么不同。据我所知,model.eval 只是针对特定模块进行区分,例如batchnormdropout。它告诉他们在评估模式而不是训练模式下表现。但是文档没有提到它会告诉变量不要保留梯度或其他一些数据。此外,我对torch如何知道我的子模块应该处于评估模式感到困惑,因为我只是在我的模块上调用eval。至于requires_grad_,我必须自己为我的模块实现这个功能,并将所有子模块的requires_grad设置为False
【解决方案2】:

您可以使用pynvml

这个 python 工具制作了 Nvidia,所以你可以像这样使用 Python 查询:

from pynvml.smi import nvidia_smi
nvsmi = nvidia_smi.getInstance()
nvsmi.DeviceQuery('memory.free, memory.total')

你也可以随时执行:

torch.cuda.empty_cache()

清空缓存,你会发现更多的可用内存。

在调用 torch.cuda.empty_cache() 之前,如果您有不再使用的对象,您可以这样调用:

obj = None

然后你打电话

gc.collect()

【讨论】:

  • 感谢您的建议。 pynvml 真的很棒!但是,我不认为torch.cuda.empty_cache() 可以解决我的问题。当然,预测计算后的回收最终会减少内存使用量。但峰值内存使用量不会减少。这就是我的问题的瓶颈。
  • 一旦您获得可用内存,您可以要求根据此调整批量大小。目前,您尚未设置。只要你设置你的图像有 2 个通道。也许这会有所帮助。
猜你喜欢
  • 2022-01-27
  • 2021-02-24
  • 2016-04-22
  • 2020-02-01
  • 2020-05-22
  • 2020-03-14
  • 2021-12-04
  • 2020-12-22
  • 1970-01-01
相关资源
最近更新 更多