Shortcuts

torch.Tensor.index_add_

Tensor.index_add_(dim, index, tensor, *, alpha=1)Tensor

Accumulate the elements of alpha times tensor into the self tensor by adding to the indices in the order given in index. For example, if dim == 0, index[i] == j, and alpha=-1, then the ith row of tensor is subtracted from the jth row of self.

The dimth dimension of tensor must have the same size as the length of index (which must be a vector), and all other dimensions must match self, or an error will be raised.

Note

This operation may behave nondeterministically when given tensors on a CUDA device. See Reproducibility for more information.

Parameters
  • dim (int) – dimension along which to index

  • index (IntTensor or LongTensor) – indices of tensor to select from

  • tensor (Tensor) – the tensor containing values to add

Keyword Arguments

alpha (Number) – the scalar multiplier for tensor

Example:

>>> x = torch.ones(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_add_(0, index, t)
tensor([[  2.,   3.,   4.],
        [  1.,   1.,   1.],
        [  8.,   9.,  10.],
        [  1.,   1.,   1.],
        [  5.,   6.,   7.]])
>>> x.index_add_(0, index, t, alpha=-1)
tensor([[  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.]])

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources