在numpy和pytorch中大步前进,如何强制写入数组或“输入Tensor和写入到的Tensor引用单个内存位置”?

jslywgbw  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(141)

在使用numpy数组和pytorchTensor进行实验时,我发现了一个不同之处,那就是试图对依赖于先前时间步长的时间序列“施魔法”
numpy-esque库的一个关键特性是,它们通常不复制数据,而是在不同的视图中操作数据。在numpy中,最有趣的工具之一是使用stride_tricks的函数。
作为一个更简单的问题,我试图做一个“inplace cumsum”,但我偶然发现numpy不会出错的事实和一个看似等效的pytorch代码。我并不需要一个inplace cumsum实现,而是需要使用inbroadcast计算数据的inplace broadcast操作。
所以我的问题是我怎样才能强迫pytorch允许求和?;我怎么才能让numpy不复制我的数据并对它求和?

import numpy as np
# array = np.arange(6.)
array = np.arange(6.).reshape(2,3) + 3
# array([[3., 4., 5.],
#       [6., 7., 8.]])
s = np.lib.stride_tricks.as_strided(array, shape=(1,3)) # array([[3., 4., 5.]])
array += s
array
# array([[ 6.,  8., 10.],
#        [ 9., 11., 13.]])
import torch
t = torch.arange(6.).reshape(2,3) + 3
# tensor([[3., 4., 5.],
        # [6., 7., 8.]])
s = t.as_strided(size=(1,3),stride=(1,1)) # tensor([[3., 4., 5.]])
t += s
t
# RuntimeError                              Traceback (most recent call last)
#       3 # tensor([[3., 4., 5.],
#       4         # [6., 7., 8.]])
#       5 s = t.as_strided(size=(1,3),stride=(1,1)) # tensor([[3., 4., 5.]])
# ----> 6 t += s
#       7 t

# RuntimeError: unsupported operation: some elements of the input tensor and the written-to tensor refer to a single memory location. Please clone() the tensor before performing the operation.

期望:

#sum the first row to itself inplace
#sum the 2nd row with the inplace modified 1st row
array([[6., 8., 10.],
      [12., 15., 18.]])
nzk0hqpo

nzk0hqpo1#

In [129]: arr=np.arange(3,9).reshape(2,3);
In [130]: s=arr[None,0]  # or the strided

In [131]: np.add.at(arr,((0,1,1),slice(None)),s)

In [132]: arr
Out[132]: 
array([[ 6,  8, 10],
       [12, 15, 18]])

In [133]: s
Out[133]: array([[ 6,  8, 10]])

add.at最常用于处理重复索引。
虽然数字匹配,但我不确定它是否符合你的要求。

相关问题