torch.Tensor.Tensor.transpose_
Tensor.transpose_(dim0: number, dim1: number): thisSwaps two dimensions of the tensor in-place, modifying this tensor.
This is the in-place (mutating) version of transpose() that swaps dimensions without
creating a new tensor. Use when you want to save memory and don't need to keep the original
tensor layout. The shape of this tensor is modified to reflect the swapped dimensions.
- Memory efficient: Does not allocate new memory for the result, just modifies shape.
- In-place mutation: Modifies this tensor directly. References to this tensor will see the new shape after the operation.
- Modifies this tensor in-place. If you need the original layout, use
transpose()instead. - May cause issues if the tensor is part of an active computation graph.
Parameters
dim0number- First dimension to swap (supports negative indexing)
dim1number- Second dimension to swap (supports negative indexing)
Returns
this– This tensor with dimensions swapped in-placeExamples
// In-place transpose modifies the tensor directly
const x = torch.zeros(2, 3, 4);
x.transpose_(0, 2); // Shape changes to [4, 3, 2]
// Converting channel layouts in-place
const image = torch.randn(height, width, channels);
image.transpose_(0, 2); // Now [channels, width, height]
// Memory-efficient for large batches when original not needed
const batch = torch.randn(batch_size, n, m);
batch.transpose_(-2, -1); // In-place swap last two dimensionsSee Also
- PyTorch tensor.transpose_(dim0, dim1)
- transpose - Creates a new tensor with transposed dimensions
- t_ - In-place version for 2D tensors