Change dimension layout
Convert tensor layouts between conventions such as channel-first and channel-last.
PyTorch · Function
Reorders a tensor’s dimensions and returns a view of the original tensor. The dims argument specifies the desired axis order.
torch.permute returns a view of the input whose axes appear in the order specified by dims. The permutation changes the tensor shape and indexing interpretation without creating a separate data copy; dims can be supplied as a torch.Size, tuple, or list of integers.
torch.permute(input, dims)| Name | Type | Description |
|---|---|---|
input | Tensor | The tensor whose dimensions are to be reordered. |
dims | torch.Size, tuple of int, or list of int | The desired ordering of dimensions; a torch.Size, tuple of integers, or list of integers. |
A Tensor view of the original input with its dimensions permuted.
import torch
x = torch.randn(2, 3, 5)
y = torch.permute(x, (2, 0, 1))
assert x.shape == (2, 3, 5)
assert y.shape == (5, 2, 3)
assert y.storage().data_ptr() == x.storage().data_ptr()Reorders the three dimensions from (0, 1, 2) to (2, 0, 1), producing shape (5, 2, 3) while retaining shared storage.
Convert tensor layouts between conventions such as channel-first and channel-last.
Prepare multidimensional data for an operation that expects a particular axis order.
Reinterpret axis order without immediately allocating a separate tensor.
torch.permute(input, dims) returns a view of input with dimensions reordered according to dims. For an input shaped (2, 3, 5), the order (2, 0, 1) produces (5, 2, 3).
Follow-up: How would you avoid aliasing the input? Use a copying operation such as torch.permute_copy, which performs the permutation while creating fresh output tensors.
input is the tensor being rearranged. dims specifies the desired dimension ordering and may be a torch.Size, tuple of integers, or list of integers.
Follow-up: What does the dimension sequence represent? It identifies the original axis used at each position in the result, rather than giving the new size values directly.
The function changes the dimension order while returning a view, so the output can have a different shape without duplicating the tensor's underlying data. The documented example changes (2, 3, 5) to (5, 2, 3).
Follow-up: When is a separate tensor preferable? Choose a copying variant when subsequent code requires independently allocated output storage rather than an aliasing view.
torch.Tensor.permutetorch.permute_copy