Undergraduate/ML & DL

[PyTorch tutorial] PyTorch에서 GPU 활용하기

unnjena 2020. 5. 12. 15:16
  • PyTorch에서 GPU를 활용하는 법은 간단하다. "모델을 GPU에 넣어주면 됨"
device = torch.device("cuda:0")
model.to(device)
  • 모든 텐서를 GPU에 넣어줌(input, lable 등)
mytensor = my_tensor.to(device)

GPU 활용 예시

  • 데이터 로드
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader

# Parameters and DataLoaders
input_size = 5
output_size = 2

batch_size = 30
data_size = 100
  • GPU 설정
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  • 랜덤 데이터 클래스 설정
class RandomDataset(Dataset):

    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return self.len

rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),
                         batch_size=batch_size, shuffle=True)
  • 모델 클래스 설정
class Model(nn.Module):
    # Our model

    def __init__(self, input_size, output_size):
        super(Model, self).__init__()
        self.fc = nn.Linear(input_size, output_size)

    def forward(self, input):
        output = self.fc(input)
        print("\tIn Model: input size", input.size(),
              "output size", output.size())

        return output

여러 GPU 사용하기

model = Model(input_size, output_size)
if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  model = nn.DataParallel(model)

model.to(device)
  • Let's use 3 GPUs!

for data in rand_loader:
    input = data.to(device)
    output = model(input)
    print("Outside: input size", input.size(),
          "output_size", output.size())