PyTorch切片赋值为何多次输出结果一致?
Great question! This behavior comes down to two core PyTorch design choices: compatible element counts and implicit shape adjustment during assignment. Let’s break it down clearly:
First, let’s look at the target we’re assigning to: a[-2:] is a 1D slice of the original tensor with shape (2,), meaning it holds exactly 2 elements. For any assignment to this slice to work, the right-hand side (RHS) tensor must have the same total number of elements as the slice—and PyTorch will automatically adjust the RHS shape to match the slice if possible.
Let’s analyze each case:
Case 1: 3D tensor
torch.tensor([[[5, 6]]])(shape(1, 1, 2))
This tensor has a total of1 * 1 * 2 = 2elements, which matches the slice’s element count. PyTorch recognizes that the leading dimensions (both size 1, called "singleton dimensions") don’t add any unique elements, so it implicitly squeezes those away to get a 1D tensor of shape(2,). The elements5and6then directly map to the slice’s positions.Case 2: 2D tensor
torch.tensor([[5, 6]])(shape(1, 2))
Again, this has1 * 2 = 2elements. The single leading singleton dimension is squeezed out, leaving a 1D tensor that perfectly matches the slice’s shape. The assignment copies the elements into the last two positions ofawithout issues.Case 3: 1D tensor
torch.tensor([5, 6])(shape(2,))
This is an exact shape match with the target slice. No adjustment is needed—PyTorch simply copies the elements directly into the slice.
Key Takeaway
PyTorch allows flexible assignments when:
- The RHS tensor has the same total number of elements as the target slice, AND
- The RHS shape can be implicitly reshaped (by removing leading singleton dimensions) to match the slice’s shape.
This avoids forcing you to manually reshape tensors every time you need to assign to a slice, making code cleaner and more intuitive.
内容的提问来源于stack exchange,提问作者apostofes

