torch.nn.utils.invert_permutation
function invert_permutation(permutation: number[]): number[]Inverts a permutation array.
Given a permutation (a mapping from positions), returns the inverse permutation. If applying permutation P to array X gives Y, then applying the inverse permutation to Y recovers X. Essential for:
- Sequence reordering: Undoing sorting operations on variable-length sequences
- RNN batch handling: Restoring original sequence order after packing/unpacking
- Data manipulation: Reversing any permutation-based reordering
- Inverse operations: Mathematical operations that require undoing permutations
- Involution property: Inverting twice gives the original:
invert_permutation(invert_permutation(p)) === p - Linear time: O(n) operation, very fast for any practical size
- In-place capable: Implementation reuses input array (be aware if mutability matters)
Parameters
permutationnumber[]- Array of indices representing a permutation (values must be unique integers from 0 to length-1)
Returns
number[]– The inverse permutation array (same length as input)Examples
// Basic inversion
const perm = [2, 0, 1];
const inv = torch.nn.utils.rnn.invert_permutation(perm);
// inv: [1, 2, 0]
// Verify inverse property
const original = [10, 20, 30];
const reordered = perm.map(i => original[i]); // [30, 10, 20]
const restored = inv.map(i => reordered[i]); // [10, 20, 30]
// Identity permutation
const identity = torch.nn.utils.rnn.invert_permutation([0, 1, 2]);
// identity: [0, 1, 2]See Also
- PyTorch torch.nn.utils.rnn.invert_permutation()
- pack_sequence - Related operation that reorders sequences for RNN processing
- unpack_sequence - Uses permutations internally to restore original sequence order