| 1 |
--- |
| 2 |
title: Converting |
| 3 |
|
| 4 |
--- |
| 5 |
|
| 6 |
# Converting Between EagerPy and Native Tensors |
| 7 |
|
| 8 |
A native tensor could be a PyTorch GPU or CPU tensor, a TensorFlow tensor, a JAX array, or a NumPy array. |
| 9 |
|
| 10 |
**A native PyTorch tensor:** |
| 11 |
```python |
| 12 |
import torch |
| 13 |
x = torch.tensor([1., 2., 3., 4., 5., 6.]) |
| 14 |
``` |
| 15 |
|
| 16 |
**A native TensorFlow tensor:** |
| 17 |
```python |
| 18 |
import tensorflow as tf |
| 19 |
x = tf.constant([1., 2., 3., 4., 5., 6.]) |
| 20 |
``` |
| 21 |
|
| 22 |
**A native JAX array:** |
| 23 |
```python |
| 24 |
import jax.numpy as np |
| 25 |
x = np.array([1., 2., 3., 4., 5., 6.]) |
| 26 |
``` |
| 27 |
|
| 28 |
**A native NumPy array:** |
| 29 |
```python |
| 30 |
import numpy as np |
| 31 |
x = np.array([1., 2., 3., 4., 5., 6.]) |
| 32 |
``` |
| 33 |
|
| 34 |
No matter which native tensor you have, it can always be turned into the appropriate EagerPy tensor using `ep.astensor`. This will automatically wrap the native tensor with the correct EagerPy tensor class. The original native tensor can always be accessed using the `.raw` attribute. |
| 35 |
|
| 36 |
```python |
| 37 |
# x should be a native tensor (see above) |
| 38 |
# for example: |
| 39 |
import torch |
| 40 |
x = torch.tensor([1., 2., 3., 4., 5., 6.]) |
| 41 |
|
| 42 |
# Any native tensor can easily be turned into an EagerPy tensor |
| 43 |
import eagerpy as ep |
| 44 |
x = ep.astensor(x) |
| 45 |
|
| 46 |
# Now we can perform any EagerPy operation |
| 47 |
x = x.square() |
| 48 |
|
| 49 |
# And convert the EagerPy tensor back into a native tensor |
| 50 |
x = x.raw |
| 51 |
# x will now again be a native tensor (e.g. a PyTorch tensor) |
| 52 |
``` |
| 53 |
|
| 54 |
Especially in functions, it is common to convert all inputs to EagerPy tensors. This could be done using individual calls to `ep.astensor`, but using `ep.astensors` this can be written even more compactly. |
| 55 |
|
| 56 |
```python |
| 57 |
# x, y should be a native tensors (see above) |
| 58 |
# for example: |
| 59 |
import torch |
| 60 |
x = torch.tensor([1., 2., 3.]) |
| 61 |
y = torch.tensor([4., 5., 6.]) |
| 62 |
|
| 63 |
import eagerpy as ep |
| 64 |
x, y = ep.astensors(x, y) # works for any number of inputs |
| 65 |
``` |