# Functionality of tensor.index_copy_

Hi,

I am trying to use tensor.index_copy_, but having some issues regarding tensor’s dimensions.

On the Pytorch documents, there is an example:

x = torch.zeros(5,3)
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9]], dtype=torch.float)
index = torch.tensor([0, 4, 2])
x.index_copy_(0, index, t)

These codes result in x as:
x = [[1, 2, 3],
[0, 0, 0],
[7, 8, 9],
[0, 0, 0],
[4, 5, 6]]

I understood this example with the dimension of 0, but if I try to use it with dimension of 1 in similar example, I receive an runtime error that indicates some dimension issues. For the clarification, I will leave an example of this below:

x = torch.zeros(5,3)
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]], dtype=torch.float)
index = torch.tensor([0, 2, 1])
x.index_copy_(1, index, t)

I expect to receive x as
[[1, 3, 2],
[4, 6, 3],
[7, 9, 8],
[10, 12, 11],
[13, 15, 14],]
but running these codes results in the following error:
RuntimeError: index_copy_(): Source.destination tensor must have same slice shapes. Destination slice shape: [5] at dimension 1 and source slice shape: [3] at dimension 0.

Could someone explain what is wrong with this? Thank you!

Your code snippet seems to work and returns the right result:

``````x = torch.zeros(5,3)
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]], dtype=torch.float)
index = torch.tensor([0, 2, 1])
x.index_copy_(1, index, t)
> tensor([[ 1.,  3.,  2.],
[ 4.,  6.,  5.],
[ 7.,  9.,  8.],
[10., 12., 11.],
[13., 15., 14.]])
``````
1 Like

When I run the same code on my environment, it raises with the error below.

RuntimeErrorTraceback (most recent call last)
in ()
----> 1 x.index_copy_(1, index, t)

RuntimeError: index_copy_(): Source/destination tensor must have same slice shapes. Destination slice shape: [5] at dimension 1 and source slice shape: [3] at dimension 0.

I am running this code in torch version 0.4.0.
What I notice is that if I run the same code on the torch version 0.3.1, then it runs as I expected, but it does not run properly once I use torch version 0.4.0. Do you know how to run this code on version 0.4.0?
Thank you!

I’m not sure, but I would recommend to update to the latest stable release as described here.
A lot of bug fixes were shipped in the versions after `0.4.0`, and this might be a particular bug.

1 Like