Error while Assigning Multiple Indices

I have a multi-dimensional tensor of and I want to change the value at only certain indices. I tried the numpy method of indexing using a list of indices but its producing some weird and inconsistent behavior. Sometimes it works as I want it to but at some, apparently arbitrary, indices I get an out-of-bounds error. Please look at the code below to get an idea of what I am talking about:

>>> import torch
>>> a = torch.zeros((3,3))
>>> idxs = [(2,2),(2,1)]
>>> a[idxs] = 2
>>> a
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  2.,  2.]])
# This is is exactly what I wanted

# Now for the weirdness
>>> a = torch.zeros((6,32))
>>> idxs = [(2,6),(2,1)]
>>> a[idxs]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: invalid argument 2: out of range: 193 out of 192 at /pytorch/aten/src/TH/generic/THTensorMath.c:430

# I tried the same indices, in the reverse order and no error
>>> idxs = [(2,1),(2,6)]
>>> a[idxs]
tensor([ 0.,  0.])

Any idea what I am doing wrong?
Most probably its not a bug and I have some misunderstanding about how this format of indexing works in pytorch.

I’m not sure if you really get the indices you would like to have.
Have a look at the following code:

a = torch.arange(6*32).view(6,32)
idxs = [(2,1),(2,6)]
> tensor([66, 38])

You are basically getting a[2, 2] and a[1, 6], which explains the error in the other example.
If you want a[2, 1] and a[2, 6] try:

idxs = ([2, 2], [1, 6])
a[2, 1]
a[2, 6]

Note that the error is hidden in your first example, as the column and row tensors are (2, 2) and (2, 1).

Oh, so each sub-list should contain the indices of the respective dimensions. Got it. Thanks :slight_smile: