---
title: Abstractions in JAX
description: I love how effectively JAX exposes low-level behavior while still providing useful abstractions.
author: Dovydas Joksas
url: https://dovydas.com/blog/abstractions-in-jax
html: https://dovydas.com/blog/abstractions-in-jax?format=html
---

August 11, 2022 · 1 min read

# Abstractions in JAX

*Originally posted [on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6963415736346185728)*.

I’m considering making a transition from [TensorFlow](https://www.tensorflow.org/) to [JAX](https://jax.readthedocs.io/) and, so far, am loving how effectively the latter exposes low-level behavior while still providing useful abstractions.

For example, the code snippet[^original-code] below shows how one can perform gradient descent while utilising multiple devices:

1. the gradients are computed on *multiple* devices
2. they are *synced* across multiple devices and averaged
3. the new parameters are computed by adjusting them in a direction opposite to gradient

```python
@functools.partial(jax.pmap, axis_name="num_devices")
def update(params, xs, ys, learning_rate=0.005):
    # 1. Compute the gradients on the given minibatch
    # (individually on each device).
    grads = jax.grad(loss_fn)(params, xs, ys)

    # 2. Combine the gradients across all devices
    # (by taking their mean).
    grads = jax.lax.pmean(grads, axis_name="num_devices")

    # 3. Each device performs its own update, but since we
    # start with the same params and synchronise gradients,
    # the params stay in sync.
    new_params = jax.tree_map(
        lambda param, g: param - g * learning_rate,
        params,
        grads,
    )

    return new_params
```

[^original-code]: adapted from [a tutorial](https://jax.readthedocs.io/en/latest/jax-101/06-parallelism.html) by DeepMind’s Vladimir Mikulik and Roman Ring
