sparse.FloatTensor: size is inconsistent with indices

With PyTorch 1.13, I want to create a sparse FloatTensor:

num_nodes = 29
num_edges = 75
n2n_idxes = torch.LongTensor(2, num_edges * 2)
n2n_vals = torch.FloatTensor(num_edges * 2)
n2n_sp = torch.sparse.FloatTensor(n2n_idxes, n2n_vals, torch.Size([num_nodes, num_nodes]))

Run script 1:
RuntimeError: found negative index -4745092176981434354 for dim 0
Run script 2:
RuntimeError: size is inconsistent with indices: for dim 0, size is 29 but found index 140147970303920

I found a similar question here: RuntimeError: sizes is inconsistent with indices. Pytorch 0.4.1
But the problem seems to be version related.
Any recommendations or solutions are highly appreciated!

You are using uninitialized memory in these lines of code:

num_nodes = 29
num_edges = 75
n2n_idxes = torch.LongTensor(2, num_edges * 2)
n2n_vals = torch.FloatTensor(num_edges * 2)

which means n2n_idxes and n2n_vals can contain any value including Infs, NaNs etc.
The error is thus expected, so make sure you are properly initializing the tensors before trying to create the sparse tensor.
I would generally recommend to use the factory method, such as torch.randn, torch.randint etc. instead of the explicit constructors for a dtype.

I think, you may try the code below

n2n_idxes = torch.LongTensor(torch.randint(1, num_nodes, [2, num_edges * 2]))

instead of

n2n_idxes = torch.LongTensor(2, num_edges * 2)

Many thanks, this solved the problem!