根据这个SO和这个PyTorch讨论,PyTorch的view功能仅适用于连续内存,而reshape不能。在第二个链接中,作者甚至声称:
[
view] 将在非连续张量上引发错误。
但是张量什么时候有非连续内存呢?
这是一个非常好的答案,它在 NumPy 的背景下解释了这个主题。PyTorch 的工作原理基本相同。它的文档通常不会提及函数输出是否(不)连续,但可以根据操作的类型(具有一些经验和对实现的理解)来猜测。根据经验,大多数操作在构造新张量时都会保持连续性。如果该操作在数组上进行就地操作并更改其跨距,您可能会看到不连续的输出。下面几个例子
import torch
t = torch.randn(10, 10)
def check(ten):
print(ten.is_contiguous())
check(t) # True
# flip sets the stride to negative, but element j is still adjacent to
# element i, so it is contiguous
check(torch.flip(t, (0,))) # True
# if we take every 2nd element, adjacent elements in the resulting array
# are not adjacent in the input array
check(t[::2]) # False
# if we transpose, we lose contiguity, as in case of NumPy
check(t.transpose(0, 1)) # False
# if we transpose twice, we first lose and then regain contiguity
check(t.transpose(0, 1).transpose(0, 1)) # True
Run Code Online (Sandbox Code Playgroud)
一般来说,如果您有不连续的张量t,您可以通过调用 使其连续t = t.contiguous()。如果t是连续的,则调用t.contiguous()本质上是无操作,因此您可以在不冒性能受到重大影响的情况下执行此操作。
| 归档时间: |
|
| 查看次数: |
4624 次 |
| 最近记录: |