如何使PyTorch DCGAN代码在GPU上运行?

时间:2020-05-10 23:38:32

标签: python pytorch gpu generative-adversarial-network

我正在尝试在GPU上训练DCGAN,但是当我开始使用PyTorch时,我尝试从文档中做一些事情,并且它可以工作,但是我想确认这是否是正确的做事方法因为我看过很多关于在GPU上运行它的问题,但是它们以不同的方式完成。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    public Transform[] spawnPoints;
    public GameObject enemy;
    public float spawnTime = 5f;
    public float spawnDelay = 3f; 

    // Use this for initialization
    void Start () {
        InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
    }

    void addEnemy() {
        int spawnPointIndex = Random.Range(0, spawnPoints.Length);
        Instantiate (enemy, spawnPoints[spawnPointIndex].position, 
spawnPoints[spawnPointIndex].rotation);
    }
}

1 个答案:

答案 0 :(得分:1)

关于您的代码的一些评论:

  1. 您的device变量的值是什么?
    确保是torch.device('cuda:0')(或您的GPU的设备ID是什么)。
    否则,如果您的device实际上是torch.device('cpu'),那么您将在CPU中运行。
    有关更多信息,请参见torch.device

  2. 您删除了代码的“模型”部分,但是您可能跳过了其中的重要部分:您是否也将模型移到了GPU?通常,模型包含许多内部参数(又称可训练的权重),您在设备上也需要它们。
    您的代码也应该有

dis.to(device)
criterion.to(device)  # if your loss function also has trainable parameters

请注意,与torch.tensor不同的是,在.to上调用nn.Modulean "in place" operation

  1. 您的代码中有多余的地方:您不必同时调用 .cuda().to()
    调用.cuda()是将事物移至GPU的旧方法,但是一段时间以来pytorch引入了.to()来简化编码。

  2. 由于您的输入和模型都在GPU上,因此您也无需将输出也明确移至设备。因此,您可以将output = dis(input).cuda().to(device)替换为output = dis(input)

  3. 无需显式使用Variable。您可以替换

noise = Variable(torch.randn(input.size()[0], 100, 1, 1)).cuda().to(device)

使用

noise = torch.randn(input.size()[0], 100, 1, 1), device=input.device)

您还可以将target变量使用torch.zeros_liketorch.ones_like

target = torch.zeros_like(input)

请注意,zeros_likeone_like会为您照顾设备(和数据类型),它与input的设备相同。

相关问题