我对@987654322@的性能持怀疑态度,所以我用numpy搜索了类似的问题,发现this的帖子。
从 NumPy 到 Pytorch 的类似解决方案
我从@Andy L 那里得到了解决方案并将其翻译成pytorch。但是,请持保留态度,因为我不知道大步是如何工作的:
from numpy.lib.stride_tricks import as_strided
# NumPy solution:
def custom_roll(arr, r_tup):
m = np.asarray(r_tup)
arr_roll = arr[:, [*range(arr.shape[1]),*range(arr.shape[1]-1)]].copy() #need `copy`
#print(arr_roll)
strd_0, strd_1 = arr_roll.strides
#print(strd_0, strd_1)
n = arr.shape[1]
result = as_strided(arr_roll, (*arr.shape, n), (strd_0 ,strd_1, strd_1))
return result[np.arange(arr.shape[0]), (n-m)%n]
# Translated to PyTorch
def pcustom_roll(arr, r_tup):
m = torch.tensor(r_tup)
arr_roll = arr[:, [*range(arr.shape[1]),*range(arr.shape[1]-1)]].clone() #need `copy`
#print(arr_roll)
strd_0, strd_1 = arr_roll.stride()
#print(strd_0, strd_1)
n = arr.shape[1]
result = torch.as_strided(arr_roll, (*arr.shape, n), (strd_0 ,strd_1, strd_1))
return result[torch.arange(arr.shape[0]), (n-m)%n]
这也是@Daniel M 的即插即用解决方案。
def roll_by_gather(mat,dim, shifts: torch.LongTensor):
# assumes 2D array
n_rows, n_cols = mat.shape
if dim==0:
#print(mat)
arange1 = torch.arange(n_rows).view((n_rows, 1)).repeat((1, n_cols))
#print(arange1)
arange2 = (arange1 - shifts) % n_rows
#print(arange2)
return torch.gather(mat, 0, arange2)
elif dim==1:
arange1 = torch.arange(n_cols).view(( 1,n_cols)).repeat((n_rows,1))
#print(arange1)
arange2 = (arange1 - shifts) % n_cols
#print(arange2)
return torch.gather(mat, 1, arange2)
基准测试
首先,我在 CPU 上运行这些方法。
令人惊讶的是,上面的gather 解决方案是最快的:
n_cols = 10000
n_rows = 100
shifts = torch.randint(-100,100,size=[n_rows,1])
data = torch.arange(n_rows*n_cols).reshape(n_rows,n_cols)
npdata = np.arange(n_rows*n_cols).reshape(n_rows,n_cols)
npshifts = shifts.numpy()
%timeit roll_by_gather(data,1,shifts)
%timeit pcustom_roll(data,shifts)
%timeit custom_roll(npdata,npshifts)
>> 2.41 ms ± 68.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>> 90.4 ms ± 882 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
>> 247 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
在 GPU 上运行代码显示类似的结果:
%timeit roll_by_gather(data,shifts)
%timeit pcustom_roll(data,shifts)
131 µs ± 6.79 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
3.29 ms ± 46.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
(注意:roll_by_gather方法中需要torch.arange(...,device='cuda:0'))