Deep learning based on pytorch--Data parallelization

Source: Internet
Author: User
Tags pytorch dataloader

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. http://blog.csdn.net/zzlyw/article/details/78769012

Preface

This article refers to the Pytorch official website of the tutorial, divided into five basic modules to introduce Pytorch. In order to avoid the article too long, these five modules are introduced in five blog post respectively.

Part1:pytorch Simple Knowledge

Automatic gradient calculation of Part2:pytorch

PART3: Building a neural network using Pytorch

PART4: Training A neural network classifier

PART5: parallelization of data


This article is about the content of Part5.

Part5: parallelization of data

In this article, you'll talk about Dataparallel using multiple GPUs.

Using the GPU in Pytorch is simpler, so you can put the model on the GPU.

Model.gpu ()

You can also copy all the tensors onto the GPU.

Mytensor = My_tensor.gpu ()

Note that simply calling MYTENSOR.GPU () does not copy the tensor onto the GPU. You need to assign it to a new tensor and then use the new tensor on the GPU.

Forward and reverse propagation can run on multiple GPUs. However, Pytorch uses only one GPU by default. You can use Dataparallel to make your model parallel on a GPU.

Model = NN. Dataparallel (model)

1 package Import and parameter settings

Import the Pytorch module and set the parameters.

Import Torch
import torch.nn as nn from
Torch.autograd import Variable from
torch.utils.data import Dataset, Dataloader

# Parameters and dataloaders
input_size = 5
output_size = 2

batch_size =
Data_size = 100

2 Virtual datasets

To make a virtual (random) dataset, you only need to execute getitem.

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, +),
                         batch_size=batch_size, shuffle= True)

3 Simple Model

As an example, our model just gets the input, carries on the linear operation, gives the result. However, you can apply dataparallel to any model (Cnn,rnn,capsule Net, and so on).

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 ("In  Model: Input Size ", input.size (),
              " Output size ", output.size ())

        return output

4 Creating models and data parallelism

This is the core content of this tutorial. We need to make a model instance and check if there are multiple GPUs. If you have multiple GPUs, you can use NN. Dataparallel packed our model. After that, we can put the model on the GPU using Model.gpu ().

Model = Model (input_size, output_size)
if Torch.cuda.device_count () > 1:
  print ("Let's use", Torch.cuda.device_count (), "gpus!")
  # Dim = 0 [+, xxx], [...], [Ten, ...], [Ten, ...] on 3 GPUs
  model = NN. Dataparallel (model)

if torch.cuda.is_available ():
   Model.cuda ()

5 Running the model

For data in Rand_loader:
    if Torch.cuda.is_available ():
        Input_var = Variable (Data.cuda ())
    else:
        input _var = Variable (data)

    output = Model (Input_var)
    print ("Outside:input size", input_var.size (),
          "Output_ Size ", output.size ())

Expected output:

In Model:input size torch. Size ([5]) output size torch. Size ([2])
outside:input size torch. Size ([5]) Output_size Torch. Size ([2]) in
  model:input size torch. Size ([5]) output size torch. Size ([2])
outside:input size torch. Size ([5]) Output_size Torch. Size ([2]) in
  model:input size torch. Size ([5]) output size torch. Size ([2])
outside:input size torch. Size ([5]) Output_size Torch. Size ([2]) in
  model:input size torch. Size ([5]) output size torch. Size ([ten, 2])
outside:input size torch. Size ([Ten, 5]) Output_size Torch. Size ([10, 2])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.