The neural notebook
← All chapters

IV-19 / Part IV · Sequence Models

Sequences, Order and Recurrent State

Compute each state of an ordered scalar recurrence, distinguish shared parameters from time states, and make prefixes, resets and feature axes explicit.

Review the ideas this chapter uses

Reading three measurements in order is different from receiving an unordered bag of measurements. A running calculation can carry information from an earlier item into the next one. A recurrent neural network, or RNN, does this by computing a new state from the current input and the previous state. We will use one number per input and one number per state so every operation stays visible.

Learning objective: Define ordered samples, shared recurrent parameters and temporal state.

The prerequisite is IV-18 — How Embeddings Learn From Gradients: repeated uses of one embedding row shared parameters while retaining distinct output positions. Here different times share the same recurrence parameters. For an optional review of matrix times column-vector notation, use II.9 — Matrix × vector.

Move an item, then follow the calculation

Compute it yourself

Move ordered items and recompute every shared-state step

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
x0
1
x1
2
x2
-1
wx
0.5
wh
0.5
b
0
h0
0
T
3
activation
0
order
0
finalState0.125
T3
activation0
order0

finalState 0.125. T 3. activation 0. order 0. Current: ordered active sequence. Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.. source0 0. source1 1. source2 2. T 3. h0 0

Current: ordered active sequence

permute three source identities; take leading T; initialize h0

Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.

Inputs

x0
1
x1
2
x2
-1
wx
0.5
wh
0.5
b
0
h0
0
T
3
activation
0
order
0

Outputs

source0
0
source1
1
source2
2
T
3
h0
0

Ordered source items and actual forward states

Source identity stays visible even for equal values. Permute all three items first, then use only the leading T=3. Inactive items cause no state update. h0=0 initializes this calculation.

Move left / Move right swaps adjacent source identities through the existing input controls. The native order selector above is the keyboard equivalent; all buttons also work by keyboard.

All three ordered positions, before selecting the active prefix
PositionSource identityValuePrefix statusMove this source item
1x01Active
2x12Active
3x2-1Active
Current actual states: X[1,T,1], states[1,T+1,1], z/slopes[1,T,1]
TimeSourceInputPrevious statewx × inputwh × previousProduct sumBiaszActual hStored slope
0Explicit initial state; no input consumed0Not an activation step
1x0100.500.500.50.51
2x120.510.251.2501.251.251
3x2-11.25-0.50.6250.12500.1250.1251

Tables show stored values. Tanh uses the stored slope 1−h², which may round to zero at saturation even when the finite real derivative is positive. Trace navigation highlights an actual operation; the controls remain the starting inputs.

Inspect tensor shapes and full precision

All computed outputs

finalState
0.125
T
3
activation
0
order
0
h0
0
h1
0.5
h2
1.25
h3
0.125
sequence_source0
0
sequence_source1
1
sequence_source2
2
sequence_T
3
sequence_h0
0
forward_1_previousState
0
forward_1_inputProduct
0.5
forward_1_recurrentProduct
0
forward_1_partialSum
0.5
forward_1_z
0.5
forward_1_state
0.5
forward_1_slope
1
forward_2_previousState
0.5
forward_2_inputProduct
1
forward_2_recurrentProduct
0.25
forward_2_partialSum
1.25
forward_2_z
1.25
forward_2_state
1.25
forward_2_slope
1
forward_3_previousState
1.25
forward_3_inputProduct
-0.5
forward_3_recurrentProduct
0.625
forward_3_partialSum
0.125
forward_3_z
0.125
forward_3_state
0.125
forward_3_slope
1

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

X

B=1 × T=3 × D=1 · float64 · display precision 8 · Actual active ordered inputs; inactive positions omitted.

Storage indexValue
01
12
2-1

states

B=1 × State=4 × H=1 · float64 · display precision 8 · Explicit h0 followed by every actual recurrent state.

Storage indexValue
00
10.5
21.25
30.125

z

B=1 × T=3 × H=1 · float64 · display precision 8 · Actual preactivations.

Storage indexValue
00.5
11.25
20.125

slopes

B=1 × T=3 × H=1 · float64 · display precision 8 · Stored linear or 1-state² slopes; saturation can produce zero.

Storage indexValue
01
11
21

sourceIds

Position=3 · int32 · display precision 8 · Source identity at each ordered position, even when values coincide.

Storage indexValue
00
11
22

orderedValues

Position=3 · float64 · display precision 8 · Full permutation before selecting the active prefix.

Storage indexValue
01
12
2-1

sourceValues

Source=3 · float64 · display precision 8 · Original source values indexed by identity.

Storage indexValue
01
12
2-1

Try T=1 to see the active prefix, then move a different source item into position 1. Set h0 to a nonzero value and change order twice: each edit starts again from that explicit h0. Reset restores all ten fields.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. What is shared across recurrent time steps?
2. Reset. What is h1 for x0=1, wx=1/2, wh=1/2, b=0 and h0=0?
3. Read the actual forward table. What is the final state for the current controls?
4. Reset, then move x1 left so the order is [x1,x0,x2]. What is the final linear state?
5. Set wh=0. Which statement is correct for a fixed last active item?

Begin with Reset. The three source items have values x0=1, x1=2 and x2=-1. These code names identify source items, starting at zero. They are different from the mathematical time subscript in xtx_t: time starts at one, and xtx_t means whichever item is consumed at that time.

Use the order selector, or the adjacent Move left and Move right buttons. Move the source item x1 before x0. The active sequence becomes [2,1,−1][2,1,-1]. Compare every state with the reset sequence [1,2,−1][1,2,-1], not just the final number. Keyboard users can make the same choices with the native selector and buttons; movement past an end is disabled.

Each edit starts a fresh calculation from the displayed initial state. Trace navigation explains that calculation; it does not carry a state into a later edit. Reset restores the supplied example, including its initial state. Editing these hand-set parameters is exploration, not training: this chapter has no target, loss or automatic parameter update.

Name the three ingredients

At each time tt, combine the input xtx_t with the previous state ht−1h_{t-1}:

zt=wxxt+whht−1+b,ht=a(zt).z_t=w_xx_t+w_hh_{t-1}+b,\qquad h_t=a(z_t).

The input weight wxw_x scales the new item. The recurrent weight whw_h scales the old state. The bias bb adds a constant offset. These three numbers are shared parameters: the same values are used at every active time. They do not become different weights merely because the recurrence is drawn three times.

The preactivation ztz_t is the sum before applying function aa. The hidden state hth_t is its output, passed to the next time. “Hidden” names an internal quantity, not a secret or an established interpretation. h0h_0 is an explicitly supplied initial state; it is present before the first input is consumed.

The activation selector offers two functions. Linear activation means a(z)=za(z)=z, with slope a′(z)=1a'(z)=1. Hyperbolic tangent, written tanh⁡\tanh, is

a(z)=tanh⁡z=ez−e−zez+e−z,a′(z)=1−tanh⁡2z.a(z)=\tanh z=\frac{e^z-e^{-z}}{e^z+e^{-z}},\qquad a'(z)=1-\tanh^2z.

Here ee is the natural exponential base, the prime denotes a derivative, and a slope describes how a small input change affects an output locally. Tanh compresses finite real inputs into the open interval (−1,1)(-1,1). The displayed mathematical identity explains it; a numerical implementation need not form those exponentials directly.

Keep shape separate from time

A tensor is an array with named axes. This example has batch size B=1B=1, input feature dimension D=1D=1 and hidden dimension H=1H=1. A batch counts separate examples, D counts coordinates per input, and H counts coordinates per state. T counts active time steps.

QuantityShapeAxis meanings
Active inputs X[1,T,1]batch, time, input feature
States including the initial state[1,T+1,1]batch, state index, hidden feature
Preactivations z[1,T,1]batch, time, hidden feature
Activation slopes[1,T,1]batch, time, hidden feature

There are T+1 states because the initial state precedes the T updates. There are only T preactivations and slopes; h0h_0 was supplied, not produced by an activation in this calculation. In X’s storage, position t−1t-1 corresponds to mathematical time t.

This scalar recurrence is a 1×11\times1 instance of the vector formula

zt=Wxut+Whht−1+b,ht=a(zt),z_t=W_xu_t+W_hh_{t-1}+b,\qquad h_t=a(z_t),

where ut:[D,1]u_t:[D,1], Wx:[H,D]W_x:[H,D], Wh:[H,H]W_h:[H,H] and b:[H,1]b:[H,1]. The vector ztz_t and state column both have shape [H,1][H,1]; activation acts on each coordinate. Each product therefore produces one hidden column, and the bias is a same-shaped addition.

To connect feature-last storage with those columns, take X’s D-coordinate row at batch zero and position t−1t-1, then transpose that row to obtain utu_t. Transpose exchanges rows and columns without changing coordinates. Here D=H=1, so orientation changes no visible value, but the conversion still matters. This example does not define every RNN architecture. The broader idea of composing representations is developed in III-41 — Composition and Learned Representations; here every parameter remains hand-set.

Work through every reset state

Reset uses linear activation, wx=wh=1/2w_x=w_h=1/2, b=0b=0 and h0=0h_0=0. First compute two products, add the bias, then apply activation:

z1=(1/2)(1)+(1/2)(0)+0=1/2+0+0=1/2,h1=1/2.z_1=(1/2)(1)+(1/2)(0)+0=1/2+0+0=1/2,\qquad h_1=1/2.

The next recurrent product uses that newly computed state:

z2=(1/2)(2)+(1/2)(1/2)+0=1+1/4+0=5/4,h2=5/4.z_2=(1/2)(2)+(1/2)(1/2)+0=1+1/4+0=5/4,\qquad h_2=5/4.

Finally,

z3=(1/2)(−1)+(1/2)(5/4)+0=−1/2+5/8+0=1/8,h3=1/8.z_3=(1/2)(-1)+(1/2)(5/4)+0=-1/2+5/8+0=1/8,\qquad h_3=1/8.

Thus the stored state sequence includes [0,1/2,5/4,1/8][0,1/2,5/4,1/8]. Each activation slope is one. The negative final input reduces the state, but does not erase the positive recurrent contribution 5/85/8. The final state is neither the final input nor the sum of all inputs.

A trace step should be read as an arithmetic record: current input, old state, both weighted products, bias, their sum, activation and slope. A small final output can conceal larger intermediate states. Inspecting the complete sequence avoids attributing that small result to a computation that never occurred.

Why changing order changes the result

Keep all parameters fixed, but use source order [x1,x0,x2]. The calculation is now

h1=(1/2)(2)+(1/2)(0)+0=1,h_1=(1/2)(2)+(1/2)(0)+0=1, h2=(1/2)(1)+(1/2)(1)+0=1,h_2=(1/2)(1)+(1/2)(1)+0=1, h3=(1/2)(−1)+(1/2)(1)+0=0.h_3=(1/2)(-1)+(1/2)(1)+0=0.

The inputs contain exactly the same values and have the same last item. Nevertheless the final state changed from 1/81/8 to zero. Earlier items reached the final state through different numbers of recurrent multiplications.

Expanding three linear steps explains why:

h3=wxx3+whwxx2+wh2wxx1+b(1+wh+wh2)+wh3h0.h_3=w_xx_3+w_hw_xx_2+w_h^2w_xx_1 +b(1+w_h+w_h^2)+w_h^3h_0.

A power such as wh2w_h^2 means two multiplications by whw_h. The first input crosses two recurrent links; the last crosses none. These unequal coefficients make this recurrence sensitive to order. They do not guarantee that every reordering produces a different value: equal inputs or special parameters can make outputs coincide.

The selector encodes the six permutations of source positions in a fixed order:

Order codeSource positionsReset values in that order
0[0,1,2][1,2,-1]
1[0,2,1][1,-1,2]
2[1,0,2][2,1,-1]
3[1,2,0][2,-1,1]
4[2,0,1][-1,1,2]
5[2,1,0][-1,2,1]

Two equal-valued items still have different identities. Buttons swap adjacent source positions; the resulting permutation determines the order code. They do not invent intermediate numerical states while an item moves.

A shorter prefix is not zero padding

T selects the leading T items after the full three-item permutation. At order zero and T=2, the active inputs are [1,2][1,2] and the states are [0,1/2,5/4][0,1/2,5/4]. The remaining source item is inactive. There is no third update or fabricated third output.

Replacing an inactive item with zero would be a different operation: even with zero input, whht−1+bw_hh_{t-1}+b can change the state. Padding means adding positions to a representation, often with an accompanying rule for ignoring them. This example uses an active prefix and skips inactive positions; it does not implement a padded batch.

The initial state also has real mathematical influence. For linear activation at T=3, changing only h0h_0 by an amount δ\delta changes h3h_3 by wh3δw_h^3\delta. The symbol δ\delta names that initial change. This is a dependency within a single calculation, distinct from accidentally remembering a previous interface gesture.

Set wh=0w_h=0 for a useful limit. Then ht=a(wxxt+b)h_t=a(w_xx_t+b) has no dependence on the preceding state. Swapping earlier items while keeping the last active item fixed leaves the last output unchanged. Changing which item is last can still change it. Removing recurrent memory does not make selection of the last item irrelevant.

Valid inputs and finite arithmetic

Exactly ten fields define the state: x0,x1,x2,wx,wh,b,h0,T,activation,order. Source values are finite numbers in [−4,4][-4,4]; the four fields wx,wh,b,h0 are in [−2,2][-2,2]. T is integer 1 through 3, activation is integer 0 for linear or 1 for tanh, and order is integer 0 through 5.

All source fields are checked even when inactive. Missing, extra, nonnumeric or out-of-range entries are invalid; silently clipping or rounding would replace the requested problem. Intermediate values must also remain finite. Tensor coordinates use binary64, the finite-precision format commonly called double precision.

For tanh the recorded slope is computed from the stored state as 1−ht21-h_t^2. A stored tanh value can round to exactly 1 or −1, making that slope zero, although the real derivative at every finite preactivation is positive. Distinguish this stored numerical boundary from a proof that the real function stops changing.

Five exercises to use with the lab

  1. Shared parameters. What is shared across recurrent time steps? The same wx,wh,b parameters. Each time has its own state; h0h_0 is the explicit starting value for each fresh calculation.
  2. First-state arithmetic. Reset. What is h1h_1 for source x0=1, wx=wh=1/2w_x=w_h=1/2, b=0b=0 and h0=0h_0=0? Linear activation gives (1/2)(1)+(1/2)(0)+0=1/2(1/2)(1)+(1/2)(0)+0=1/2. The recurrent product uses h0h_0, not the next item; tanh would apply tanh to this sum.
  3. Current final state. Read the actual forward table. What is the final state for the current controls? Follow every current previous-state product and take the last active state. Reset gives 1/81/8; after an edit, use that calculation’s actual result rather than reusing the reset answer.
  4. Move an item. Reset, then move x1 left so the order is [x1,x0,x2]. What is the final linear state? Zero, through states 1,1,01,1,0. Reusing the reset intermediate 5/45/4 would mix two calculations.
  5. Zero-memory limit. Set wh=0. Which statement is correct for a fixed last active item? The last state is independent of earlier items, but changing the last item can still change it: ht=a(wxxt+b)h_t=a(w_xx_t+b). Inactive positions are skipped, and zero recurrent weight does not force every output to zero.

Read the canonical program

The chapter program and shared recurrent helper are included directly from their actual Python files. Read the validation, explicit recurrence and recorded operands together; the helper is part of the implementation, not an omitted numerical black box.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV19: source identity, order, active prefixes and shared recurrent state."""
from recurrent_reference import RECURRENT_BOUNDS, RECURRENT_DEFAULTS, Trace, fixed_state, forward, guarded, run

DEFAULT_IV19 = dict(RECURRENT_DEFAULTS)


@guarded
def derive_iv19(state):
    """Compute the ordered scalar recurrence from an explicit fresh initial state."""
    s = fixed_state(state, DEFAULT_IV19, RECURRENT_BOUNDS, ("T", "activation", "order"))
    trace = Trace()
    current = forward(s, trace)
    summary = dict(finalState=float(current["states"][0, s["T"], 0]),
                   T=s["T"], activation=s["activation"], order=s["order"])
    summary.update({f"h{t}": current["states"][0, t, 0] for t in range(s["T"] + 1)})
    return trace.result(summary, current["tensors"])


if __name__ == "__main__":
    run(derive_iv19, DEFAULT_IV19)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Shared IV19–21 source: strict states, scalar arithmetic and NumPy storage.

Keep this helper beside the lesson files. Each CLI accepts defaults, a complete
JSON replacement, or '-' for stdin. Authored under the runtime hold; not executed.
"""
import argparse
from functools import wraps
import json
import math
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def fixed_state(state, defaults, bounds, integers=()):
    # Validate inactive fields too; no merging, string coercion or clipping.
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = bounds[key]
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integers and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integers else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class Trace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        # Local names remain readable; aggregate keys cannot shadow the summary.
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
        self.steps.append({"id": identifier, "label": label, "equation": equation,
                           "explanation": explanation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
                "steps": self.steps, "tensors": tensors}


def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    array = np.asarray(values, dtype=np.float64)
    if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    flat = [finite(value, identifier) for value in array.reshape(-1)]
    if dtype == "int32":
        if any(not value.is_integer() for value in flat):
            raise NumericalFault("INVALID_INPUT", "Source IDs must be integers.")
        flat = [int(value) for value in flat]
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": dtype,
            "values": flat, "provenance": provenance, "precision": 8}


RECURRENT_DEFAULTS = dict(x0=1, x1=2, x2=-1, wx=0.5, wh=0.5, b=0, h0=0,
                          T=3, activation=0, order=0)
RECURRENT_BOUNDS = {"x0": (-4, 4), "x1": (-4, 4), "x2": (-4, 4),
                    "wx": (-2, 2), "wh": (-2, 2), "b": (-2, 2), "h0": (-2, 2),
                    "T": (1, 3), "activation": (0, 1), "order": (0, 5)}
PERMUTATIONS = ((0, 1, 2), (0, 2, 1), (1, 0, 2),
                (1, 2, 0), (2, 0, 1), (2, 1, 0))


def activate(z, choice):
    state = finite(z if choice == 0 else math.tanh(z), "activation")
    square = finite(state * state, "stored activation square")
    # Stored 1-h*h can round to zero although the finite real tanh slope is positive.
    return state, 1.0 if choice == 0 else finite(1.0 - square, "stored tanh slope")


def forward(s, trace, prefix=""):
    """Permute source identities first, then evaluate only the active prefix."""
    def name(key):
        return f"{prefix}_{key}" if prefix else key

    T = s["T"]
    sources = np.array([s["x0"], s["x1"], s["x2"]], dtype=np.float64)
    source_ids = np.array(PERMUTATIONS[s["order"]], dtype=np.int32)
    ordered = np.empty(3, dtype=np.float64)
    for position in range(3):
        ordered[position] = sources[int(source_ids[position])]
    X = np.empty((1, T, 1), dtype=np.float64)
    states = np.empty((1, T + 1, 1), dtype=np.float64)
    z = np.empty((1, T, 1), dtype=np.float64)
    slopes = np.empty((1, T, 1), dtype=np.float64)
    states[0, 0, 0] = s["h0"]
    trace.add(name("sequence"), f"{prefix or 'Current'}: ordered active sequence",
              "permute three source identities; take leading T; initialize h0",
              "Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.",
              s, dict(source0=source_ids[0], source1=source_ids[1], source2=source_ids[2], T=T, h0=s["h0"]))
    for t in range(1, T + 1):
        x, previous = float(ordered[t - 1]), float(states[0, t - 1, 0])
        input_product = finite(s["wx"] * x, "wx*x")
        recurrent_product = finite(s["wh"] * previous, "wh*previousState")
        partial_sum = finite(input_product + recurrent_product, "input plus recurrent product")
        preactivation = finite(partial_sum + s["b"], "z")
        state, slope = activate(preactivation, s["activation"])
        X[0, t - 1, 0], states[0, t, 0] = x, state
        z[0, t - 1, 0], slopes[0, t - 1, 0] = preactivation, slope
        trace.add(name(f"forward_{t}"), f"{prefix or 'Current'}: forward time {t}",
                  "inputProduct=wx*x; recurrentProduct=wh*previousState; z=(inputProduct+recurrentProduct)+b; state=a(z); slope=1 or 1-state²",
                  "The same wx, wh and b are reused at each time. A stored tanh slope can round to zero although the finite real derivative is positive.",
                  dict(t=t, sourceId=int(source_ids[t - 1]), x=x, wx=s["wx"], wh=s["wh"], b=s["b"],
                       previousState=previous, activation=s["activation"]),
                  dict(previousState=previous, inputProduct=input_product, recurrentProduct=recurrent_product,
                       partialSum=partial_sum, z=preactivation, state=state, slope=slope))
    tensors = [
        tensor(name("X"), [1, T, 1], ["B", "T", "D"], X, "Actual active ordered inputs; inactive positions omitted."),
        tensor(name("states"), [1, T + 1, 1], ["B", "State", "H"], states, "Explicit h0 followed by every actual recurrent state."),
        tensor(name("z"), [1, T, 1], ["B", "T", "H"], z, "Actual preactivations."),
        tensor(name("slopes"), [1, T, 1], ["B", "T", "H"], slopes, "Stored linear or 1-state² slopes; saturation can produce zero."),
        tensor(name("sourceIds"), [3], ["Position"], source_ids, "Source identity at each ordered position, even when values coincide.", "int32"),
        tensor(name("orderedValues"), [3], ["Position"], ordered, "Full permutation before selecting the active prefix."),
        tensor(name("sourceValues"), [3], ["Source"], sources, "Original source values indexed by identity."),
    ]
    return dict(X=X, states=states, z=z, slopes=slopes, tensors=tensors)


def run(derive, defaults):
    """No argument uses defaults; a JSON object fully replaces them; '-' reads stdin."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive(state)
    else:
        state = dict(defaults)
        result = derive(state)
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Keep the files together. The CLI accepts defaults with no state argument, a complete replacement JSON object, or - to read that object from standard input.

Recap and bridge

An ordered sample supplies inputs in a declared sequence. Shared weights are reused while time states remain distinct. A prefix skips inactive positions, and each calculation starts from its explicit h0h_0. Shapes account for that initial state separately from active inputs.

Next, IV-20 — Recurrent Networks and Backpropagation Through Time attaches one final-state loss and follows its derivatives backward through every use of these shared parameters.