What is JaxNumpy-compatible equivalent to this Python function?

Viewed 207

How do I implement the below in a JAX-compatable way (e.g., using jax.numpy)?

def actions(state: tuple[int, ...]) -> list[tuple[int, ...]]:
    l = []
    iterables = [range(1, i+1) for i in state]
    ns = list(range(len(iterables)))
    for i, iterable in enumerate(iterables):
        for value in iterable:
            action = tuple(value if n == i else 0 for n in ns)
            l.append(action)
    return l

>>> state = (3, 1, 2)
>>> actions(state)
[(1, 0, 0), (2, 0, 0), (3, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 2)]
1 Answers

Jax, like numpy, cannot efficiently operate on Python container types like lists and tuples, so there's not really any JAX-compatible way to create a function with the exact signature you specify above.

But if you're alright with the return value being a two-dimensional array, you could do something like this, based on jnp.vstack:

from typing import Tuple
import jax.numpy as jnp
from jax import jit, partial

@partial(jit, static_argnums=0)
def actions(state: Tuple[int, ...]) -> jnp.ndarray:
  return jnp.vstack([
    jnp.zeros((val, len(state)), int).at[:, i].set(jnp.arange(1, val + 1))
    for i, val in enumerate(state)])
>>> state = (3, 1, 2)
>>> actions(state)
DeviceArray([[1, 0, 0],
             [2, 0, 0],
             [3, 0, 0],
             [0, 1, 0],
             [0, 0, 1],
             [0, 0, 2]], dtype=int32)

Note that because the size of the output array depends on the content of state, state must be a static quantity, so a tuple is a good option for the input.

Related