| 1 |
--- |
| 2 |
title: Automatic Differentiation |
| 3 |
|
| 4 |
--- |
| 5 |
|
| 6 |
# Automatic Differentiation in EagerPy |
| 7 |
|
| 8 |
EagerPy uses a functional approach to automatic differentiation. You first define a function that will then be differentiated with respect to its inputs. This function is then passed to `ep.value_and_grad` to evaluate both the function and its gradient. More generally, you can also use `ep.value_aux_and_grad` if your function has additional auxiliary outputs and `ep.value_and_grad_fn` if you want the gradient function without immediately evaluating it at some point `x`. |
| 9 |
|
| 10 |
Using `ep.value_and_grad` for automatic differentiation in EagerPy: |
| 11 |
|
| 12 |
```python |
| 13 |
import torch |
| 14 |
x = torch.tensor([1., 2., 3.]) |
| 15 |
|
| 16 |
# The following code works for any framework, not just Pytorch! |
| 17 |
|
| 18 |
import eagerpy as ep |
| 19 |
x = ep.astensor(x) |
| 20 |
|
| 21 |
def loss_fn(x): |
| 22 |
# this function takes and returns an EagerPy tensor |
| 23 |
return x.square().sum() |
| 24 |
|
| 25 |
print(loss_fn(x)) |
| 26 |
# PyTorchTensor(tensor(14.)) |
| 27 |
|
| 28 |
print(ep.value_and_grad(loss_fn, x)) |
| 29 |
# (PyTorchTensor(tensor(14.)), PyTorchTensor(tensor([2., 4., 6.]))) |
| 30 |
``` |