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利用率

RAM是您的数据被堆叠的地方。要进行处理,堆叠会被传输到SRAM或其他称为缓存的地方,这是离CPU最近的内存(称为主机(。为系统选择RAM内存的一般规则被认为等同于或大于GPU内存。

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

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

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

最新更新