Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
11
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@elm200

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
11
Help us understand the problem. What are the problem?