Neural Networks
RNN vs LSTM Memory
A direct cell path and a final hidden-output derivative answer different questions: multiply local Jacobians through time and sum the signed contributions at forks.
RNN, single selected cell, 5 tokens; initial h₀=0, c₀=0. Inspect token 0, Forget f. Final hidden h_last=0.171893. Q=h_last, supplied upstream (h,c)=(1,0). No training.
RNN, single selected cell, 5 tokens; initial h₀=0, c₀=0. Inspect token 0, Forget f. Final hidden h_last=0.171893. Q=h_last, supplied upstream (h,c)=(1,0). No training.
Signed derivatives (scientific notation below .001): first token to h_last, RNN 0.120406, LSTM 0.114446; direct cell retention after token 0 0.285633. Fixed-decimal metrics may round tiny values to zero; these values and inspection preserve magnitude.
All current settings remain active at every stage. RNN W_h=0.8, W_x=.5,b=0. LSTM f=σ(1); i=o=σ(10)=0.9999546021312976 (close to one); g=tanh(x). All LSTM recurrent weights and gate input weights are zero. No training.
Token 0, x=1. h_previous=0; z=0.8×0+.5×1=0.5; h=tanh(z)=0.46211715726000974.
What exactly returns to the next step?
The same parameters are reused. Inspect a real timestep, its token and its previous states; selection is not training.
Recurrent state
The numerical state passed between successive applications of the same cell.
Check this stage
Check your understanding
Inspect how tokens write recurrent states and how local Jacobians carry derivatives to the final hidden output. Compare that with the direct LSTM cell path.
What the experiment compares
The main curves differentiate final hidden output with respect to each input token, with a supplied output adjoint of one. The extra dotted curve differentiates final cell state along its direct cell route. These are different questions. Neither curve is a trained task score.
Both models receive the same editable active token prefix, length and initial hidden state. Tokens use indices ; state is initial, before token 0. After token , the state is . The RNN uses input weight , bias zero and the editable recurrent weight. The LSTM uses a candidate and has an extra initial cell state. These input maps are deliberately different, so this is an inspectable mechanism comparison, not identical functions or matched training performance.
Select a timestep in the graph or native selector. Its forward row, gate equation, local Jacobians, signed backward contributions and curve rings refer to that same token. Cell view follows the stage by default; choose single selected cell or unrolled explicitly to keep that view. Selecting a timestep does not run an optimiser.
Follow the RNN write and transport
The RNN computes
Its local state and input-write Jacobians are
With terminal and supplied , reverse mode gives and . A post-step hidden-state adjoint leaves out that token's write factor. An initial-state derivative additionally traverses the first recurrent factor. They are not interchangeable.
Try ten zero tokens with initial hidden state zero and . Every state remains zero and every tanh slope is one. The derivative to initial hidden state is ; the first-token derivative is . A recurrent weight above one can amplify. With a nonzero trajectory, saturation can instead make the tanh slope small. There is no global architectural maximum of 0.283; that number describes a sampled/default fixture for a different post-step quantity.
Retain, write, then expose
This lab deliberately isolates the forget mechanism. Every LSTM recurrent gate/candidate weight is zero. Gate input weights are zero; input and output biases are 10. The candidate has input weight one and bias zero:
The selected row separates retained contribution and written contribution , then prints the output transformation. Negative tokens can write negative values or cancel retained values. The two fixed gates are close to one, not exactly one. No gate is learned here: there is no loss, optimiser or training run.
Holding the independent coordinate fixed gives local . Multiplying later forget factors gives the direct route from a post-token cell to final cell. In this isolated experiment, the absent recurrent hidden paths make that route also the total cell-coordinate derivative at a state boundary. That simplification is not valid for all parameters supported by the general pure API.
Even here the token derivative includes at writing and at final hidden reading, as well as later forget factors. Repeated positive tokens can make the cell large and saturate its hidden readout while direct cell retention remains substantial. Retaining a cell contribution therefore guarantees neither output sensitivity nor useful task memory.
A three-token hand calculation
Choose LSTM, length three, tokens [1,0,0], initial h₀=c₀=0 and forget bias one. Here f≈0.731059 and i=o≈0.999955. At token 0, g≈0.761594, retained=0 and written≈0.761560, so c₁≈0.761560 and h₁≈0.641966. Token 1 writes zero: c₂=f c₁≈0.556745 and h₂≈0.505535. Token 2 also writes zero, giving c₃≈0.407013 and h₃≈0.385916.
The direct route after token 0 is f²≈0.534447. The first-token derivative to final hidden output additionally multiplies the candidate write and the final readout slopes, giving about 0.191005. Inspect those factors separately; the difference is computation, not a measured learning advantage.
The full two-state Jacobian
The inspection panel derives the general no-peephole scalar API, including nonzero recurrent gate weights. Write , , , , , and . Gates depend on through their own affine maps. Define
For independent boundary state order , rows are new coordinates and columns previous coordinates:
For , initialise and propagate . Token derivatives are . The live hidden-output experiment supplies ; the direct-cell curve declares a separate terminal . A forget product does not replace this matrix recurrence.
The boundary cell adjoint treats and as independent outputs of a completed cell. Inside that same cell, its internal cell-node adjoint is . This adds the readout fork once. The collapsed matrix already contains this fork: adding it again would double count it.
Parameters are a different derivative
The panel computes preactivation adjoints , , , . Each affine map contributes to its recurrent weight, to its input weight and to its bias. Sum every shared occurrence once. The RNN uses and the same affine rule.
Initial-state, token, internal-node, boundary-state and shared-parameter derivatives have distinct labels in raw inspection. These are derivatives of the declared terminal quantity. No parameter update is applied. Gradient magnitude, representational capacity, information retention, optimisation success and generalisation remain different questions. LSTMs can still exhibit vanishing, amplification, cancellation and saturation.
Read the display without losing the arithmetic
The vertical curve coordinate is . It removes sign; the raw ledgers and selected-step text retain it. Magnitudes below share a display floor of −12. The upper domain expands for amplification rather than clipping it. Straight segments only join discrete timestep values. Rings identify the inspected timestep. Signed h and c bars use zero as their baseline; gate bars show positive values. Compressed layouts omit node IDs instead of shrinking text; native inspection retains every identity. Graph edges indicate recurrence, not gradient magnitude.
The dashed horizontal line at is a chosen diagnostic. The trailing token count stops at the first value below that magnitude or nonfinite value; it is not a measured task-memory horizon. A small nonzero derivative is not proof of zero information, numerical failure or inability to learn. Readouts round; raw tables retain JavaScript doubles. Activation endpoint rounding and underflow can produce computed zeros, as can exact zero factors and cancellation; a zero alone does not identify its analytical cause. Nonfinite computations withhold model geometry/headlines and retain raw inspection.
Set forget bias to −3. Its gate is about 0.0474, small and positive. The nine later direct factors at length ten give about ; the past is heavily attenuated, not exactly erased. Load the small-forget preset, edit it, then Restore experiment to recover the complete preceding state. The challenge asks only for direct cell retention above 0.5 at length ten with LSTM selected. It does not certify hidden-output sensitivity or training success.
Keep and share the same experiment
Length changes compute only the active prefix while retaining the full ten-token buffer, including the inactive suffix. Earlier stages retain the chosen model, initial states and active mechanisms. Mathematical, stage and mode changes clear predictions; timestep, mechanism, view selection and opening inspection preserve them.
Share reproduces every token, setting, resolved inspection choice and display stage in guided mode, recomputing the same outputs. Guesses, recovery snapshots and local progress stay local. In-memory recovery additionally restores the original guided stage, sandbox and prediction after further edits. Reset restores defaults and all ten tokens, keeps the guided stage, returns guided and clears recovery and guesses. URL navigation clears recovery and guesses. There is no random-data action or playback clock for this bounded deterministic computation.
Sources
The original LSTM paper introduces the protected self-loop and access gates. Learning to Forget extends that mechanism with adaptive forgetting. Pascanu, Mikolov and Bengio analyse Jacobian transport and temporal parameter contributions. Deep Learning, chapter 10 connects those mechanisms to recurrent modelling and optimisation. Their training results are not results of this lab.
Stage recap
One cell, one loop
The same parameters are reused. Inspect a real timestep, its token and its previous states; selection is not training.
Unrolled in time
Token sensitivity includes the input-write Jacobian as well as transport through later steps. Inactive tokens stay in the retained buffer.
The vanishing gradient
The actual factor is (1−h²)W_h. On a zero-input, zero-state trajectory tanh has slope one; W_h above one amplifies. Saturation can instead attenuate it.
The LSTM cell
Compare token derivatives to final hidden output in both models. The extra direct-cell curve has a different terminal quantity c_last and is explicitly labelled.
The forget gate
No. The output gate and tanh(c) still affect the hidden readout. Gates are manually fixed here; there is no loss, optimiser or training.
Reference
- RNN
- h=tanh(W_h hprev + .5 x); b=0; J=(1−h²)W_h; K=(1−h²).5.
- LSTM gates
- q=σ(w_hq hprev+w_xq x+b_q) for f,i,o; g=tanh(w_hc hprev+w_xc x+b_c). No peepholes.
- Retain and write
- c=f cprev+i g; h=o tanh(c). Retained and written contributions sum before the readout.
- Isolation
- All recurrent LSTM weights zero; all gate input weights zero; i=o=σ(10)<1; g=tanh(x); f=σ(forget bias).
- Matched quantity
- Main curves d h_last/d x_k use same tokens, length, h₀ and upstream one, but different input maps. No fitted-performance claim.
- Direct route
- Product of later forget gates: d c_last/d c_k along the direct route. Not a general full-state derivative or token derivative.
- Full local J
- State order (h,c): [[a B+t O w_ho,a f],[B,f]], a=o(1−tanh(c)²), B=cprev F w_hf+g I w_hi+i G w_hc.
- Input write
- K=[a D+t O w_xo,D], D=cprev F w_xf+g I w_xi+i G w_xc; F=f(1−f), I=i(1−i), G=1−g², O=o(1−o).
- Reverse
- Boundary lambda_prev=Jᵀ lambda; dQ/dx=Kᵀ lambda. For Q=h_last supply (1,0); no computed loss or update.
- Shared parameters
- Sum local parameter contributions over every occurrence exactly once, using the same forward pass.
- Diagnostics
- 1e-3 is a chosen threshold. log10(abs) discards sign and floors at −12 for display; raw signed doubles remain in inspection.
- Limits
- Gradient size, information retention, capacity, optimisation and generalisation are distinct. LSTMs can still attenuate, amplify, cancel or saturate.
Break it on purpose
At forget bias −3 the gate is small and positive: σ(−3)≈0.0474. Direct cell retention shrinks rapidly; it is not exactly zero, mathematical memorylessness or proof that a task cannot be learned.
Explore next
- BackpropagationMultiply local Jacobians along each path; add contributions where a value feeds multiple paths.
- AttentionChange the attention weights and inspect how they blend the corresponding value vectors.
- Multi-Layer PerceptronNonlinear hidden features let an affine output separate patterns that one affine classifier cannot represent.