The two lines of code provided in PyTorch behave differently due to how PyTorch handles in-place operations and advanced indexing. Here's a breakdown of their behavior:
1. x[indices, :seq_len] += pos_embed[:, :seq_len]
Behavior: This line does modify the original tensor x.
Mechanism:
x[indices, :seq_len] uses advanced indexing (e.g., indices is a tensor of indices), which creates a copy of the relevant portion of x.
The += operator is equivalent to x[indices, :seq_len] = x[indices, :seq_len] + pos_embed[:, :seq_len].
PyTorch implicitly handles this by:
Reading the values from x at the specified indices.
Adding pos_embed to them.
Writing the result back to the original tensor x at the same indices.
Effect: The original tensor x is updated in-place.
Use x[indices, ...] += ... when you want to update the original tensorx.
Avoid x[indices, ...].add_(...) if you intend to modify x, as it only affects a temporary copy.
This distinction is critical when working with advanced indexing in PyTorch, as in-place operations on copies do not propagate changes back to the original tensor.