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
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
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.
| Position | Source identity | Value | Prefix status | Move this source item |
|---|---|---|---|---|
| 1 | x0 | 1 | Active | |
| 2 | x1 | 2 | Active | |
| 3 | x2 | -1 | Active |
| Time | Source | Input | Previous state | wx × input | wh × previous | Product sum | Bias | z | Actual h | Stored slope |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Explicit initial state; no input consumed | 0 | Not an activation step | |||||||
| 1 | x0 | 1 | 0 | 0.5 | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 |
| 2 | x1 | 2 | 0.5 | 1 | 0.25 | 1.25 | 0 | 1.25 | 1.25 | 1 |
| 3 | x2 | -1 | 1.25 | -0.5 | 0.625 | 0.125 | 0 | 0.125 | 0.125 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
states
B=1 × State=4 × H=1 · float64 · display precision 8 · Explicit h0 followed by every actual recurrent state.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 0.5 |
| 2 | 1.25 |
| 3 | 0.125 |
z
B=1 × T=3 × H=1 · float64 · display precision 8 · Actual preactivations.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 1.25 |
| 2 | 0.125 |
slopes
B=1 × T=3 × H=1 · float64 · display precision 8 · Stored linear or 1-state² slopes; saturation can produce zero.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
sourceIds
Position=3 · int32 · display precision 8 · Source identity at each ordered position, even when values coincide.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
orderedValues
Position=3 · float64 · display precision 8 · Full permutation before selecting the active prefix.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
sourceValues
Source=3 · float64 · display precision 8 · Original source values indexed by identity.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 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.
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 : time starts at one, and 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 . Compare every state with the reset sequence , 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 , combine the input with the previous state :
The input weight scales the new item. The recurrent weight scales the old state. The bias 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 is the sum before applying function . The hidden state is its output, passed to the next time. “Hidden” names an internal quantity, not a secret or an established interpretation. is an explicitly supplied initial state; it is present before the first input is consumed.
The activation selector offers two functions. Linear activation means , with slope . Hyperbolic tangent, written , is
Here 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 . 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 , input feature dimension and hidden dimension . A batch counts separate examples, D counts coordinates per input, and H counts coordinates per state. T counts active time steps.
| Quantity | Shape | Axis 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; was supplied, not produced by an activation in this calculation. In X’s storage, position corresponds to mathematical time t.
This scalar recurrence is a instance of the vector formula
where , , and . The vector and state column both have shape ; 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 , then transpose that row to obtain . 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, , and . First compute two products, add the bias, then apply activation:
The next recurrent product uses that newly computed state:
Finally,
Thus the stored state sequence includes . Each activation slope is one. The negative final input reduces the state, but does not erase the positive recurrent contribution . 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
The inputs contain exactly the same values and have the same last item. Nevertheless the final state changed from to zero. Earlier items reached the final state through different numbers of recurrent multiplications.
Expanding three linear steps explains why:
A power such as means two multiplications by . 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 code | Source positions | Reset 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 and the states are . 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, 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 by an amount changes by . The symbol names that initial change. This is a dependency within a single calculation, distinct from accidentally remembering a previous interface gesture.
Set for a useful limit. Then 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 ; the four fields wx,wh,b,h0 are in . 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 . 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
- Shared parameters. What is shared across recurrent time steps? The same
wx,wh,bparameters. Each time has its own state; is the explicit starting value for each fresh calculation. - First-state arithmetic. Reset. What is for source
x0=1, , and ? Linear activation gives . The recurrent product uses , not the next item; tanh would apply tanh to this sum. - 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 ; after an edit, use that calculation’s actual result rather than reusing the reset answer.
- Move an item. Reset, then move
x1left so the order is[x1,x0,x2]. What is the final linear state? Zero, through states . Reusing the reset intermediate would mix two calculations. - 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: . 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 . 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.