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 update()

How / caveats

jax.jit

Supported

Inlined before the analysis, so jit boundaries are transparent.

jax.lax.cond

Supported

An ETP-relevant cond is if-converted: all branches execute every step and select_n picks the result. Values and exact gradients are unchanged. A dead branch with a NaN/Inf local Jacobian (e.g. a cond guarding a sqrt domain) contaminates reverse-mode gradients. Keep such conds opaque with ControlFlowPolicy(cond='opaque'), or guard the operand inside the branch. Conds with effects, or with a while/scan in a branch, are not converted (COND_CONVERSION_SKIPPED).

jax.lax.scan / brainstate.transform.for_loop (static length)

Supported

Scans up to scan_unroll_limit (default 16) iterations are unrolled. Longer ones are descended (scan_descent='auto', D-RTRL family): their bodies are analyzed in place. Reverse scans, nested control flow in the body, and weights scanned over as xs block descent.

jax.lax.while_loop without a trainable weight

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 CONTROL_FLOW_OPAQUE_FWD warning records each detach. vjp_method='multi-step' raises, as does a loop that reaches no hidden state (one used only on the readout): JAX cannot reverse-differentiate a while.

jax.lax.while_loop using a trainable weight

Not supported

NotImplementedError (WEIGHT_IN_WHILE): a data-dependent trip count admits no fixed per-iteration decomposition. Apply the weight outside the loop, or use a fixed-length scan / for_loop.

jax.vmap

Supported for ETP ops

vmap over an unbatched matmul / lora_matmul / sparse_matmul re-binds the batched ETP primitive. Where promotion is impossible (batched weights, etp_conv, nested vmap), the op decomposes with a UserWarning.

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

The “Weight -> Weight -> Hidden” Invariant#

ETP rules are local to a single primitive: each primitive’s xy_to_dw rule assumes its x is externally-supplied data, and its dt_to_t rule assumes the path from this primitive’s output y to a hidden state h contains no other trainable ETP weights. If a primitive W1’s output flows through another non-gradient-enabled ETP primitive W2 before reaching h, the per-primitive rules cannot soundly account for W1 – that would either double-count the contribution from W2 or treat W2’s x as raw data when it is actually a function of W1.

The compiler enforces this by excluding W1 from the relation list whenever its only path to h passes through another non-gradient-enabled ETP primitive. The diagnostic kind is RELATION_EXCLUDED_WEIGHT_TO_WEIGHT and a UserWarning is emitted at compile time. The excluded weight is still trainable – but only via BPTT, not via online learning.

The classic example is braintrace.nn.GRUCell. It has three internal Linear layers (Wz, Wr, Wh), but the compiler records only two ETP relations:

  • Wz – output flows directly into the new hidden state. Included.

  • Wh – output flows directly into the new hidden state. Included.

  • Wr – output is consumed by Wh’s matmul (it gates r * old_h). Excluded with a RELATION_EXCLUDED_WEIGHT_TO_WEIGHT warning.

This is correct: Wr’s contribution to dL/dh is already implicit in Wh’s gradient (because Wh’s input depends on Wr), so adding Wr separately would double-count. To learn Wr online with this architecture, you would need to bundle Wr and Wh together – something per-primitive ETP cannot express.

When to use gradient_enabled=True#

The single exception is etp_elemwise_p – the only built-in primitive registered with gradient_enabled=True. Element-wise ops (gating biases, learnable thresholds, learnable time constants) are identity-like enough that they may sit on the tail of the y -> h walk without breaking the per-primitive assumption: an upstream ETP weight whose output passes through an element-wise op is still recorded as a relation.

When registering a custom primitive, leave gradient_enabled at its default False. Set it to True only if your primitive is genuinely identity-like (single weight, no input multiplication, the xy_to_dw rule is essentially a passthrough). Setting gradient_enabled=True on a trainable op – one with both an x and a w – silently re-enables the unsound double-counting and will produce wrong gradients.

# Concrete demonstration: GRUCell yields 2 ETP relations, not 3.
import jax.numpy as jnp
import brainstate
import braintrace

cell = braintrace.nn.GRUCell(in_size=4, out_size=8)
brainstate.nn.init_all_states(cell, batch_size=2)

graph = braintrace.compile_etrace_graph(cell, jnp.zeros((2, 4)))

print(f"GRUCell has {len(list(cell.states(brainstate.ParamState)))} ParamStates")
print(f"but the compiler recorded only {len(graph.hidden_param_op_relations)} ETP relations:")
for r in graph.hidden_param_op_relations:
    # ``trainable_paths`` maps each trainable key (e.g. 'weight', 'bias') to the
    # owning ParamState path; print the owning path(s) for this relation.
    print(f"  - {r.trainable_paths}  (primitive: {r.primitive.name})")

# The third weight (Wr) shows up as a RELATION_EXCLUDED_WEIGHT_TO_WEIGHT diagnostic.
from braintrace import DiagnosticKind
excluded = [
    d for d in graph.diagnostics
    if d.kind == DiagnosticKind.RELATION_EXCLUDED_WEIGHT_TO_WEIGHT
]
print(f"\nWeight->weight exclusions: {len(excluded)}")
for d in excluded:
    print(f"  - {d.weight_path}: {d.message}")
GRUCell has 3 ParamStates
but the compiler recorded only 2 ETP relations:
  - {'weight': ('Wz', 'weight'), 'bias': ('Wz', 'weight')}  (primitive: etp_mm)
  - {'weight': ('Wh', 'weight'), 'bias': ('Wh', 'weight')}  (primitive: etp_mm)

Weight->weight exclusions: 1
  - ('Wr', 'weight'): ETP primitive etp_mm (weight=('Wr', 'weight')) reaches a hidden state only through another trainable ETP primitive (etp_mm). Per the non-parametric-tail invariant this weight is excluded from ETP; learn it by BPTT or rewire the architecture so its output flows directly into a hidden state.
/home/chaoming/miniconda3/lib/python3.13/site-packages/braintrace/_compiler/hid_param_op.py:853: UserWarning: ETP primitive etp_mm (weight=('Wr', 'weight')) reaches a hidden state only through another trainable ETP primitive (etp_mm). Per the non-parametric-tail invariant this weight is excluded from ETP; learn it by BPTT or rewire the architecture so its output flows directly into a hidden state.
  _emit_no_relation_diag(

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

Outputs That Bypass New Hidden States#

Under the default vjp_method='single-step', a parameter’s online gradient is assembled from the eligibility trace, dL/dh^t · e^t. A step output can also be computed from a value that is not a new hidden state: a spike read from the pre-reset membrane potential, a readout weight applied inside the step, or the stacked ys of a descended scan. The compiler finds such bypass paths and adds their exact same-step credit:

  • the parameters’ own gradient along the bypass (bypass_param_paths), and

  • the learning signal dL^t/dh^{t-1} of a previous hidden value read along the bypass, paired with the previous trace e^{t-1} (bypass_hidden_paths).

An INFO diagnostic OUTPUT_BYPASSES_HIDDEN names them. Below, the LIF output is read before the reset, and D-RTRL matches BPTT.

A bypass path that crosses a while_loop or an equation with effects cannot be differentiated in reverse mode. That part is dropped with a WARNING (OUTPUT_BYPASS_DROPPED). learning_signal='modulatory' replaces dL/dh entirely and does not add the bypass terms.

import jax
import jax.numpy as jnp
import brainstate
import braintools
import braintrace

sg = braintools.surrogate.Sigmoid()


class LIF(brainstate.nn.Module):
    def __init__(self):
        super().__init__()
        self.w = brainstate.ParamState(brainstate.random.randn(3, 4))

    def init_state(self, *args, **kwargs):
        self.V = brainstate.HiddenState(jnp.zeros(4))

    def update(self, x):
        V_pre = 0.9 * self.V.value + braintrace.matmul(x, self.w.value)
        spk = sg(V_pre - 1.0)
        self.V.value = V_pre - jax.lax.stop_gradient(spk)  # reset
        return spk                                          # read before the reset


def loss_fn(y, t):
    return jnp.mean((y - t) ** 2)


brainstate.random.seed(42)
xs = brainstate.random.rand(10, 3) * 2.0
ys = jnp.full((10, 4), 0.3)

brainstate.random.seed(0)
net = LIF()
brainstate.nn.init_all_states(net)
learner = braintrace.compile(net, braintrace.D_RTRL, xs[0])
print('bypass parameters   :', list(learner.graph.hidden_perturb.bypass_param_paths))
print('bypass hidden states:', list(learner.graph.hidden_perturb.bypass_hidden_paths))
g_online = learner.etrace_grad(xs, ys, step_fn=lambda x, y: loss_fn(learner(x), y))

brainstate.random.seed(0)
net = LIF()
brainstate.nn.init_all_states(net)
g_bptt = brainstate.transform.grad(
    lambda: brainstate.transform.for_loop(lambda x, y: loss_fn(net(x), y), xs, ys).mean(),
    grad_states={'w': net.w},
)()
print(f"D_RTRL |grad w| = {float(jnp.abs(g_online[('w',)]).sum()):.6f}")
print(f"BPTT   |grad w| = {float(jnp.abs(g_bptt['w']).sum()):.6f}")
bypass parameters   : [('w',)]
bypass hidden states: [('V',)]
D_RTRL |grad w| = 1.079097
BPTT   |grad w| = 1.079097

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

D_RTRL

O(B * weight_size * hidden_size)

O(B * |theta| * H)

Full eligibility traces

ES_D_RTRL

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 parameters

  • Consider using braintrace.lora_matmul for low-rank weight updates

Compilation Time#

The braintrace compiler performs several steps when compiling a model for online learning:

  1. Jaxpr tracing: JAX traces the model’s update() method to produce a Jaxpr

  2. Relation discovery: The compiler walks the Jaxpr to find ETP primitives, trace weight origins, and connect them to hidden states

  3. 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.compile should 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.divide

  • Element-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.softmax

  • jax.nn.silu, jax.nn.gelu, jax.nn.leaky_relu

Shape manipulation:

  • jnp.reshape, jnp.transpose, jnp.concatenate

  • jnp.expand_dims, jnp.squeeze

Selection and masking:

  • jax.lax.select(predicate, on_true, on_false) (preferred over jnp.where inside update(); 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 tracking

  • braintrace.element_wise – element-wise parameter operations with ETP tracking

  • braintrace.conv – convolution with ETP tracking

  • braintrace.sparse_matmul – sparse matrix multiplication with ETP tracking

  • braintrace.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:

  1. Control flow inside update(): avoid only a trainable weight inside a while_loop body. jit is inlined, cond is if-converted, and static-length scans are unrolled or descended. A weight-free while_loop is an opaque forward node (single-step VJP; no same-step credit through the loop).

  2. Mind dead branches. If-converted conds and jax.lax.select / jnp.where evaluate every branch. Guard operands so that a dead branch cannot produce NaN/Inf gradients, or keep such a cond opaque.

  3. 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.

  4. 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_WEIGHT warning – it must be learned via BPTT or the architecture must be rewired. etp_elemwise_p (the only gradient_enabled=True built-in) is the sole exception.

  5. Do not write a ParamState inside the step. Update trained weights outside the step from the etrace_grad gradients; hold locally-updated (plastic) weights in a non-param state such as brainstate.LongTermState.

  6. 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 a while_loop, which is dropped with a warning.

  7. Choose the right algorithm based on memory/accuracy tradeoffs. Use D_RTRL for exact gradients with moderate model sizes, and ES_D_RTRL for memory-efficient approximate gradients with larger models.

  8. Call braintrace.compile once before training, not inside the training loop. The compiled graph is cached and reused for inputs of the same shape.

  9. 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.