这是一个简单的(就地)示例,不确定真正大张量的性能:
代码:
import torch
# Create some tensors
N = 3
A = torch.ones(N, 3, 3)
A[1] *= 2
A[2] *= 3
B = torch.zeros(N*3, N*3)
def diagonalizer(A, B):
N = A.shape[0]
i_min = 0
j_min = 0
i_max = 3
j_max = 3
for t in range(N):
B[i_min:i_max, j_min:j_max] = A[t] # NOTE! this is inplace operation
# do the step:
i_min += 3
j_min += 3
i_max += 3
j_max += 3
print('before:\n', B, sep='')
diagonalizer(A, B)
print('after:\n', B, sep='')
输出:
before:
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.]])
after:
tensor([[1., 1., 1., 0., 0., 0., 0., 0., 0.],
[1., 1., 1., 0., 0., 0., 0., 0., 0.],
[1., 1., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 2., 2., 2., 0., 0., 0.],
[0., 0., 0., 2., 2., 2., 0., 0., 0.],
[0., 0., 0., 2., 2., 2., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 3., 3., 3.],
[0., 0., 0., 0., 0., 0., 3., 3., 3.],
[0., 0., 0., 0., 0., 0., 3., 3., 3.]])