how to assign value to a tensor using index correctly?

I defined four tensors that represent index_x,index_y,index_z,and value,respectively and assigned value to a new tensor using these three index. Why were the results of the two assignments different?

import torch
import numpy as np
import random
import os

def seed_torch(seed=0):
    random.seed(seed)
    np.random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

seed_torch(1)
a_list, b_list, c_list = [], [], []
for i in range(0, 512*512):
    a_ = random.randint(0, 399)
    b_ = random.randint(0, 399)
    c_ = random.randint(0, 199)
    a_list.append(a_)
    b_list.append(b_)
    c_list.append(c_)
a = torch.tensor(a_list)
b = torch.tensor(b_list)
c = torch.tensor(c_list)
v = torch.rand(512*512)
matrix1 = torch.zeros(400,400,200)
matrix2 = torch.zeros(400,400,200)
index=[a,b,c]
matrix1[index]=v
matrix2[index]=v
m = matrix1 - matrix2
print(m.sum())

print(m.sum()) is not zero

You are using repetitive indices, which will write to the same index in an undefined order.
You can check it by comparing the shape of the indices and their unique length:

index = torch.stack(index)
u = index.unique(dim=1)
print(index.shape)
> torch.Size([3, 262144])
print(u.shape)
> torch.Size([3, 261021])
1 Like

Thank you very much! If I want to calculate the mean of repetitive indices as the value of this index, how can I achieve it fast? If I use circular judgement, it will be very slow.

You could use torch.unique with return_counts=True, check for each index with counts > 1, and grab the index. Once you have all repeated indices, you could use it to calculate the position of these indices and use this to calculate the mean of v.