torch.map is a structured control flow operator that applies a function over the leading dimension of
input tensors. It can logically be seen as implemented as follows:
defmap(f:Callable[[PyTree,...],PyTree],xs:Union[
PyTree
,
torch
.
Tensor
],
*
args
,
):
out
=
[]
for
idx
in
range
(
xs
.
size
(
0
)):
xs_sliced
=
xs
.
select
(
0
,
idx
)
out
.
append
(
f
(
xs_sliced
,
*
args
))
return
torch
.
stack
(
out
)
Examples
Below is an example that uses map to apply a function over a batch:
import torch
from torch._higher_order_ops importmapdeff(x):return x.sin()+ x.cos()
xs = torch.randn(3,4,5)# batch of 3 tensors, each 4x5# Applies f to each of the 3 slices
result =map(f, xs)# returns tensor of shape [3, 4, 5]print(result)
We can export the model with map for further transformations and deployment.
This example uses dynamic shapes to allow variable batch size:
classMapModule(torch.nn.Module):def__init__(self):super().__init__()defforward(self, xs: torch.Tensor)-> torch.Tensor:defbody_fn(x):return x.sin()+ x
Notice that torch.map is lowered to torch.ops.higher_order.map_impl, and the body function becomes a
sub-graph attribute of the top-level graph module.
Restrictions
Mapped xs can only consist of tensors.
Leading dimensions of all tensors in xs must be consistent and non-zero.
The body function must not mutate inputs.
API Reference
torch._higher_order_ops.map.map(f, xs, *args)
Performs a map of f with xs. Intuitively, you can think of the semantic being:
f (Callable) – a callable that takes an input x, that could either be a single Tensor
or a nested dict, list of tensors and some additional inputs
xs (Any | Tensor) – the inputs that’re to be mapped over. We’ll iterate over the first dim of each x
and perform f on each slice.
*args (TypeVarTuple) – additional arguments provided to each step of f. They could also be omitted and
map is able to automatically figure out the read dependency.