equinox icon indicating copy to clipboard operation
equinox copied to clipboard

better handling of statefulness - oryx way of handling state

Open simon-bachhuber opened this issue 4 years ago • 7 comments

Hey,

some of you might know the library oryx. There, the following design pattern is introduced to more easily handle state.

Right now we are doing the following

# model is pure function
state, y = model(state, x)

However, this is one variable less (and IMO really nice).

# model is still a pure function 
model, y = model(x)

# this also works 
model = model.reset()

Turns out we have everything we need to implement this (and i did). This is just a first attempt. Many conventions i introduced could be handled much more elegantly.

There is no magic going on at all (which is nice).

Personally i find this encapsulation of state really useful. Dealing with state explicitly is quite error-prone and annoying. It also allows for a more simplified interface of some objects ("the state doesn't leak / pop up in higher-order functions").

For example:

# this works
def scan_fn(counters, x):
    # i don't really care about the state or the logic how it is updated
    # this is hidden now but we still are not mutating anything
    new_counters, ys = counters()
    return new_counters, ys

These different modules can be created from an eqx.Module using

# state
S = PyTree[Union[jnp.ndarray, eqx.Module, "Module"]]

# parametric function - a `eqx.Module` with this signature
ParametricFunction = Callable[
    [S, PRNGKey, PyTree[jnp.ndarray]], Tuple[S, PRNGKey, PyTree[jnp.ndarray]]
]

# we transform to another `eqx.Module` called `Module` with signature
Module = Callable[
    [Optional[PyTree[jnp.ndarray]]], Tuple["Module", PyTree[jnp.ndarray]]
]

def make_module_from_eqx_module(
    parametric_function: eqx.Module, init_state, init_key
) -> "Module":
    pass 

and such a Module can itself encapsulate arbitrary other Modules - just like with eqx.Module. In the example below we create a Module that encapsulates several other Modules representing counters with varying speeds.

def make_counter(step_size):
    init_state = jnp.array(0)
    init_params = step_size
    init_key = jrand.PRNGKey(1)

    class CountUp(eqx.Module):
        step_size: jnp.ndarray
        def __call__(self, state, key, x):
            del x
            return state + self.step_size, key, state

    return make_module_from_eqx_module(CountUp(init_params), init_state, init_key)


def make_many_counters(number_of_counters: int = 3):
    init_state = [
        make_counter(jnp.array(step_size)) for step_size in range(number_of_counters)
    ]
    init_params = {}
    init_key = jrand.PRNGKey(1)

    def apply_fn(params, state, key, x):
        counters = state
        # write only the outer logic 
        # now counting up
        ys = [counter()[1] for counter in counters]
        new_counters = [counter()[0] for counter in counters]
        return new_counters, key, ys

    return make_module_from_function(apply_fn, init_params, init_state, init_key)

Well, WDYT? Does this make sense?

Full example:

from typing import Callable, Generic, Optional, Tuple, TypeVar, Union

import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jrand
import jax.tree_util as jtu

T = TypeVar("T")
PRNGKey = TypeVar("PRNGKey")


class PyTree(Generic[T]):
    pass


# state
S = PyTree[Union[jnp.ndarray, eqx.Module, "Module"]]
# parametric function - a `eqx.Module` with this signature
ParametricFunction = Callable[
    [S, PRNGKey, PyTree[jnp.ndarray]], Tuple[S, PRNGKey, PyTree[jnp.ndarray]]
]
# we transform to another `eqx.Module` called `Module` with signature
_Module = Callable[
    [Optional[PyTree[jnp.ndarray]]], Tuple["_Module", PyTree[jnp.ndarray]]
]
# this function does the "transform"


def make_module_from_eqx_module(
    parametric_function: eqx.Module, init_state: S, init_key
) -> "Module":
    return _init_module(parametric_function, init_state, init_key)


class Module(eqx.Module):
    parametric_function: eqx.Module
    state: PyTree[Union[jnp.ndarray, eqx.Module, "Module"]]
    key: jnp.ndarray
    init_state: PyTree[Union[jnp.ndarray, eqx.Module, "Module"]]
    init_key: jnp.ndarray

    def __call__(
        self, x: Optional[PyTree[jnp.ndarray]] = None
    ) -> Tuple["Module", PyTree[jnp.ndarray]]:
        state, key, y = self.parametric_function(self.state, self.key, x)
        return self.replace(state, key), y

    def reset(self, reset_key=True):
        def _reset(state_leaf, init_state_leaf):
            if isinstance(state_leaf, Module):
                return state_leaf.reset(reset_key)
            else:
                return init_state_leaf

        state = jtu.tree_map(
            _reset,
            self.state,
            self.init_state,
            is_leaf=lambda leaf: isinstance(leaf, Module),
        )

        if reset_key:
            key = self.init_key
        else:
            key = self.key

        return self.replace(state, key)

    def replace(self, state, key):
        return Module(
            self.parametric_function, state, key, self.init_state, self.init_key
        )


def _init_module(
    parametric_function,
    init_state,
    init_key,
    state=None,
    key=None,
) -> Module:
    if state is None:
        state = init_state
    if key is None:
        key = init_key

    return Module(parametric_function, state, key, replace_module(init_state), init_key)


def replace_module(tree, replace_with=None):
    """Replace every leaf that is a `Module` in tree `tree` by `replace_with`.
    Defaults to `None`."""

    def is_module(leaf):
        if isinstance(leaf, Module):
            return replace_with
        else:
            return leaf

    return jtu.tree_map(is_module, tree, is_leaf=lambda leaf: isinstance(leaf, Module))


def filter_module(tree, include_init_state: bool = False) -> PyTree[bool]:
    """Make a mask of tree where arrays are `True` if they are part of
    `parametric_function` field but not part of `state` field.
    Useful for `eqx.filter_grad(arg=...)`
    """

    def is_module(leaf):

        if isinstance(leaf, Module):
            if include_init_state:
                # modules carry their own initial state
                # this will be captured via `filter_module(leaf.state)`
                # hence replace this state here by `None`
                init_state = replace_module(leaf.init_state)
                init_state = eqx.is_array(init_state)
            else:
                init_state = False
            return Module(
                jtu.tree_map(eqx.is_array, leaf.update_fn),
                filter_module(leaf.state, include_init_state),
                False,
                init_state,
                False,
            )
        else:
            return False

    return jtu.tree_map(is_module, tree, is_leaf=lambda leaf: isinstance(leaf, Module))


def filter_scan(scan_fn, init, xs, length, filter_spec=eqx.is_array):
    init_arrays, init_funcs = eqx.partition(init, filter_spec=filter_spec)

    def _scan_fn(arrays, x):
        carry = eqx.combine(arrays, init_funcs)
        carry, y = scan_fn(carry, x)
        arrays, _ = eqx.partition(carry, filter_spec=filter_spec)
        return arrays, y

    return jax.lax.scan(_scan_fn, init=init_arrays, xs=xs, length=length)


def make_module_from_function(apply_fn, init_params, init_state, init_key) -> Module:
    class parametric_function(eqx.Module):
        params: dict
        apply_fn: Callable

        def __call__(self, state, key, x):
            state, key, y = self.apply_fn(self.params, state, key, x)
            return state, key, y

    return _init_module(
        parametric_function(init_params, apply_fn), init_state, init_key
    )


def make_counter(step_size):
    init_state = jnp.array(0)
    init_params = step_size
    init_key = jrand.PRNGKey(
        1,
    )

    class CountUp(eqx.Module):
        step_size: jnp.ndarray

        def __call__(self, state, key, x):
            del x
            return state + self.step_size, key, state

    return make_module_from_eqx_module(CountUp(init_params), init_state, init_key)


def make_many_counters(number_of_counters: int = 3):
    init_state = [
        make_counter(jnp.array(step_size)) for step_size in range(number_of_counters)
    ]
    init_params = {}
    init_key = jrand.PRNGKey(
        1,
    )

    def apply_fn(params, state, key, x):
        counters = state
        # you don't need to know how exactly the state is updated
        # inside the counter logic
        # but you are still in full control which state is changing
        ys = [counter()[1] for counter in counters]
        new_counters = [counter()[0] for counter in counters]
        return new_counters, key, ys

    return make_module_from_function(apply_fn, init_params, init_state, init_key)


def test_counters():
    counters = make_many_counters()

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(0), jnp.array(0)])

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(1), jnp.array(2)])

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(2), jnp.array(4)])

    # test .reset mechanism
    # this will recursively reset all `Modules` in the PyTree
    # but it will not touch the `parameterized_function`
    # we do not want to reset parameters (usually)
    counters = counters.reset()
    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(0), jnp.array(0)])

    # repeat with jit

    counters = counters.reset()
    counters = eqx.filter_jit(counters)

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(0), jnp.array(0)])

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(1), jnp.array(2)])

    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(2), jnp.array(4)])

    counters = counters.reset()
    counters, y = counters()
    assert eqx.tree_equal(y, [jnp.array(0), jnp.array(0), jnp.array(0)])


def test_filter_scan():
    def scan_fn(counters, x):
        new_counters, ys = counters()
        return new_counters, ys

    counters = make_many_counters()

    _, ys = filter_scan(scan_fn, init=counters, xs=None, length=3)

    assert eqx.tree_equal(ys[0], jnp.array([0, 0, 0]))
    assert eqx.tree_equal(ys[1], jnp.array([0, 1, 2]))
    assert eqx.tree_equal(ys[2], jnp.array([0, 2, 4]))

    # repeat with jit

    counters = counters.reset()

    @eqx.filter_jit
    def unroll(counters):
        _, ys = filter_scan(scan_fn, init=counters, xs=None, length=3)
        return ys

    ys = unroll(counters)

    assert eqx.tree_equal(ys[0], jnp.array([0, 0, 0]))
    assert eqx.tree_equal(ys[1], jnp.array([0, 1, 2]))
    assert eqx.tree_equal(ys[2], jnp.array([0, 2, 4]))


test_counters()
test_filter_scan()

simon-bachhuber avatar Nov 08 '22 16:11 simon-bachhuber

So you've got rather a lot going on there, but if I understand you correctly then the key idea is simply to have a 'stateful' module return an updated version of itself.

I think what you've got can be simplified a bit. Into something like:

import equinox as eqx
import jax
import jax.numpy as jnp
import optax
from jaxtyping import Array, Int'

class Counter(eqx.Module)
    count: Int[Array, ""]

    def __call__(self):
        new_self = eqx.tree_at(lambda s: s.count, self, self.count + 1)
        return new_self

class Norm(eqx.Module):
    mean: Array

    def __call__(self, x):
        mean = jnp.mean(x)
        mean = 0.01 * mean * 0.99 * self.mean
        x = x - mean
        new_self = eqx.tree_at(lambda s: s.mean, self, mean)
        return new_self, x

class MyModel(eqx.Module):
    linear1: eqx.nn.Linear
    linear2: eqx.nn.Linear
    counter: Counter
    norm: Norm

    def __call__(self, x):
        x = self.linear1(x)
        x = jax.nn.relu(x)
        new_norm, x = self.norm(x)
        x = self.linear2(x)
        new_counter = self.counter()
        new_self = eqx.tree_at(lambda s: (s.counter, s.norm), self, (new_counter, new_norm))
        return new_self, x

model = MyModel(...)
optim = optax.adam(...)
opt_state = optim.init(eqx.filter(model, eqx.is_array))

@eqx.filter_grad(has_aux=True)
def compute_loss(model, x, y):
    new_model, pred_y = model(x)
    loss = jnp.mean((y - pred_y) ** 2)
    return loss, new_model

@eqx.filter_jit
def make_step(model, opt_state, x, y):
    grads, model = compute_loss(model, x, y)
    updates, opt_state = optim.update(grads, opt_state)
    model = eqx.apply_updates(model, updates)
    return model, opt_state

for x, y in data:
    model, opt_state = make_step(model, opt_state, x, y)

This is quite a clean idea.

The main/only difficulty is how every downstream user of your class needs to also update themselves appropriately. The statefulness is "infectious". (Arguably it should be, though...)

Now as it turns out, JAX actually has some notion of stateful operations, that should be appearing in the not-distant future. (Have a look at the recent work on algebraic effects, and the as-yet-undocumented for_loop, over in the main JAX repo.) As such, I'm actually inclined to wait until that graduates and becomes public.

But if that weren't the case, then the version you've got it pretty good, and would probably be worth implementing over here. (Although I'm not sure how SpectralNorm would end up working, given that that make a module stateful, even if it wasn't before. Perhaps another good reason to wait until we get officially-supported stateful operations.)

patrick-kidger avatar Nov 11 '22 05:11 patrick-kidger

Thanks for your input!

So you've got rather a lot going on there, but if I understand you correctly then the key idea is simply to have a 'stateful' module return an updated version of itself.

Jep. I think i mostly got tired of carrying around so much state and having to create several "state containers" in the form of NamedTuples just to keep track of what state i am currently dealing with. Of course that state still leaks (= has to be dealt with) by the downstream users (as you called it before) and i think this is okay but at least the state object could contain its own update logic. I think this is what this example (and yours) can achieve.

One problem with this approach is maybe though that you always have to create an entirely new PyTree even though only small parts are being updated.

class Model(eqx.Module):
    state: jnp.ndarray  # large array
    count: jnp.ndarray # small (tiny) array
    def __call__(self):
        # when `__call__` is jit-compiled, have to copy the large array
        return Model(self.state, self.count + 1)

Couple of questions regarding your example:

# Question 1

class Counter(eqx.Module)
    count: Int[Array, ""]

    def __call__(self):
        # this seems cleaner or is there any disadvantage?
        return Counter(self.count + 1)
        # instead of
        new_self = eqx.tree_at(lambda s: s.count, self, self.count + 1)
        return new_self

# Question 2 

# this is a difficult operation. How can i filter out all the state variables
# in a possilbly nested structure of `eqx.Module`s ?
# the best option is to maybe create a new type and use the `is_leaf` logic but not sure 
opt_state = optim.init(eqx.filter(model, eqx.is_array))

Now as it turns out, JAX actually has some notion of stateful operations, that should be appearing in the not-distant future. (Have a look at the recent work on algebraic effects, and the as-yet-undocumented for_loop, over in the main JAX repo.) As such, I'm actually inclined to wait until that graduates and becomes public.

Very good to know and looking forward for that. I think having an official solution / approach of dealing with state with some common convention that everyone uses will go a long way.

simon-bachhuber avatar Nov 16 '22 23:11 simon-bachhuber

Regarding creating a copy: there shouldn't be any copies happening. Can you expand on this?

Answer 1: yep, that's definitely cleaner in this case. When I wrote that I was thinking of the general case:

class Model(eqx.Module):
    counter: ...
    lots: ...
    of: ...
    things: ...

    def __call__(self):
        ...

for which the tree_at solution is shorter than enumerating all the other arguments. (And I failed to spot that I didn't need this generic version here.)

Answer 2: hmm, creating a wrapper type is definitely one way to do this. Something like:

# Define buffers

class Buffer(eqx.Module, Generic[T]):
    value: T

is_buffer = lambda x: isinstance(x, Buffer)

def resolve_leaf(x):
    if is_buffer(x):
        return lax.stop_gradient(x.value)  # stop gradient just in case we forget to filter them out
    else:
        return x

def resolve_buffers(model):
    return jtu.tree_map(resolve_leaf, model, is_leaf=is_buffer)

# Use buffers

class Model(eqx.Module):
    array: Buffer[Float[Array, "channel1 channel2"]]
    ...  # do all the in-place update stuff discussed above

# Training loop

def compute_loss(model_no_buffer, model_buffer, data):
    model = eqx.combine(model_no_buffer, model_buffer)
    model = resolve_buffers(model)
    ...   # calculate a loss and stateful model updates
    return loss, model

@eqx.filter_jit
def make_step(model, opt_state, data):
    model_buffer, model_no_buffer = eqx.partition(model, is_buffer, is_leaf=is_buffer)
    grads, model = eqx.filter_grad(compute_loss, has_aux=True)(model_no_buffer, model_buffer, data)
    ...  # update model and opt_state
    return model, opt_state

opt_state = optim.init(eqx.filter(model, eqx.is_inexact_array, is_leaf=is_buffer))

Although FWIW that is clearly pretty finickity and unpleasant.

patrick-kidger avatar Nov 16 '22 23:11 patrick-kidger

Once improvement might be replace lax.stop_gradient(x.value) with equinox.internal.nondifferentiable(x.value, name="buffer"). This would assert that the user has written their downstream code correctly.

patrick-kidger avatar Nov 16 '22 23:11 patrick-kidger

On the CPU side, it seems like the copying does happen.

class Model(eqx.Module):
    state: jnp.ndarray  # large array
    count: jnp.ndarray # small (tiny) array
    def __call__(self):
        # when `__call__` is jit-compiled, have to copy the large array
        return Model(self.state, self.count + 1)


data = np.arange(100000, dtype=np.float32)

a = Model(state=jnp.asarray(data), count = jnp.array(0))

a_jit = eqx.filter_jit(a)
a_jit()

a1 = a()
a2 = a_jit()
print(np.shares_memory(np.asarray(a.state), data), np.byte_bounds(data)==np.byte_bounds(np.asarray(a.state))) #True True
print(np.shares_memory(np.asarray(a1.state), data), np.byte_bounds(data)==np.byte_bounds(np.asarray(a1.state))) #True True
print(np.shares_memory(np.asarray(a2.state), data), np.byte_bounds(data)==np.byte_bounds(np.asarray(a2.state))) #False False

uuirs avatar Nov 17 '22 04:11 uuirs

Right - what you're showing here is a generic feature of JAX on CPU. (On GPU and TPU, FWIW, take a look at jax.jit(..., donate_argnums=...), which eqx.filter_jit actually still needs an analogue for.)

That is, the outputs of a JIT'd region are in distinct buffers to the inputs. That's nothing to do with Model though, or the statefulness approach proposed here. (E.g. any other statefulness approach would necessarily also have this. As would any normal stateless approach! Since you're presumably passing model.state both in and out of the JIT'd region, during model training.)

patrick-kidger avatar Nov 17 '22 04:11 patrick-kidger

Regarding creating a copy: there shouldn't be any copies happening. Can you expand on this? _Right - what you're showing here is a generic feature of JAX on CPU. _

Jep agreed. This is more something i realized after posting a connected question here. So this is just a limitation given by JAX and can not be so easily overcome.

Although FWIW that is clearly pretty finickity and unpleasant.

Yeah. I am also not really happy with it and it seems to introduce as much complexity (and sorta magical things) as it eliminates. I guess if there is an official solution approaching one shouldn't waste too much time on this. So i will close this for now.

simon-bachhuber avatar Nov 18 '22 16:11 simon-bachhuber