TECHNOLOGY

JAX scan carry: keep recurrent state shape and dtype stable across steps

In this article
THE QUICK TAKE

A scan carry has a fixed structure, shape and dtype across iterations; collected outputs belong in the scan output contract.

Separate state from a history of outputs

A recurrent scoring pipeline maintains a running state while producing a score at every step. The scan API separates the carried value from the per-step output. Keep a fixed-size state in carry and let the scan collect outputs. Appending every result to a growing state array changes its shape and conflicts with the loop’s contract, even if an equivalent ordinary Python loop would accept the changing container.

Initialize the state for the actual update

The carry must preserve its array shapes and dtypes, not merely remain broadcast-compatible. Inspect the first update against the initializer. A scalar initializer that becomes a vector, or an integer value that turns into floating-point state, expresses a different contract. In a running feature accumulator, initialize the intended feature layout and dtype explicitly. Do not rely on a later arithmetic operation to establish the final structure after the loop has already begun.

Represent state updates as returned values

The stateful-computation guide explains passing evolving state into a function and returning its replacement. Use the same pattern in the scan body. A Python object mutated on the side does not provide a dependable recurrent dependency for the transformed numerical calculation. Include all model-relevant state in the declared structure, including counters or statistics that influence later steps, while keeping unrelated service bookkeeping outside the recurrence.

Choose the loop from its stopping contract

The control-flow guide discusses structured loops and their transformation behavior. Scan is designed around a static iteration count and avoids unrolling an ordinary Python loop into a large compiled computation. A data-dependent stopping condition needs a suitable different control-flow design. Padding to a fixed bound can be valid, but its masks and stopped-state behavior should be part of the model logic rather than an undocumented workaround.

Compare the recurrence on a readable sequence

Use a short sequence with distinguishable inputs and inspect final carry separately from stacked outputs. Check reversed processing, empty-input behavior where supported and the intended initial state. The guides on residual state updates and variable-length loss weighting provide related context. The important handoff is an explicit statement of which values evolve, which are collected and which iterations contribute to the final model result.

Earn rental income from GPUs

Have idle GPUs or looking to fund AI infrastructure? Retrivium finds a rental platform, sets up the server and helps you assess income and costs with a pilot.

Explore GPU hosting
← All articles