Limitations & Workarounds#
Introduction#
braintrace analyzes the model’s Jaxpr (JAX’s intermediate representation) at compile time to automatically derive eligibility trace update rules. This compilation process walks through the traced computation graph to identify the relationships between hidden states, parameters, and the operations that connect them.
Some JAX operations create sub-Jaxprs: separate, nested computation graphs (the branches of a cond, the body of a scan or while_loop). Before the analysis, the compiler canonicalizes most of them into a flat graph. User jax.jit bodies are inlined, ETP-relevant conds are if-converted, and static-length scans are unrolled or descended. A few patterns remain that the compiler cannot express as an online learning rule.
Understanding these limitations helps you design models that are fully compatible with braintrace’s online learning compilation. This tutorial covers the known limitations and provides practical workarounds for each.
Control Flow Inside the Model#
How each JAX control-flow primitive is handled inside the model’s update() method (the knobs live on braintrace.ControlFlowPolicy):
Primitive |
Inside |
How / caveats |
|---|---|---|
|
Supported |
Inlined before the analysis, so |
|
Supported |
An ETP-relevant |
|
Supported |
Scans up to |
|
Supported (single-step VJP) |
Kept as an opaque forward node: its hidden-to-hidden Jacobian is taken in forward mode. Its inputs are detached in the perturbed step whenever its result reaches a hidden state, directly or through further operations. Consequence: a parameter whose only same-step path to the loss crosses the loop (e.g. an upstream layer feeding it) gets a zero learning signal, and a |
|
Not supported |
|
|
Supported for ETP ops |
|
Important note: All of these can be used freely outside the model’s update() method. For example, using jax.lax.scan to unroll the model over time steps is perfectly fine: the analysis only concerns the traced computation of one step.
Example of Unsupported Code#
The following model applies its weight inside a while_loop body. The compiler rejects it, because a loop with a data-dependent trip count has no fixed per-iteration Jacobian to build an eligibility trace from. Moving the weight application out of the loop makes the loop weight-free, which is supported.
import jax
import jax.numpy as jnp
import brainstate
import braintrace
class SettleRNN(brainstate.nn.Module):
def __init__(self, weight_inside_loop):
super().__init__()
self.weight_inside_loop = weight_inside_loop
self.w = brainstate.ParamState(0.1 * jnp.ones((10, 10)))
self.h = brainstate.HiddenState(jnp.zeros(10))
def update(self, x):
n_iter = lambda c: c[0] < 3
if self.weight_inside_loop:
# BAD: the weight is used inside the while body
body = lambda c: (c[0] + 1, jnp.tanh(braintrace.matmul(c[1], self.w.value) + x))
else:
# GOOD: apply the weight once, the loop consumes only its result
I = braintrace.matmul(self.h.value, self.w.value) + x
body = lambda c: (c[0] + 1, 0.5 * c[1] + 0.5 * jnp.tanh(I))
self.h.value = jax.lax.while_loop(n_iter, body, (0, self.h.value))[1]
return self.h.value
for inside in [True, False]:
try:
braintrace.compile(SettleRNN(inside), braintrace.D_RTRL, jnp.zeros(10))
print(f"weight inside loop={inside}: compiled")
except NotImplementedError as e:
print(f"weight inside loop={inside}: NotImplementedError: {str(e).splitlines()[0][:120]}...")
weight inside loop=True: NotImplementedError: Weight state used inside a while loop; while bodies cannot participate in online learning (a data-dependent trip count a...
weight inside loop=False: compiled
The weight-free variant compiles with a CONTROL_FLOW_OPAQUE_FWD warning. The loop’s inputs are detached in the perturbed step, so its own hidden state keeps an exact learning signal, while same-step credit through the loop is zero (see the table above).
Branch-Free Conditional Logic#
cond is if-converted automatically, so these patterns are optional. Writing branch-free code directly makes the “both branches execute” semantics explicit, and is the fix when a dead branch would produce NaN/Inf gradients.
Strategy 1: jax.lax.select#
jax.lax.select(predicate, on_true, on_false) is the lowest-level branch-free selection operator. It compiles directly to the select_n primitive – no jit, no cond, no sub-Jaxpr. Use it whenever the body of update() needs to pick between two precomputed values.
jnp.where works as well: its internal jit is inlined before the analysis.
# Branch-free selection with jax.lax.select (a single select_n primitive).
class GoodModel(brainstate.nn.Module):
def __init__(self):
super().__init__()
self.w = brainstate.ParamState(jnp.ones((10, 10)))
self.h = brainstate.HiddenState(jnp.zeros(10))
def update(self, x):
new_h = jax.nn.tanh(braintrace.matmul(self.h.value, self.w.value) + x)
# jax.lax.select compiles to a single select_n primitive -- the
# compiler can trace right through it.
self.h.value = jax.lax.select(jnp.sum(x) > 0, new_h, self.h.value)
return self.h.value
model = GoodModel()
algo = braintrace.compile(model, braintrace.D_RTRL, jnp.zeros(10), batch_size=1)
print("Compilation successful.")
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
Compilation successful.
Strategy 2: Multiplication by a mask#
For gating-style conditional logic, you can multiply by a binary mask instead of branching. This is particularly natural for spiking neural networks where spike masks are already available.
# Instead of: jax.lax.cond(spike, lambda: reset_value, lambda: current_value)
# Use: current_value * (1 - spike) + reset_value * spike
Shape Compatibility Requirements#
The braintrace compiler requires that the output of an ETP primitive (e.g., braintrace.matmul) be shape-compatible with the target hidden state. “Compatible” means the shapes must match exactly or be broadcastable to each other.
The compiler checks this during relation construction: after identifying an ETP primitive and its associated weight, it traces forward through the Jaxpr to find reachable hidden-state output variables and filters by shape compatibility.
If the output of an ETP primitive passes through a shape-changing operation (such as slicing, indexing, or reshaping to an incompatible shape) before reaching the hidden state, the compiler will not be able to establish the connection.
# Shape mismatch example -- the weight won't be connected to the hidden state
class ShapeMismatch(brainstate.nn.Module):
def __init__(self):
super().__init__()
self.w = brainstate.ParamState(jnp.ones((10, 20))) # outputs dim 20
self.h = brainstate.HiddenState(jnp.zeros(10)) # hidden dim 10
def update(self, x):
# The output shape (20,) doesn't match hidden shape (10,)
# This weight won't be connected to the hidden state
y = braintrace.matmul(x, self.w.value)
self.h.value = y[:10] # slicing breaks the connection
return self.h.value
In this example, braintrace.matmul(x, self.w.value) produces a vector of dimension 20, but the hidden state self.h has dimension 10. The slicing operation y[:10] is not a simple broadcast – it fundamentally changes the shape, breaking the connection between the weight and the hidden state in the compiled graph.
Fix: Ensure that the weight matrix dimensions produce outputs that match the hidden state dimensions directly:
self.w = brainstate.ParamState(jnp.ones((10, 10))) # outputs dim 10 to match hidden dim 10
Parameters Are Constant Within a Step#
The eligibility-trace recursion assumes that every parameter keeps its value for the whole step. braintrace.compile therefore raises NotSupportedError when the traced step writes any ParamState. This covers parameters that are not trained online too, e.g. a weight updated by a local plasticity rule. The error names each written state by its path.
There are two supported patterns:
Trained weights are updated outside the step, from the gradients returned by
etrace_grad(an optimizer step).Locally-updated weights (Hebbian / STDP-style rules) are held in a non-param state such as
brainstate.LongTermState. They then compile, but are not trained online.
import jax.numpy as jnp
import brainstate
import braintrace
class PlasticNet(brainstate.nn.Module):
def __init__(self, plastic_cls):
super().__init__()
self.w = brainstate.ParamState(brainstate.random.randn(3, 4)) # trained online
self.w_local = plastic_cls(jnp.ones((3, 4))) # updated by a local rule
def init_state(self, *args, **kwargs):
self.V = brainstate.HiddenState(jnp.zeros(4))
def update(self, x):
self.V.value = 0.9 * self.V.value + braintrace.matmul(x, self.w.value) + x @ self.w_local.value
self.w_local.value = self.w_local.value + 1e-3 * jnp.outer(x, self.V.value) # Hebbian
return self.V.value
for cls in [brainstate.ParamState, brainstate.LongTermState]:
try:
braintrace.compile(PlasticNet(cls), braintrace.D_RTRL, jnp.ones(3))
print(f"w_local as {cls.__name__}: compiled")
except braintrace.NotSupportedError as e:
print(f"w_local as {cls.__name__}: NotSupportedError: {e}\n")
w_local as ParamState: NotSupportedError: ParamState ('w_local',) is written inside the online step. braintrace requires parameters to be constant within a step (the eligibility-trace recursion assumes it), whether or not they are trained online. Update trained weights outside the step, from the gradients returned by `etrace_grad` (e.g. with an optimizer), or hold a locally-updated weight (e.g. a plasticity rule) in a non-param state such as `brainstate.LongTermState`; it is then not trained online.
w_local as LongTermState: compiled
Performance Considerations#
Different online learning algorithms in braintrace have different memory and computational requirements. Choosing the right algorithm is important for scaling to larger models.
Memory complexity comparison#
Algorithm |
Memory per weight |
Total memory |
Description |
|---|---|---|---|
|
O(B * weight_size * hidden_size) |
O(B * |theta| * H) |
Full eligibility traces |
|
O(B * (in_size + out_size) * hidden_size) |
O(B * (I+O) * H) |
Factored eligibility traces |
BPTT |
O(T * model_size) |
O(T * N) |
Stores all activations over time |
Where B = batch size, H = hidden state dimension, T = sequence length, N = total model size, I = input size, O = output size.
Key tradeoffs#
D_RTRL provides exact online gradients but can be memory-intensive for large weight matrices. The eligibility trace for each weight matrix has shape
(weight_size, hidden_size), which grows quadratically with model size.ES_D_RTRL (factored / IO-dimension algorithm) trades gradient accuracy for memory efficiency. Instead of storing the full eligibility trace, it factors the trace into input-dimension and output-dimension components, reducing memory from O(weight_size * hidden_size) to O((in_size + out_size) * hidden_size).
BPTT (Backpropagation Through Time) stores all intermediate activations over the unrolled time steps. Memory grows linearly with sequence length T, which can be prohibitive for long sequences.
Recommendations for large models#
Use ES_D_RTRL instead of D_RTRL when weight matrices are large
Reduce hidden state dimensions where possible
Use sparse operations (
braintrace.sparse_matmul) to reduce the number of parametersConsider using
braintrace.lora_matmulfor low-rank weight updates
Compilation Time#
The braintrace compiler performs several steps when compiling a model for online learning:
Jaxpr tracing: JAX traces the model’s
update()method to produce a JaxprRelation discovery: The compiler walks the Jaxpr to find ETP primitives, trace weight origins, and connect them to hidden states
Graph construction: The eligibility trace computation graph is built from the discovered relations
braintrace.compile(model, algo, x0, batch_size=B) runs all these steps and returns a ready learner. This compilation can be slow for complex models, especially on the first call. However:
Subsequent calls with the same input shapes reuse the compiled graph. The compilation result is cached, so you only pay the cost once.
braintrace.compileshould be called once before the training loop, not inside it. Calling it repeatedly with the same shapes is harmless (it detects the cache hit), but calling it inside a loop adds unnecessary overhead.
# Good: compile once, then run many steps
learner = braintrace.compile(model, braintrace.D_RTRL, example_input, batch_size=B)
for step in range(num_steps):
output = learner(input_data[step]) # uses cached compilation
What CAN Be Used Inside update()#
The braintrace compiler works with all standard JAX mathematical operations that do not create sub-Jaxprs. These include:
Standard math operations:
jnp.add,jnp.subtract,jnp.multiply,jnp.divideElement-wise operators:
+,-,*,/
Matrix operations:
@(matrix multiply operator)jnp.dot,jnp.matmul,jnp.einsum
Activation functions:
jax.nn.tanh,jax.nn.relu,jax.nn.sigmoid,jax.nn.softmaxjax.nn.silu,jax.nn.gelu,jax.nn.leaky_relu
Shape manipulation:
jnp.reshape,jnp.transpose,jnp.concatenatejnp.expand_dims,jnp.squeeze
Selection and masking:
jax.lax.select(predicate, on_true, on_false)(preferred overjnp.whereinsideupdate(); see Workarounds above)jnp.clip,jnp.maximum,jnp.minimum
Gradient control:
jax.lax.stop_gradient– useful for detaching parts of the computation
braintrace ETP primitives:
braintrace.matmul– matrix multiplication with ETP trackingbraintrace.element_wise– element-wise parameter operations with ETP trackingbraintrace.conv– convolution with ETP trackingbraintrace.sparse_matmul– sparse matrix multiplication with ETP trackingbraintrace.lora_matmul– LoRA-style low-rank multiplication with ETP tracking
In general, if a JAX operation compiles to a flat sequence of primitives in the Jaxpr (no nested sub-Jaxprs), it is compatible with braintrace.
Summary#
The key limitations and their workarounds are:
Control flow inside
update(): avoid only a trainable weight inside awhile_loopbody.jitis inlined,condis if-converted, and static-lengthscans are unrolled or descended. A weight-freewhile_loopis an opaque forward node (single-step VJP; no same-step credit through the loop).Mind dead branches. If-converted
conds andjax.lax.select/jnp.whereevaluate every branch. Guard operands so that a dead branch cannot produce NaN/Inf gradients, or keep such acondopaque.Ensure shape compatibility between ETP primitive outputs and hidden states. The compiler filters connections by shape – if shapes don’t match or broadcast, the connection won’t be established.
Per-primitive ETP rules are local. A weight whose only path to a hidden state passes through another trainable ETP primitive is excluded with a
RELATION_EXCLUDED_WEIGHT_TO_WEIGHTwarning – it must be learned via BPTT or the architecture must be rewired.etp_elemwise_p(the onlygradient_enabled=Truebuilt-in) is the sole exception.Do not write a
ParamStateinside the step. Update trained weights outside the step from theetrace_gradgradients; hold locally-updated (plastic) weights in a non-param state such asbrainstate.LongTermState.Outputs may bypass new hidden states. Under the single-step VJP, their exact same-step credit is added automatically (
OUTPUT_BYPASSES_HIDDEN). The exception is a bypass that crosses awhile_loop, which is dropped with a warning.Choose the right algorithm based on memory/accuracy tradeoffs. Use
D_RTRLfor exact gradients with moderate model sizes, andES_D_RTRLfor memory-efficient approximate gradients with larger models.Call
braintrace.compileonce before training, not inside the training loop. The compiled graph is cached and reused for inputs of the same shape.The compiler works with all standard JAX mathematical operations. As long as you avoid the unsupported control flow primitives listed above, your model will compile successfully.