在某些应用程序上禁用GPU

时间:2017-04-22 07:06:45

标签: python pytorch

我试图在Nvidia GPU上训练一些神经网络,但似乎桌面环境(KDE)占据了GPU:

$ nvidia-smi 
Sat Apr 22 09:04:16 2017       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.39                 Driver Version: 375.39                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 960M    Off  | 0000:01:00.0     Off |                  N/A |
| N/A   52C    P0    N/A /  N/A |   1295MiB /  2002MiB |      4%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      1139    G   /usr/lib/xorg/Xorg                             681MiB |
|    0      1591    G   kwin_x11                                        50MiB |
|    0      1594    G   /usr/bin/krunner                                13MiB |
|    0      1596    G   /usr/bin/plasmashell                           126MiB |
|    0      2267    G   ...el-token=FF7F1AB0E04D51461A7E5E08B2463625   136MiB |
+-----------------------------------------------------------------------------+

这是我正在运行的python代码:

import torch
import torchvision
import torchvision.transforms as transforms


transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
                                         shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

import matplotlib.pyplot as plt
import numpy as np

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))

# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
imshow(torchvision.utils.make_grid(images))
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))


from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
net.cuda()


import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # wrap them in Variable
        inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.data[0]
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

错误:

Traceback (most recent call last):
  File "<input>", line 64, in <module>
  File "/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/nn/modules/module.py", line 147, in cuda
    return self._apply(lambda t: t.cuda(device_id))
  File "/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/nn/modules/module.py", line 118, in _apply
    module._apply(fn)
  File "/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/nn/modules/module.py", line 124, in _apply
    param.data = fn(param.data)
  File "/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/nn/modules/module.py", line 147, in <lambda>
    return self._apply(lambda t: t.cuda(device_id))
  File "/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/_utils.py", line 65, in _cuda
    return new_type(self.size()).copy_(self, async)
RuntimeError: cuda runtime error (46) : all CUDA-capable devices are busy or unavailable at /b/wheel/pytorch-src/torch/lib/THC/generic/THCStorage.cu:66
  car   cat  bird   dog

如何禁用这些kde相关进程使用GPU,让他们使用英特尔图形呢?

1 个答案:

答案 0 :(得分:0)

您似乎没有足够的GPU内存进行培训。有一些解决方案:

  1. 减少批量大小:一次只有一批批量加载到GPU中。小批量大小将占用较少的GPU内存。 (尝试将批量大小减小到1以查看它是否有效?)。看,你有超过500 MiB的GPU内存,你的批量大小为4.如果你只能用1批运行模型,那么很有可能试图释放681MiB的/ usr / lib / xorg / Xorg不会帮助你。

  2. 在GPU上运行非常简单的示例代码(不应该是计算机视觉问题,因此不需要太多的GPU内存)。此步骤确认您正确安装了CUDA和Pytorch,并且GPU应该可以正常工作。

  3. 关闭GUI并在仅终端模式下运行(因为您不需要GUI,只需一个终端即可运行python代码),它可以节省600 MB的GPU内存。尝试将GUI移动到其他GPU中要容易得多。尝试搜索关键字:&#34;如何在ubuntu中转换GUI&#34;