异步调用cuda()会导致SyntaxError

use*_*791 1 python pytorch

我正在尝试运行以下PyTorch代码:

for i, (input, target) in enumerate(train_loader):

    input = input.float().cuda(async=True)
    target = target.cuda(async=True)
    input_var = torch.autograd.Variable(input)
    target_var = torch.autograd.Variable(target)

    output = model(input_var)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试时,我收到此错误消息:

input = input.float().cuda(async=True)
                               ^
SyntaxError: invalid syntax
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我已经安装了cuda。

小智 10

有一个async参数,但现在已弃用,因为async在 Python 3.7 中成为保留字。详细信息包含在此问题rename .cuda(async=..) parameters 中。您可以使用non_blocking作为替代。


blu*_*nox 8

您的代码无效,因为:

  • async 是python中的保留关键字,不能以这种方式使用,这就是为什么您得到 SyntaxError

  • cuda()本身也没有争论async。构造函数如下所示:

    CUDA设备=无,non_blocking =假)?张量

你可以做什么:

  • 只需cuda()不带任何参数的调用就可以正常工作。

  • 您可以使用两个参数(devicenon_blocking)进行调用cuda()
    您没有写您想做的事情,但是non_blocking可能是您要找的东西:

    • non_blocking (布尔):
      如果True并且源位于固定内存中,则副本将相对于主机是异步的。否则,该参数无效。默认值:False
  • 总是很高兴查看文档:https :
    //pytorch.org/docs/stable/tensors.html#torch.Tensor.cuda



作为附加组件:如果您对async实际使用的东西感兴趣,可以在这里查看:https : //www.python.org/dev/peps/pep-0492/#new-syntax