【问题标题】:CUDA Illegal Memory Access error when using torch.cat使用 torch.cat 时出现 CUDA 非法内存访问错误
【发布时间】:2021-04-07 11:18:40
【问题描述】:

我正在玩 pytorch concatenate,想看看我是否可以使用与输入张量具有不同设备的输出张量,这是代码:

import torch
a = torch.ones(4)
b = torch.ones(4) 
c = torch.zeros(8).cuda()
print(c)
ab = torch.cat([a,b], out=c)
print(c)

我在 jupyter 笔记本中运行它。 pytorch 版本:1.7.1

我收到以下错误:

...
\Anaconda3\envs\...\lib\site-packages\torch\_tensor_str.py in __init__(self, tensor)
     87 
     88         else:
---> 89             nonzero_finite_vals = torch.masked_select(tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0))
     90 
     91             if nonzero_finite_vals.numel() == 0:

RuntimeError: CUDA error: an illegal memory access was encountered

如果您尝试访问张量 c(在本例中为 print),就会发生这种情况。

我在documentation 中找不到任何说我无法这样做的内容,除了这行:

" ...任何相同类型张量的python序列..."

这个错误有点奇怪……有什么想法吗?

【问题讨论】:

  • 我无法复制该问题,cat 操作会产生“预期的后端 CUDA 对象但得到了 CPU ...”,这是预期的,因为您将 2 个 cpu 张量连接到一个 gpu 张量中。 print 语句不会引起任何问题。您确定您粘贴的代码实际上会产生这个确切的错误吗?
  • 我敢肯定,这是笔记本中唯一的东西……你是在笔记本中运行的吗?火炬版本是一样的吗?很奇怪...... - 编辑:无论python内核是否新鲜,都会发生这种情况

标签: python memory pytorch concatenation


【解决方案1】:

似乎行为会根据 pytorch 的版本而变化。使用 1.3.0 版时,我收到错误 expected object of backend CUDA but got CPU,但在 1.5.0 版中,我确实遇到了与您相同的错误。这可能在他们的 github 上值得一提,因为我相信前者的错误比后者更有用。

无论如何,这两个错误都来自您将 cpu 张量连接到 GPU 的事实。你可以很容易地解决它:

# Move the tensors to the GPU prior to concatenating
ab = torch.cat([a.cuda(),b.cuda()], out=c)

# Move the tensor after concatenating
c.copy_(torch.cat([a,b]).cuda())

我没有笔记本,但我相信你必须重新启动内核,你得到的错误似乎把它弄坏了。在获得非法内存访问后,我的 python shell 无法再计算任何东西。

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,并重现了上面的错误,但有细微的差别:

    # 080521 debug RuntimeError: CUDA error: an illegal memory access was encountered 
    # https://stackoverflow.com/questions/66985008/cuda-illegal-memory-access-error-when-using-torch-cat
    
    import torch
    a = torch.ones(4)
    b = torch.ones(4) 
    c = torch.zeros(8).cuda()
    print(c)
    ab = torch.cat([a,b], out=c) # throws error below: 
    print(c)
    
    # RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! 
    #         (when checking arugment for argument tensors in method wrapper__cat_out_out)
    #         i.e. 'expected object of backend CUDA but got CPU'
    

    应用此逻辑:Using CUDA with pytorch?(将张量类型设置为 cuda)解决了错误:

    import torch
    torch.set_default_tensor_type('torch.cuda.FloatTensor')
    a = torch.ones(4)
    b = torch.ones(4) 
    c = torch.zeros(8).cuda()
    print(c)
    ab = torch.cat([a,b], out=c)
    print(c)
    

    【讨论】:

    • @trialNerror 嗨!感谢您对上述解决方案的 cmets。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2020-12-27
    • 1970-01-01
    • 2018-12-27
    • 2017-01-29
    相关资源
    最近更新 更多