我试图深入了解PyTorch Tensor内存模型是如何工作的。
# input numpy array
In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2)
# input tensors in two different ways
In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr)
# their types
In [93]: type(arr), type(t1), type(t2)
Out[93]: (numpy.ndarray, torch.FloatTensor, torch.FloatTensor)
# ndarray
In [94]: arr
Out[94]:
array([[ 0., 1.],
[ 2., 3.],
[ 4., 5.],
[ 6., 7.],
[ 8., 9.]], dtype=float32)
我知道PyTorch张贴共享NumPy ndarrays的内存缓冲区。因此,改变一个将反映在另一个。所以,我在这里切片并更新Tensor t2
In [98]: t2[:, 1] = 23.0
正如预期的那样,它已在t2
和arr
中更新,因为它们共享相同的内存缓冲区。
In [99]: t2
Out[99]:
0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]
In [101]: arr
Out[101]:
array([[ 0., 23.],
[ 2., 23.],
[ 4., 23.],
[ 6., 23.],
[ 8., 23.]], dtype=float32)
但 t1
也已更新。请注意,t1
是使用torch.Tensor()
构建的,而t2
是使用torch.from_numpy()
构建的
In [100]: t1
Out[100]:
0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]
因此,无论我们使用torch.from_numpy()
还是torch.Tensor()
从ndarray构造张量,所有这样的张量和ndarrays共享相同的内存缓冲区。
基于这种理解,我的问题是,为什么只有torch.from_numpy()
能够完成这项工作才能存在专用函数torch.Tensor()
?
我查看了PyTorch文档,但它没有提及任何相关内容?有什么想法/建议吗?
答案 0 :(得分:9)
from_numpy()
自动继承输入数组dtype
。另一方面,torch.Tensor
是torch.FloatTensor
的别名。
因此,如果将int64
数组传递给torch.Tensor
,则输出张量为浮点张量,它们将不会共享存储。 torch.from_numpy
为您提供了torch.LongTensor
。
a = np.arange(10)
ft = torch.Tensor(a) # same as torch.FloatTensor
it = torch.from_numpy(a)
a.dtype # == dtype('int64')
ft.dtype # == torch.float32
it.dtype # == torch.int64
答案 1 :(得分:1)
这来自_torch_docs.py
;还有可能讨论" 为什么" here
def from_numpy(ndarray): # real signature unknown; restored from __doc__
"""
from_numpy(ndarray) -> Tensor
Creates a :class:`Tensor` from a :class:`numpy.ndarray`.
The returned tensor and `ndarray` share the same memory.
Modifications to the tensor will be reflected in the `ndarray`
and vice versa. The returned tensor is not resizable.
Example::
>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
torch.LongTensor([1, 2, 3])
>>> t[0] = -1
>>> a
array([-1, 2, 3])
"""
pass
取自numpy
文档:
不同的
ndarrays
可以共享相同的数据,因此在一个ndarray中所做的更改可能在另一个中可见。也就是说,ndarray
可以是另一个ndarray
的“视图”,它所指的数据由“基础”ndarray
处理。
Pytorch docs
:
如果给出
numpy.ndarray
,torch.Tensor
或torch.Storage
,则返回共享相同数据的新张量。如果给出了Python序列,则从序列的副本创建新的张量。
答案 2 :(得分:0)
在Pytorch中构建张量的推荐方法是使用以下两个工厂函数:torch.tensor
和torch.as_tensor
。
torch.tensor
始终复制数据。例如,torch.tensor(x)
等效于x.clone().detach()
。
torch.as_tensor
始终尝试避免复制数据。 as_tensor
避免复制数据的一种情况是原始数据是一个numpy数组。
答案 3 :(得分:0)
我尝试按照您所说的进行操作,并且按预期工作: 火炬 1.8.1、Numpy 1.20.1、python 3.8.5
x = np.arange(8, dtype=np.float64).reshape(2,4)
y_4mNp = torch.from_numpy(x)
y_t = torch.tensor(x)
print(f"x={x}\ny_4mNp={y_4mNp}\ny_t={y_t}")
所有变量现在都具有与预期相同的值:
x=[[0. 1. 2. 3.]
[4. 5. 6. 7.]]
y_4mNp=tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.]], dtype=torch.float64)
y_t=tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.]], dtype=torch.float64)
From_numpy 确实使用 np 变量使用的相同底层内存。 因此,更改 np 或 .from_numpy 变量会相互影响,但不会影响张量变量。 但是对 y_t 的更改仅影响其自身,而不影响 numpy 或 from_numpy 变量。
x[0,1] = 111 ## changed the numpy variable itself directly
y_4mNp[1,:] = 500 ## changed the .from_numpy variable
y_t[0,:] = 999 ## changed the tensor variable
print(f"x={x}\ny_4mNp={y_4mNp}\ny_t={y_t}")
现在输出:
x=[[ 0. 111. 2. 3.]
[500. 500. 500. 500.]]
y_4mNp=tensor([[ 0., 111., 2., 3.],
[500., 500., 500., 500.]], dtype=torch.float64)
y_t=tensor([[999., 999., 999., 999.],
[ 4., 5., 6., 7.]], dtype=torch.float64)
不知道这是不是早期版本的问题?