brainstate.transform.eval_shape#
- brainstate.transform.eval_shape(f, *args, return_state_shapes=False, **kwargs)[source]#
Compute the abstract output shape of
fwithout executing it.This is the brainstate-aware analogue of
jax.eval_shape(). It tracesfabstractly (no real computation, no array allocation, no mutation of anyStatevalue) and returns the shape/dtype structure of the output. It is built onStatefulFunction, exactly likejit(),grad(), andvmap(), so it handles existing global states the same way every other transform does.Three behaviors are supported by a single abstract trace:
Plain outputs. If
freturns arrays/pytrees, the result is a pytree withjax.ShapeDtypeStructleaves.Existing states. If
freads or writes pre-existing globalStateobjects, they are traced transparently (no error). Their concrete values are left unchanged after the call.New nodes. If
fconstructs and returns a brainstateNode(e.g.lambda: brainstate.nn.LSTMCell(3, 4)), a node of the same type is reconstructed with abstractjax.ShapeDtypeStructleaves (lazy/abstract model construction, no memory allocated). The returned node is a first-class input to subsequent brainstate transformations.
- Parameters:
f (
Callable[...,TypeVar(A)]) – The function to abstractly evaluate. It is never executed for real.*args (
Any) – Example positional arguments. May contain arrays, pytrees, or brainstate graph nodes.return_state_shapes (
bool) – IfTrue, return(state_shapes, out_shapes)wherestate_shapesis adictmapping each touchedStateto thejax.ShapeDtypeStructof its value. Default isFalse(return only the output shapes).**kwargs (
Any) – Example keyword arguments.
- Return type:
TypeVar(A)- Returns:
out_shapes (Any) – The abstract output of
f(pytree ofjax.ShapeDtypeStruct, or a reconstructed abstractNode). Whenreturn_state_shapes=Truethis is the second element of the returned(state_shapes, out_shapes)tuple.state_shapes (dict) – Only when
return_state_shapes=True:dictofState -> jax.ShapeDtypeStructfor every state touched byf. Returned as the first element of the(state_shapes, out_shapes)tuple.
Examples
>>> import brainstate >>> import jax.numpy as jnp >>> out = brainstate.transform.eval_shape(lambda x: x * 2.0, jnp.ones(3)) >>> out.shape, out.dtype ((3,), dtype('float32')) >>> model = brainstate.transform.eval_shape(lambda: brainstate.nn.LSTMCell(3, 4)) >>> isinstance(model, brainstate.nn.LSTMCell) True