AI Wiki中文/EN

Recurrent neural networks: carry the state

循环神经网络

Execute a two-unit recurrent layer, compare chunking with resets, and separate temporal state, parameters and causal information.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Carry a state instead of restarting the calculation

A sequence model receives a new value while retaining a state from earlier values. If the state is reset before every element, the same small network may still run without a shape error—but it has lost its recurrent context. If the state is carried into an unrelated sequence, it can mix information that should have been separated.

Deep Learning, Sections 10.1–10.2 describes recurrence by unfolding a shared transition through time. The fixed PyTorch 2.8 RNN documentation describes an Elman-style recurrence with tanh or ReLU. This chapter implements one tanh layer, keeping state values, trainable parameters and optional output readout distinct.

The same transition receives a different state each time

For an input column vector xₜ with D features and hidden state hₜ with H features, use:

at=Wxxt+Whht−1+b,ht=tanh⁡(at),yt=Vht+c.a_t=W_xx_t+W_hh_{t-1}+b,\qquad h_t=\tanh(a_t),\qquad y_t=Vh_t+c.

Tanh acts coordinate by coordinate. Wx has shape H by D, Wh is H by H, and b has H entries. The optional readout V maps hidden features to the desired output space. Our program returns hidden states; its displayed readout simply subtracts the second hidden coordinate from the first.

The transition has HD+H²+H parameters, independent of sequence length. Hidden activations change at every step even when parameters stay fixed. The PyTorch interface uses separate input and recurrent bias vectors; the combined bias above describes the same forward affine expression when their sum equals b, but is not the same parameter-count convention.

Write Fθ(h,x) for the transition. Unfolding two steps gives:

h2=Fθ(Fθ(h0,x1),x2).h_2=F_\theta(F_\theta(h_0,x_1),x_2).

The two appearances of θ refer to shared parameters. This is a finite directed acyclic computation when unfolded, even though the compact diagram has a recurrent edge. At time t, a forward-only recurrence can depend on h₀ and inputs through t, but not on a future input that has not been processed.

A simple memory model makes the role of order visible

Temporarily replace the nonlinear vector transition by the scalar linear rule hₜ=ρhₜ₋₁+xₜ. Repeated substitution gives:

hT=ρTh0+∑t=1TρT−txt.h_T=\rho^Th_0+\sum_{t=1}^{T}\rho^{T-t}x_t.

For ρ=1/2 and h₀=0, inputs (1,0) yield final state 1/2, whereas (0,1) yield one. This is a separate linear illustration, not an exact expression for the tanh program. It shows how shared parameters can still give different influence to different time positions. An actual nonlinear state need not be a lossless record of all earlier inputs.

A sequence boundary is a modeling decision

Splitting a sequence into two chunks while carrying the final state of the first chunk reproduces the same deterministic forward computation as processing it in one pass, provided the parameters and all relevant state remain unchanged. Resetting the state at the chunk boundary computes something else.

Forward state carry is also different from carrying a differentiation graph across chunks. A training implementation may preserve state values while detaching their earlier derivative history. That affects training gradients without necessarily changing the forward numbers; BPTT makes the distinction explicit.

Inspect four states and a chunk boundary

The complete Python 3.12 / NumPy 1.26.4 program accepts a T-by-D sequence, H-by-D input matrix, H-by-H recurrent matrix and one combined bias. It returns all states and the final state as fresh arrays. Inputs, dimensions and magnitudes are bounded; an empty sequence returns an empty history and the unchanged initial state.

import numpy as np


def bounded(value):
    a=np.array(value,dtype=np.float64,copy=True)
    if not np.isfinite(a).all() or np.any(np.abs(a)>8):raise ValueError('finite entries with magnitude at most 8 required')
    return a


def rnn(sequence,wx,wh,b,h0=None):
    wx,wh,b=[bounded(v) for v in (wx,wh,b)]
    if wx.ndim!=2 or not 1<=wx.shape[0]<=4 or not 1<=wx.shape[1]<=4:raise ValueError('bounded H by D input matrix required')
    hsize,d=wx.shape
    if wh.shape!=(hsize,hsize) or b.shape!=(hsize,):raise ValueError('recurrent matrix or bias shape mismatch')
    x=bounded(sequence)
    if x.ndim==1 and x.size==0:x=x.reshape(0,d)
    if x.ndim!=2 or x.shape[1]!=d or len(x)>32:raise ValueError('bounded T by D sequence required')
    h=np.zeros(hsize) if h0 is None else bounded(h0)
    if h.shape!=(hsize,):raise ValueError('initial state must have H entries')
    history=[]
    for item in x:
        h=np.tanh(wx@item+wh@h+b)
        history.append(h.copy())
    return np.array(history).reshape(len(x),hsize),h.copy()


if __name__=='__main__':
    x=[[1],[0],[-1],[2]];wx=[[.5],[-.5]];wh=[[.5,.25],[-.25,.5]];b=[0,.1]
    states,last=rnn(x,wx,wh,b)
    first,carry=rnn(x[:2],wx,wh,b);second,_=rnn(x[2:],wx,wh,b,carry)
    reset_states=np.array([rnn([item],wx,wh,b)[1] for item in x])
    print('states:',np.round(states,9).tolist())
    print('readout h[0]-h[1]:',np.round(states[:,0]-states[:,1],9).tolist())
    print('chunked state carry matches:',np.array_equal(states,np.concatenate((first,second))))
    print('reset-each-step states:',np.round(reset_states,9).tolist())

Actual output:

states: [[0.462117157, -0.379948962], [0.135237706, -0.202658887], [-0.448679626, 0.434037869], [0.708502052, -0.515954748]]
readout h[0]-h[1]: [0.84206612, 0.337896593, -0.882717496, 1.2244568]
chunked state carry matches: True
reset-each-step states: [[0.462117157, -0.379948962], [0.0, 0.099667995], [-0.462117157, 0.537049567], [0.761594156, -0.71629787]]

At the first step, the two preactivations are 0.5 and −0.4, so the hidden state is (tanh(0.5),tanh(−0.4)). At the second step, the input is zero, yet the previous state contributes through Wh. Resetting before that input would instead yield (0,tanh(0.1)); the displayed difference is genuine remembered context, not an extra input feature.

Tests check literal states, exact chunk equivalence, prefix causality and initial-state derivatives against finite differences. They also cover empty input, shape mismatches and nonfinite values. A T-step forward pass costs O(T(HD+H²)); the displayed history uses O(TH) storage. Streaming inference can retain only the current H-dimensional state when earlier outputs are not required.

A hidden state is not automatically useful memory

The transition can discard information, saturate or amplify sensitivity. Tanh bounds its output coordinates, but that alone does not guarantee well-behaved parameter gradients through a long unrolled sequence. Bounded states and bounded derivatives are different properties.

The example is unbatched and single-layer. In a stacked RNN, a layer receives the lower layer’s current-time output and its own previous-time hidden state. Those are different edges; confusing layer index with time index changes the network. The fixed API’s batch_first changes input/output layout, not the hidden-state layout, and its dropout option applies between recurrent layers except after the last layer. We do not implement these additional modes.

Padding a shorter sequence and continuing transitions is not generally equivalent to stopping at its true end. A stateful batching scheme also needs a reliable mapping between streams and hidden states. The program has no masking, packed sequences or automatic persistence across calls.

No parameters are fitted here. The point is to establish the correct forward mechanism before adding a training objective; the readout values are not probabilities or task-accuracy claims. Gradients, losses and evaluation belong to the next parts of the model specification.

What crosses the boundary?

  1. Does a four-step unrolling create four independent copies of Wx and Wh?

Answer 1: No. The same parameters are reused at all four steps.

  1. What must be passed between chunks to reproduce this forward calculation?

Answer 2: The preceding chunk’s final hidden state, with unchanged parameters and no omitted relevant state.

  1. Does a zero input imply a zero next hidden state?

Answer 3: No. The recurrent term and bias can still contribute.

  1. Can a later input change a previously computed state in this forward-only model?

Answer 4: No, if the earlier inputs, initial state and parameters are unchanged.

Separate temporal state from learned weights

The textbook supplies the unrolling and parameter-sharing formulation. The fixed API supplies a concrete recurrence and layout conventions. Our two-unit network, chunk comparison and numerical checks are original; no library implementation or trained sequence benchmark was reproduced.

Continue with parameter sharing, BPTT and LSTM. These explain how shared weights are trained and how gated transitions change the route by which state information persists.

Make a prediction, then check

What reproduces one-pass inference when a sequence is split into chunks?

Choose one answer

Learning objectives

  • Carry hidden state correctly through a deterministic sequence.
  • Distinguish state carry from parameter sharing and gradient history.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive Nets
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. RNN — PyTorch 2.8
    PyTorch contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Recurrent state carry, full/cut BPTT and LSTM/GRU state Jacobians are checked against literal references, independent forward sensitivities, frozen-boundary surrogates and finite differences. RNN/GRU use NumPy1.26.4; BPTT/LSTM use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.