AI & Machine Learning Master Course — 124. Recurrent neural networks
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 124: Recurrent neural networks
Prerequisites: Lesson 123. Learning outcome: Trace hidden-state sequence processing and its training challenges.
Carry information through a sequence
A recurrent neural network processes an ordered sequence while maintaining a hidden state. At step t, a simple tanh cell computes h_t=tanh(W_x x_t+W_h h_previous+b). The same parameters are reused at every step. The state is a learned numerical summary, not a literal copy of every earlier token.
Parameter sharing lets one cell operate across different sequence lengths. It does not mean that a model trained on short sequences automatically succeeds on longer ones. Repeated transformations can forget information, amplify unstable behavior, or encounter distributions absent from training.
For sequence classification, a head may use the final valid hidden state. For per-token labeling, a head can produce an output at every valid position. For next-token prediction, the state summarizes the available prefix. Choose the output arrangement according to the task rather than forcing every sequence problem into a single final label.
Order matters, and so do state boundaries
Because each step depends on the previous state, changing input order generally changes the result. That addresses a limitation of bag-of-words and simple mean pooling. It also makes the handling of boundaries important. Independent documents should normally start with a reset state; accidentally carrying state between unrelated documents leaks information and makes predictions depend on processing order.
Batches often contain different lengths. Padding fills array positions, but padded values should not overwrite the final valid state used for a document’s prediction. Use lengths or an appropriate masking/packing mechanism. In streaming tasks, carrying state across successive chunks of the same sequence can be intentional, but the ownership and reset policy must be explicit.
A bidirectional RNN reads both directions and combines their information. That is useful when the full sequence is available, such as offline document labeling. It is inappropriate to use future tokens for a real-time prediction that must be made before those tokens arrive. Architectural convenience does not change the information available at prediction time.
Backpropagation through time is shared-weight differentiation
Unroll the recurrence conceptually into a chain of steps. Backpropagation carries derivatives backward through that chain. Since the same recurrent weights appear at multiple steps, their gradient is the sum of contributions from every use. Treating each step’s copy as an unrelated parameter would train a different model.
For a scalar tanh state, the derivative with respect to its preactivation is 1−h_t². The gradient arriving at the previous state is multiplied by that derivative and by the recurrent weight. Repeated factors with magnitude below one can shrink signals; repeated large effective factors can amplify them. Vector models involve products of Jacobians, so one scalar rule does not fully characterize every network.
Gradient clipping can limit very large gradients before an update. It does not restore information already lost through vanishing gradients. Truncated backpropagation limits how many steps receive credit across a boundary, reducing computation and memory while changing the learning signal. Carrying a hidden value forward and detaching its history are separate operations.
CPU lab: check a three-step recurrent gradient
The scalar inputs are [1,0,−1], the input weight is 0.5, the recurrent weight is 0.8, and the initial state is zero. The target for the final state is 0.2. Loss is half the squared final-state error. No output layer or bias is included in this minimal demonstration.
The hidden states are approximately [0.462117,0.353724,−0.213677]. Starting from the final error, the reverse loop accumulates derivatives for both shared weights. The resulting gradients are approximately 0.220944 for the input weight and −0.267336 for the recurrent weight.
Central finite differences independently perturb each weight by 0.000001 and recompute the complete forward loss. The analytic and numerical gradients agree within the stated tolerance. This executes the recurrence and its gradient on CPU; it does not train a language model or demonstrate long-sequence generalization. PyTorch documentation is a reference for framework conventions, but PyTorch is absent and no framework code is executed.
import numpy as np
x = np.array([1., 0., -1.])
wx, wh, target = .5, .8, .2
def loss(a, b):
h = 0.
for value in x:
h = np.tanh(a * value + b * h)
return .5 * (h - target) ** 2
states = [0.]
for value in x:
states.append(float(np.tanh(wx * value + wh * states[-1])))
dh = states[-1] - target
gwx = gwh = 0.
for t in range(len(x) - 1, -1, -1):
dz = dh * (1 - states[t + 1] ** 2)
gwx += dz * x[t]
gwh += dz * states[t]
dh = dz * wh
step = 1e-6
numeric = [(loss(wx + step, wh) - loss(wx - step, wh)) / (2 * step),
(loss(wx, wh + step) - loss(wx, wh - step)) / (2 * step)]
print('Hidden states:', np.round(states[1:], 6).tolist())
print('Gradients wx / wh:', np.round([gwx, gwh], 6).tolist())
assert np.allclose([gwx, gwh], numeric, atol=1e-8)
print('Finite-difference gradient check:', True)
Shape contracts and practical diagnostics
For batched vector inputs, common axes are batch, sequence length, and feature dimension, though frameworks differ in their defaults. Hidden-state tensors may arrange layers and directions separately. Write down each axis rather than inferring its meaning from a shape that happens to multiply successfully.
First overfit a few short training sequences, verify state resets, and compare masked versus unpadded processing. Then inspect gradient norms and performance by sequence length. An aggregate score can hide complete failure on long documents. Compare with a simpler lexical baseline; order sensitivity is useful only if the task benefits from it and the model learns to use it.
For online use, evaluate chronological prefixes and respect label delays. For independent-document classification, group related documents before splitting. The presence of a recurrent state makes boundary discipline especially important, but it does not replace the ordinary rules of independent evaluation.
Four practice questions with worked answers
Practice 1
With x=1, previous state zero, input weight 0.5, and zero bias, find the next state.
Answer: The preactivation is 0.5 and tanh(0.5) is approximately 0.462117. The recurrent weight contributes nothing at this step because the previous state is zero.
Practice 2
Why are recurrent-weight gradient contributions summed across steps?
Answer: The same parameter participates in every recurrence. The chain rule accumulates all paths through which that shared parameter affects the loss. Updating independent copies would remove the intended weight sharing.
Practice 3
A padded batch uses the state after ten positions for every document, including a three-token document. What may go wrong?
Answer: Seven padding updates can change its state after its real content ended. Use the final valid state or a correct masking/packing scheme so batching artifacts do not redefine the document representation.
Practice 4
Does clipping large gradients solve vanishing gradients?
Answer: No. Clipping constrains overly large update signals. It does not increase derivatives that have already shrunk through repeated recurrence, so the two problems require distinct reasoning.
Five multiple-choice questions
Question 1
What is shared across time in a basic RNN?
- A. An identical hidden-state value at every step.
- B. An independent set of weights for each possible sequence position.
- C. The input and recurrent transformation parameters.
Correct: C. States change with inputs and history, while the parameters defining the recurrence are reused.
Question 2
What must be reset between independent documents unless a different protocol is intentional?
- A. The trained weight matrices.
- B. The carried hidden state.
- C. The vocabulary ID mapping.
Correct: B. Resetting state prevents unrelated document history from affecting predictions. Weights and vocabulary remain part of the fitted model.
Question 3
Which use of a bidirectional RNN violates an online next-step setting?
- A. Using future sequence elements that are unavailable when the prediction is needed.
- B. Using earlier observed tokens in the forward state.
- C. Resetting the state at the beginning of an independent sequence.
Correct: A. Future information changes the task’s information boundary. Earlier observations and appropriate resets are compatible with online prediction.
Question 4
What does the lab’s finite-difference test verify?
- A. The chosen weights minimize the loss globally.
- B. The two analytic gradients match local numerical loss derivatives.
- C. The recurrent model will remember arbitrarily long sequences.
Correct: B. Gradient agreement validates this local derivative computation. It does not establish memory capacity or optimality.
Question 5
What changes with truncated backpropagation?
- A. Shared recurrent weights become independent parameters for each chunk.
- B. The forward hidden-state value must always be replaced by zero at every boundary.
- C. Credit assignment is limited across the chosen history boundary.
Correct: C. Truncation restricts derivative history. State can still be carried forward, and recurrent parameters remain shared.
Common pitfalls
Avoid state leakage across documents, reading padded states as valid final states, using unavailable future context, or claiming that gradient clipping fixes all recurrent training problems. Check a tiny recurrence numerically before debugging a large sequence model.
Summary
RNNs create order-sensitive representations through shared recurrent transformations. Their training is ordinary chain-rule differentiation across time, with special attention to state boundaries, valid sequence lengths, and the stability of long gradient paths.