@KFrank 's method is a great ad hoc way to inverse a permutation.
If the argument is rather large (say >=10000 elements) and you know it is a permutation (0…9999) then you could also use indexing:
def inverse_permutation(perm):
    inv = torch.empty_like(perm)
    inv[perm] = torch.arange(perm.size(0), device=perm.device)
    return inv

This will give the same result (again, if you knew the input is a permutation), but on my computer and with 100.000 elements, a quick %timeit benchmark has it faster on the CPU (~4ms vs. ~165µs) and on the GPU (~147µs vs. ~20µs).
In other words, this is something where the O(n log n) complexity of sort vs. the O(n) complexity of index assignment shows for large operands.
The beauty of @KFrank’s solution is that you don’t need to write a new function, it instantly generalizes to batches, too. Unless you are in the CPU, have large operands and are in a hurry or in a very tight loop, the speed difference probably doesn’t matter much.
Best regards
Thomas