Undo a length sort with the inverse permutation from argsort
Why it matters Length-sorted batching is used in training and serving, and every sorted batch must be unsorted before results go back to users.
Inference servers sort a batch by length to reduce padding, run the model, then must put outputs back in the order the requests came in. The tool for that is the inverse permutation.
Write restore_order(x_sorted, order). order is the int array returned by np.argsort on the original batch (so the sorted batch is original[order]). x_sorted has shape (B,) or (B, ...) and holds outputs in sorted order. Return the outputs in ORIGINAL order, same shape, so that result[order[i]] == x_sorted[i].
def restore_order(x_sorted, order)Example
restore_order([10, 20, 30], [2, 0, 1]) is [20, 30, 10].
Understand the idea
A permutation is a reordering. If order = argsort(lengths), then lengths[order] is sorted: position i of the sorted batch came from position order[i] of the original. To go back you need the inverse permutation inv, which says where each original item went.
Worked example: order = [2, 0, 1]. Sorted item 0 came from original 2, item 1 from original 0, item 2 from original 1. With x_sorted = [10, 20, 30], original position 2 gets 10, position 0 gets 20, position 1 gets 30, so the result is [20, 30, 10]. argsort([2, 0, 1]) = [1, 2, 0], and x_sorted[[1, 2, 0]] = [20, 30, 10].
Rule: inv = argsort(order), original = x_sorted[inv]. Equivalently result[order] = x_sorted.
Dynamic batching in LLM servers and bucketed training loaders use this to return results in request order.
Shapes and data flow
order (B,), x_sorted (B, ...) -> result (B, ...)