Migrating from functorch to torch.func
The following APIs are a drop-in replacement for the following
functorch APIs.
They are fully backwards compatible.
Furthermore, if you are using torch.autograd.functional APIs, please try out
the torch.func equivalents instead. torch.func function
transforms are more composable and more performant in many cases.
(
3
,
3
)
fmodel
,
params
=
functorch
.
make_functional
(
model
)
def
compute_loss
(
params
,
inputs
,
targets
):
prediction
=
fmodel
(
params
,
inputs
)
return
torch
.
nn
.
functional
.
mse_loss
(
prediction
,
targets
)
grads
=
functorch
.
grad
(
compute_loss
)(
params
,
inputs
,
targets
)
import
torch
inputs
=
torch
.
randn
(
64
,
3
)
targets
=
torch
.
randn
(
64
,
3
)
model
=
torch
.
nn
.
Linear
(
3
,
3
)
params
=
dict
(
model
.
named_parameters
())
def
compute_loss
(
params
,
inputs
,
targets
):
prediction
=
torch
.
func
.
functional_call
(
model
,
params
,
(
inputs
,))
return
torch
.
nn
.
functional
.
mse_loss
(
prediction
,
targets
)
grads
=
torch
.
func
.
grad
(
compute_loss
)(
params
,
inputs
,
targets
)
.
make_functional
(
model
)
jacobians
=
functorch
.
jacrev
(
fmodel
)(
params
,
inputs
)
import
torch
from
torch.func
import
jacrev
,
functional_call
inputs
=
torch
.
randn
(
64
,
3
)
model
=
torch
.
nn
.
Linear
(
3
,
3
)
params
=
dict
(
model
.
named_parameters
())
jacobians
=
jacrev
(
functional_call
,
argnums
=
1
)(
model
,
params
,
(
inputs
,))
import torch
num_models = 5
batch_size = 64
in_features, out_features = 3, 3
models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
data = torch.randn(batch_size, 3)
import functorch
fmodel, params, buffers = functorch.combine_state_for_ensemble(models)
output = functorch.vmap(fmodel, (0, 0, None))(params, buffers, data)
assert output.shape == (num_models, batch_size, out_features)
import copy
base_model = copy.deepcopy(models[0])
base_model.to('meta')
params, buffers = torch.func.stack_module_state(models)
def call_single_model(params, buffers, data):
return torch.func.functional_call(base_model, (params, buffers), (data,))
output = torch.vmap(call_single_model, (0, 0, None))(params, buffers, data)
assert output.shape == (num_models, batch_size, out_features)