我正在尝试在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);
}
}
答案 0 :(得分:1)
关于您的代码的一些评论:
您的device
变量的值是什么?
确保是torch.device('cuda:0')
(或您的GPU的设备ID是什么)。
否则,如果您的device
实际上是torch.device('cpu')
,那么您将在CPU中运行。
有关更多信息,请参见torch.device
。
您删除了代码的“模型”部分,但是您可能跳过了其中的重要部分:您是否也将模型移到了GPU?通常,模型包含许多内部参数(又称可训练的权重),您在设备上也需要它们。
您的代码也应该有
dis.to(device)
criterion.to(device) # if your loss function also has trainable parameters
请注意,与torch.tensor
不同的是,在.to
上调用nn.Module
是an "in place" operation。
您的代码中有多余的地方:您不必同时调用 .cuda()
和.to()
。
调用.cuda()
是将事物移至GPU的旧方法,但是一段时间以来pytorch引入了.to()
来简化编码。
由于您的输入和模型都在GPU上,因此您也无需将输出也明确移至设备。因此,您可以将output = dis(input).cuda().to(device)
替换为output = dis(input)
。
无需显式使用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_like
和torch.ones_like
:
target = torch.zeros_like(input)
请注意,zeros_like
和one_like
会为您照顾设备(和数据类型),它与input
的设备相同。