These two lines look almost identical, but in PyTorch they do very different things because of the way Python’s augmented-assignment (+=) works versus calling an in-place method (add_).
- x[indices, :seq_len] += pos_embed[:, :seq_len]
Python translates the augmented assignment roughly as
tmp = x.__getitem__((indices, slice(None, seq_len)))
tmp = tmp + pos_embed[:, :seq_len] # element-wise add
x.__setitem__((indices, slice(None, seq_len)), tmp)
Therefore PyTorch:
• Reads the selected rows/columns.
• Adds pos_embed to that slice.
• Writes the result back into the original tensor x.
So the underlying tensor x is really modified.
If the same index appears more than once, the contribution is accumulated (just like torch.index_add_).
- x[indices, :seq_len].add_(pos_embed[:, :seq_len])
Here you first obtain the indexed tensor, and then you call add_ on it:
view_or_copy = x[indices, :seq_len]
view_or_copy.add_(pos_embed[:, :seq_len])
But when you use “advanced indexing” (indices is a LongTensor / list / ndarray), PyTorch returns a copy, not a view.
Doing an in-place operation on that copy changes only the temporary tensor, not x itself.
When the line finishes, the copy is discarded and x is left untouched.
(If you had used only basic slicing, e.g. x[:, :seq_len], the slice would be a view and add_ would modify x, but as soon as you mix in tensor/boolean indexing you get a copy.)
Quick demo
>>> import torch
>>> x = torch.zeros(5, 3)
>>> idx = torch.tensor([0, 2])
# line 1 behaviour
>>> x[idx, :2] += 1
>>> x
tensor([[1., 1., 0.],
[0., 0., 0.],
[1., 1., 0.],
[0., 0., 0.],
[0., 0., 0.]])
# reset
>>> x.zero_()
# line 2 behaviour
>>> x[idx, :2].add_(1)
>>> x # unchanged
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
Summary
• a[idx] += b ➜ modifies the original tensor a (write-back happens).
• a[idx].add_(b) ➜ modifies only the temporary result of the indexing; for advanced indexing that change does not propagate to a.
So if you actually want to update x, use the += form (or index_add_).