torch.Tensor.Tensor.permute
Tensor.permute<D0 extends number, D1 extends number>(d0: D0, d1: D1): Tensor<DynamicShape, D, Dev>Tensor.permute(...dims: number[]): Tensor<DynamicShape, D, Dev>Permutes (reorders) dimensions of the tensor.
Rearranges dimensions according to the specified order. Essential for adapting tensor layouts between different operations, moving batch dimensions, transposing multi-dimensional arrays, and preparing data for different modules.
Common use cases:
- Transpose matrices and tensors
- Move batch dimension: (height, width, batch, channels) -> (batch, channels, height, width)
- Swap dimensions for operations: (seq, batch, features) -> (batch, seq, features)
- Prepare for convolution/attention modules
- Match different conventions (channels-first vs channels-last)
- Must specify all dimensions: Every dimension must appear exactly once. Order matters.
- Negative indexing: Dimensions can be specified with negative indices.
- Compile-time safety: TypeScript ensures you have correct number of dimensions.
- Gradient flow: Gradients flow correctly through permutation.
Parameters
d0D0d1D1
Returns
Tensor<DynamicShape, D, Dev>– Tensor with dimensions reorderedExamples
// Transpose a matrix
const x = torch.randn(3, 4); // 3x4
const transposed = x.permute(1, 0); // 4x3
// Reorder image batch dimensions
const x = torch.randn(32, 224, 224, 3); // [batch, height, width, channels]
const reordered = x.permute(0, 3, 1, 2); // [batch, channels, height, width] - PyTorch convention
// Channels-last to channels-first
const nhwc = torch.randn(batch_size, 224, 224, 3); // TensorFlow format
const nchw = nhwc.permute(0, 3, 1, 2); // PyTorch format
// Sequence processing: move batch to position 1
const x = torch.randn(seq_len, batch_size, features); // RNN output
const x_batched = x.permute(1, 0, 2); // [batch, seq_len, features]
// Using array form
const x = torch.randn(2, 3, 4, 5);
const perm1 = x.permute(0, 2, 1, 3); // Variadic form
const perm2 = x.permute([0, 2, 1, 3]); // Array form (equivalent)
// Negative indexing
const x = torch.randn(2, 3, 4);
const last_first = x.permute(-1, 0, 1); // [4, 2, 3] (-1 means last dimension)See Also
- PyTorch tensor.permute()
- transpose - Swap two dimensions specifically
- t - Transpose 2D matrix (shorthand)
- reshape - General shape transformation