首页 > 解决方案 > GPU 上的神经网络使用系统 RAM 而不是 GPU 内存

问题描述

我使用 PyTorch 构建了一个基本的聊天机器人,在训练代码中,我将神经网络和训练数据都移动到了 gpu。但是,当我运行该程序时,它最多使用 2GB 的内存。使用了一点 gpu 内存,但没有那么多。当我运行相同的程序时,但这次是在 cpu 上,它只需要大约 900mb 的内存。谁能告诉我为什么会这样?我附上了我的代码,以及几个屏幕截图。抱歉,如果答案很明显,我是深度学习的新手。

我的代码:

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np
from nltk_utils import tokenizer, stem, bag_of_words
import pandas as pd

device = torch.device("cuda")

#Neural Network
class NeuralNetwork(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super().__init__()
        self.l1 = nn.Linear(input_size, hidden_size)
        self.l2 = nn.Linear(hidden_size, hidden_size)
        self.l3 = nn.Linear(hidden_size, hidden_size)
        self.l4 = nn.Linear(hidden_size, num_classes)
        self.relu = nn.ReLU()
        
    def forward(self, x):
        out = self.relu(self.l1(x))
        out = self.relu(self.l2(out))
        out = self.relu(self.l3(out))
        out = self.l4(out)
        return out
    
#data initialization
data = pd.read_csv("path_to_train_data")
data = data.dropna(axis=0)

allwords = []
taglist = []
xy = []
ignorewords = ["?", "!", "'", ","]

taglist.extend(x for x in data["tag"] if x not in taglist)

#developing vocabulary
for x in data["pattern"]:
    w = tokenizer(x)
    allwords.extend(stem(y) for y in w if y not in ignorewords)
    
#making training data
for indx, x in enumerate(data["pattern"]):
    w = tokenizer(x)
    bag = bag_of_words(w, allwords)
    tag = taglist.index(data["tag"].iloc[indx])
    xy.append((bag, tag))

xtrain = np.array([x[0] for x in xy])
ytrain = np.array([x[1] for x in xy])

class TestDataset(Dataset):
    def __init__(self):
        self.num_classes = len(xtrain)
        self.xdata = torch.from_numpy(xtrain.astype(np.float32))
        self.ydata = torch.from_numpy(ytrain.astype(np.float32))

    def __getitem__(self, index):
        return self.xdata[index], self.ydata[index]
    
    def __len__(self):
        return self.num_classes

dataset = TestDataset()    
train_data = DataLoader(dataset=dataset,
                        batch_size=8,
                        shuffle=True,
                        num_workers=0,
                        pin_memory=True)

inputSize = len(xtrain[0])
hiddenSize = 32
outputSize = len(taglist)

model = NeuralNetwork(inputSize, hiddenSize, outputSize).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())

epochs = 5000

for epoch in range(epochs):
    for (words, labels) in train_data:
        words = words.to(device)
        labels = labels.type(torch.LongTensor)
        labels = labels.to(device)

        y_pred = model(words)
        
        loss = criterion(y_pred, labels)
        
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        optimizer.step()
        
    with torch.no_grad():
        if (epoch + 1) % 10 == 0:
            print(f"epoch: {epoch + 1}, loss: {loss:.30f}")

在 GPU 上运行时: GPU 利用率RAM 利用率

在 CPU 上运行时: RAM 利用率

标签: pythondeep-learningneural-networkpytorch

解决方案


RAM 是您的数据被堆叠以继续进行的地方,然后将堆栈传输到 SRAM 或称为缓存,它是离 CPU(称为主机)最近的内存。为系统选择 RAM 内存的一般规则被认为等于或大于 GPU 内存。

例如:如果 GPU 内存为 8GB,则您需要有 8GB 或更大的 RAM 以确保最佳性能。

因此,当在 GPU(称为设备)上运行时,您的数据将直接传输到 GPU 以执行张量操作。但是在 CPU 上它不能执行并行计算,因此使用较少的 RAM 内存。

您可以尝试使用不同的 batch_size 并观察 RAM 使用情况。请注意,如果您的一批数据不适合 GPU 内存,您将看到 CUDA 内存不足错误。


推荐阅读