【问题标题】:Calling cuda() with async results in SyntaxError使用异步调用 cuda() 会导致 SyntaxError
【发布时间】:2023-03-16 00:30:01
【问题描述】:

我正在尝试运行这个 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)

但是当我尝试时,我收到了这个错误消息:

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

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

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出。请参阅How to Ask 链接以获取有关如何提出问题并相应更新您的问题的更多详细信息。

标签: python pytorch


【解决方案1】:

您的代码不起作用,因为:

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

  • cuda() 不再有一个参数async。构造函数如下所示:

cuda(device=None, non_blocking=False) → 张量

改用non_blocking:

参数non_blocking 与之前的async 具有相同的效果:



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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2021-02-17
      • 2015-12-09
      • 2015-02-06
      相关资源
      最近更新 更多