Python 在某些应用程序上禁用GPU

Python 在某些应用程序上禁用GPU,python,pytorch,Python,Pytorch,我试图在Nvidia GPU上训练一些神经网络,但桌面环境(KDE)似乎正在占用GPU: $ nvidia-smi Sat Apr 22 09:04:16 2017 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 375.39 Driver Version: 375.39 |

我试图在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
回溯(最近一次呼叫最后一次):
文件“”,第64行,在
cuda中的文件“/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site packages/torch/nn/modules/module.py”,第147行
返回自应用(lambda t:t.cuda(设备id))
文件“/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site packages/torch/nn/modules/module.py”,第118行,适用于
模块应用(fn)
文件“/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site packages/torch/nn/modules/module.py”,第124行,适用于
参数数据=fn(参数数据)
文件“/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site packages/torch/nn/modules/module.py”,第147行,在
返回自应用(lambda t:t.cuda(设备id))
文件“/home/kaiyin/virtualenvs/pytorch/lib/python3.5/site-packages/torch/_-utils.py”,第65行,中文版
返回新类型(self.size()).copy(self,异步)
运行时错误:cuda运行时错误(46):所有支持cuda的设备在/b/wheel/pytorch src/torch/lib/THC/generic/THCStorage处忙或不可用。cu:66
汽车猫鸟狗

如何禁用那些与kde相关的进程使用GPU,并让它们改用Intel graphics?

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

  • 减少批大小:一次仅将一批加载到GPU中。小批量将占用更少的GPU内存。(尝试将批量大小减少到1,看看是否有效?)。看,你还有500多个MiB的GPU内存,批处理大小为4。如果您无法仅使用一个批处理运行该模型,那么尝试释放681MiB/usr/lib/xorg/xorg很可能对您没有帮助

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

  • 关闭GUI并在仅终端模式下运行(因为您不需要GUI,只需一个终端就可以运行python代码),这样可以节省600 MB的GPU内存。尝试将GUI移动到其他GPU中要容易得多。尝试搜索关键字:“如何在ubuntu中打开GUI”


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

  • 减少批大小:一次仅将一批加载到GPU中。小批量将占用更少的GPU内存。(尝试将批量大小减少到1,看看是否有效?)。看,你还有500多个MiB的GPU内存,批处理大小为4。如果您无法仅使用一个批处理运行该模型,那么尝试释放681MiB/usr/lib/xorg/xorg很可能对您没有帮助

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

  • 关闭GUI并在仅终端模式下运行(因为您不需要GUI,只需一个终端就可以运行python代码),这样可以节省600 MB的GPU内存。尝试将GUI移动到其他GPU中要容易得多。尝试搜索关键字:“如何在ubuntu中打开GUI”


  • 这不是一个真正的编程问题,最好在其他地方问,比如askubuntu.com。我在想这可能会涉及一些脚本。这不是一个真正的编程问题,最好在其他地方问一下,比如askubuntu.com。我在想这可能需要一些脚本。