We wrote the Codecademy Docs entry for PyTorch’s .take_along_dim(). Codecademy Docs is an open-source reference that anyone can contribute to, and this page is a short introduction to the function, with the full entry on Codecademy.
What it does
torch.take_along_dim(input, indices, dim) picks values out of a tensor. For every position in indices, it looks along the dimension dim of input and takes the value at that index. The result has the same number of dimensions as the input, so each row keeps its own values.
import torch
input_tensor = torch.tensor([[10, 20, 30],
[40, 50, 60]])
indices = torch.tensor([[2, 1, 0],
[1, 0, 2]])
result = torch.take_along_dim(input_tensor, indices, dim=1)
print(result)
# tensor([[30, 20, 10],
# [50, 40, 60]])
The first row reads its values in the order 2, 1, 0; the second in the order 1, 0, 2.
Where it helps
It is most useful straight after a function that returns indices, such as torch.argsort() or torch.topk(): those tell you where the values you want are, and .take_along_dim() collects them.
scores = torch.tensor([[10, 30, 20],
[5, 15, 25]])
order = torch.argsort(scores, dim=1, descending=True)
torch.take_along_dim(scores, order, dim=1)
# tensor([[30, 20, 10],
# [25, 15, 5]])
Things to know
indicesmust have the same number of dimensions asinput.- If you leave out
dim, both tensors are flattened first and the result is one-dimensional, liketorch.take(). - Gradients flow through the selected values, so it can be used inside a model while it trains.