LoginSignup
11

More than 3 years have passed since last update.

posted at

PyTorch で GPU を使う

説明

基本的に .cuda() を使う。
1. モデル(net)
2. 入力(inputs)
3. 正解データ(labels)
のそれぞれに対して作用させること。

def try_gpu(e):
    if torch.cuda.is_available():
        return e.cuda()
    return e

みたいなメソッドを定義しておいて、

import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(28 * 28, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.view(-1, 28 * 28)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

net = Net()
net = try_gpu(net)

とか

epochs = 100

for epoch in range(epochs):
    running_loss = 0.0
    for i, (inputs, labels) in enumerate(trainloader, 0):
        # zero the parameter gradients
        optimizer.zero_grad()
        inputs = try_gpu(inputs)
        labels = try_gpu(labels)

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

        # print statistics
        running_loss += loss.item()
        if i % 100 == 99:
            print('[{:d}, {:5d}] loss: {:.3f}'
                    .format(epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0

print('Finished Training')

とかすると、自動的に CPU と GPU を切り替えられて良いかもしれない。
理想は、.cuda() を明示的にコードの中に入れないことなのだが、もっとよい方法があれば教えてください。

参考

PyTorchでMNIST

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
11