执行 torch.matmul() 时出现 RuntimeError

Posted

技术标签:

【中文标题】执行 torch.matmul() 时出现 RuntimeError【英文标题】:RuntimeError when execute torch.matmul() 【发布时间】:2020-08-12 23:27:22 【问题描述】:

我正在尝试实现注意力模型,但未能执行 matmul

torch.matmul(att, v)

att和v的形状是:

att shape:torch.Size([20, 3, 128, 128])
v shape:torch.Size([20, 3, 128, 100])

我收到这样的错误:

RuntimeError:预期张量在维度 1 处的大小为 100,但参数 #2 'batch2' 的大小为 128(同时检查 bmm 的参数)

我还尝试通过 torch.randn 生成两个具有相同形状的张量并重复相同的操作并且没有出现错误。我不知道是什么导致了这样的错误

【问题讨论】:

PyTorch 版本?无法在1.4.1上重现 我在 pytorch 版本 1.3.0 的服务器上训练我的模型。我在自己的笔记本电脑上使用 torch.randn() 进行测试,其中 pytorch 版本是 1.3.1 我在服务器上运行我的测试脚本并没有发生错误,似乎是上一步导致它 【参考方案1】:

可能内存和形状对齐的差异。如果您使用视图方法,您可以根据需要处理张量形状。但是内存上的数组没有被重塑。这有时会导致不清楚的问题。因此 contiguous() 或 reshape() 可能会对您有所帮助。

参考: https://pytorch.org/docs/master/tensors.html?highlight=view#torch.Tensor.view What's the difference between reshape and view in pytorch?

【讨论】:

感谢您的帮助。这两种方法我都试过了,都不管用。

以上是关于执行 torch.matmul() 时出现 RuntimeError的主要内容,如果未能解决你的问题,请参考以下文章

每天讲解一点PyTorch torch.matmul

每天讲解一点PyTorch torch.matmul

torch.matmul(input, other, *, out=None)

torch.matmul(input, other, *, out=None)

pytorch的matmul怎么广播

执行“eb local run”时出现“注册表配置无效”错误