LSTM: retain, write and reveal
长短期记忆网络
Execute a modern scalar LSTM and its full-state Jacobian, separating the direct memory path from the complete gradient and historical variants.
lstmKeep a cell state and decide what to reveal
An LSTM maintains two related states: a cell state c and a visible hidden state h. Gates control how much old cell content is retained, how much new content is added and how much is exposed through h. Keeping c separate from the squashed output creates a particular route for information and derivatives; it does not guarantee unlimited useful memory.
Hochreiter and Schmidhuber’s 1997 paper, Section 4 describes an additive memory cell with input/output gates and a fixed self-connection. A forget gate belongs to subsequent developments, including Gers, Schmidhuber and Cummins’ accepted 2000 manuscript. We implement a modern no-peephole, no-projection form consistent with the gate equations in the fixed PyTorch 2.8 LSTM documentation, not a reconstruction of every detail of the 1997 architecture.
Three gates and one candidate
Use sigmoid for the input i, forget f and output o gates, and tanh for candidate g. With shared weights and one combined bias per affine transform:
The gates are coordinate-wise values between zero and one in real arithmetic. They are computed from the current input and previous hidden state, rather than prescribed binary switches. The candidate is proposed content; calling every one of these four quantities a sigmoid gate would be inaccurate.
The state update is:
The first term retains cell content; the second adds new content. Input and forget gates are independently parameterized, so their values need not sum to one. The cell state can exceed the range of tanh, while the visible h is squashed and gated. An output gate can hide content without immediately erasing it from c.
The direct cell route is only one derivative route
In this no-peephole form, hold the previous hidden state fixed when differentiating a single cell update with respect to the previous cell value. For a scalar cell, the direct route has:
The last closed form additionally assumes constant gates and candidate. It follows by expanding the affine recurrence. It is not the full general LSTM solution. The direct route can retain a gradient better when forget values are close to one, but a product of values below one still decays.
For the whole state, h and c are connected. Gates can depend on h, and h depends on earlier c. The full state Jacobian must include those extra routes. In the scalar program, the derivative of the new c with respect to old h is c f′+g i′+i g′; the output derivative also includes o′ and the tanh slope. Multiplying the resulting two-by-two Jacobians checks the entire state sensitivity rather than only the direct-cell product.
A constant-gate example with an exact recurrence
The complete Python 3.12 program implements a scalar cell with four input weights, four recurrent weights and four combined biases in i,f,g,o order. It returns all gate values and the analytic Jacobian with state order (h,c). The sequence runner composes these Jacobians while carrying both states.
Set all input and recurrent weights to zero, biases to (0,log 3,log 3,0), and start at zero. Then i=o=1/2, f=3/4 and g=4/5, so each step adds 2/5 after retaining three quarters of c. The first three cell values are 2/5,7/10,37/40. These gates come from actual sigmoid/tanh computations, not hand-assigned outputs.
import math
def scalar(x):
if type(x) not in (int,float) or not math.isfinite(x) or abs(x)>32:raise ValueError('finite scalar with magnitude at most 32 required')
return float(x)
def sigmoid(x):
if x>=0:return 1/(1+math.exp(-x))
e=math.exp(x);return e/(1+e)
def cell(x,h,c,wi,wh,bias):
x,h,c=[scalar(v) for v in (x,h,c)]
wi,wh,bias=[tuple(scalar(v) for v in row) for row in (wi,wh,bias)]
if any(len(row)!=4 for row in (wi,wh,bias)):raise ValueError('four coefficients in i,f,g,o order required')
a=[u*x+v*h+b for u,v,b in zip(wi,wh,bias)]
i,f,g,o=sigmoid(a[0]),sigmoid(a[1]),math.tanh(a[2]),sigmoid(a[3])
new_c=f*c+i*g;t=math.tanh(new_c);new_h=o*t
di=i*(1-i)*wh[0];df=f*(1-f)*wh[1];dg=(1-g*g)*wh[2];do=o*(1-o)*wh[3]
dc_dh=c*df+g*di+i*dg;read=o*(1-t*t)
jacobian=[[t*do+read*dc_dh,read*f],[dc_dh,f]]
return dict(h=new_h,c=new_c,i=i,f=f,g=g,o=o,jacobian=jacobian)
def run(inputs,wi,wh,bias,h0=0,c0=0):
if not 1<=len(inputs)<=32:raise ValueError('1 through 32 time steps required')
h,c=h0,c0;history=[];total=[[1.,0.],[0.,1.]]
for x in inputs:
state=cell(x,h,c,wi,wh,bias);j=state['jacobian']
total=[[sum(j[a][k]*total[k][b] for k in range(2)) for b in range(2)] for a in range(2)]
history.append(state);h,c=state['h'],state['c']
return history,total
if __name__=='__main__':
biases=[0,math.log(3),math.log(3),0]
history,jac=run([0,0,0],[0]*4,[0]*4,biases)
for t,state in enumerate(history,1):
print('step:',t,'i,f,g,o:',*[f'{state[k]:.6f}' for k in ('i','f','g','o')],
'c,h:',f'{state["c"]:.9f}',f'{state["h"]:.9f}')
print('dc3/dc0:',f'{jac[1][1]:.9f}','dh3/dc0:',f'{jac[0][1]:.9f}')
print('twenty-step direct retention:',f'{(.75**20):.9f}')
Actual output:
step: 1 i,f,g,o: 0.500000 0.750000 0.800000 0.500000 c,h: 0.400000000 0.189974481
step: 2 i,f,g,o: 0.500000 0.750000 0.800000 0.500000 c,h: 0.700000000 0.302183889
step: 3 i,f,g,o: 0.500000 0.750000 0.800000 0.500000 c,h: 0.925000000 0.364127103
dc3/dc0: 0.421875000 dh3/dc0: 0.099065913
twenty-step direct retention: 0.003171212
Because the gates in this particular run are independent of the previous state, dc₃/dc₀ equals (3/4)³=27/64. The derivative reaching h₃ is smaller because the output gate and tanh contribute too. At twenty steps, the direct retention is only about 0.003171212; the presence of an additive state does not remove the effect of repeated forgetting.
Tests compare the literal cell values and closed form, check single-step and multi-step full-state Jacobians by finite differences with nonzero recurrent gate weights, and exercise bounded-input/shape contracts. A stable scalar sigmoid avoids overflow at large positive or negative preactivations, although floating-point saturation can still round a gate to an endpoint.
The scalar run costs O(T) and saves O(T) history. A vector cell with hidden width H and input width D has four H-by-D and four H-by-H transforms, plus biases: O(T H(D+H)) work with a larger constant than the simple RNN. Separate-bias or projected implementations have different parameter counts and state shapes.
A memory path is not a full learning guarantee
A nearly closed input gate may prevent useful writes; a nearly closed output gate may block the loss from seeing stored information. Saturated sigmoid derivatives can make gate parameters hard to update. Large recurrent weights introduce additional gradient paths, so bounding gate values alone does not bound every state or parameter derivative.
State resets must preserve the intended sequence boundaries. Carrying h without c does not reproduce the same LSTM continuation. Detaching either state for truncated training changes which paths BPTT follows; the constant-gate forward example here does not implement parameter learning or a truncation schedule.
Peephole variants make gates depend on cell values, and projection variants can give h a different width from c. Those changes require different derivatives and shape handling. The program is a small bounded scalar implementation of the declared form; it does not claim complete framework compatibility.
The original and later papers report results under their own training procedures. We use them to distinguish the architecture’s development, not to claim a reproduced benchmark or a universal memory horizon for modern LSTMs.
Stored, forgotten or merely hidden?
- What are the first three cell values in the constant-gate example?
Answer 1: 2/5,7/10 and 37/40.
- What is dc₃/dc₀ in that example?
Answer 2: 27/64, since its gates do not depend on the previous state.
- Does closing the output gate necessarily erase the cell state immediately?
Answer 3: No. It hides the visible output; the cell update has its own retain/write terms.
- Is the product of forget gates always the full derivative through a general LSTM?
Answer 4: No. Hidden-state dependence of the gates and candidate creates additional routes.
Name the variant before reproducing it
The 1997 memory-cell construction, the later forget-gate study and the fixed modern API are distinct references. The scalar code, constant-gate calculation and complete-state derivative audit here are original. Source figures, training algorithms and experimental results were not copied or reproduced.
Continue with BPTT for training through the state graph and GRU for a gated recurrence with one state vector. Compare the actual formulas before treating differently named gates as interchangeable.
Make a prediction, then check
In the constant-gate example, what is dc3/dc0?
Learning objectives
- Compute gates, cell state and hidden state under a declared LSTM variant.
- Distinguish direct retention from the full state derivative.
Prerequisites & connections
Explore related knowledge →References
- Long Short-Term Memory
Sepp Hochreiter; Jürgen Schmidhuber · 1997 - Learning to Forget: Continual Prediction with LSTM — accepted manuscript
Felix A. Gers; Jürgen Schmidhuber; Fred Cummins · 2000 - LSTM — 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:
- Long Short-Term Memory · Author-hosted1997 PDF32 physicalpages: visually inspected Section4 physical6–7, fixed self-connection and input/output gates; garbled text extraction not trusted for formulas.
- Learning to Forget: Continual Prediction with LSTM — accepted manuscript · Author-hosted accepted2000 manuscript20 pages: cover, abstract and Figure1/standard-cell discussion physical2/4/5 visually read. Used for later forget-gate motivation, not first-introduction date or benchmark replication.
- LSTM — PyTorch 2.8 · Fixed2.8 LSTM gate/state equations, no-peephole default form, separate biases and optional projection distinction; original scalar implementation and full-state derivative.
Related topics