!pip install ivy
Unify code
Unify a simple torch
function and use it alongside any ML framework!
⚠️ If you are running this notebook in Colab, you will have to install Ivy
and some dependencies manually. You can do so by running the cell below ⬇️
If you want to run the notebook locally but don’t have Ivy installed just yet, you can check out the Get Started section of the docs.
Firstly, let’s import the dependencies and define a torch
function.
import ivy
import torch
def normalize(x):
= torch.mean(x)
mean = torch.std(x)
std return torch.div(torch.sub(x, mean), std)
By using ivy.unify()
, you can convert any code from any framework into Ivy code, which as we have already seen, can be executed using any framework as the backend.
Let’s unify the function!
= ivy.unify(normalize, source="torch") normalize
And that’s it! The normalize
function can now be used with any ML framework. It’s as simple as that!
So, let’s give it a try!
# import the frameworks
import numpy as np
import jax.numpy as jnp
import tensorflow as tf
# create random numpy arrays for testing
= np.random.uniform(size=10).astype(np.float32)
x "numpy")
ivy.set_backend(print(normalize(x))
# jax
= jnp.array(x)
x_ "jax")
ivy.set_backend(print(normalize(x_))
# tensorflow
= tf.constant(x)
x_ "tensorflow")
ivy.set_backend(print(normalize(x_))
# torch
= torch.tensor(x)
x_ "torch")
ivy.set_backend(print(normalize(x_))
ivy.array([ 0.82997245, 0.44733784, -0.32163444, -1.93330479, -0.52438271,
-0.20438017, 1.252316 , 0.0827222 , 1.26017165, -0.88881904])
ivy.array([ 0.82997245, 0.44733784, -0.32163444, -1.93330479, -0.52438271,
-0.20438017, 1.252316 , 0.0827222 , 1.26017165, -0.88881904])
ivy.array([ 0.82997245, 0.44733784, -0.32163444, -1.93330479, -0.52438271,
-0.20438017, 1.252316 , 0.0827222 , 1.26017165, -0.88881904])
ivy.array([ 0.82997245, 0.44733784, -0.32163444, -1.93330479, -0.52438271,
-0.20438017, 1.252316 , 0.0827222 , 1.26017165, -0.88881904])
We can see that the new normalize
function can operate with any ML framework. ivy.unify
converts the framework-specific torch
implementation into a framework-agnostic ivy
implementation, which is compatible with all frameworks.
Round Up
That’s it, you can now unify ML code! However, there are several other important topics to master before you’re ready to unify ML code like a pro 🥷. Next, we’ll be learning how to make our unified Ivy code run much more efficiently! ⚡