1. Fundamental RNN Theory & Sequence Modeling

Why Standard Feedforward Networks Fail on Sequences (Slides 5–6)

A standard Multi-Layer Perceptron (MLP) cannot model sequences effectively due to four core structural flaws:

  1. Inability to handle variable-length sequences: MLPs require a fixed-dimensional input vector . Sequences in language or time series vary dynamically in length . Truncating or zero-padding forces arbitrary limits and wastes computation.
  2. Lack of parameter sharing across time: An MLP learns separate weights for each input index. If the model learns that "2009" is a temporal entity at position 2 (“In 2009, I went to Nepal”), it cannot transfer that knowledge to position 6 (“I went to Nepal in 2009”). It must relearn language rules independently at every temporal position.
  3. Loss of temporal ordering: Order carries crucial syntax and semantics. MLPs cannot intrinsically represent sequential precedence without ad-hoc positional encodings.
  4. Inability to retain long-term memory: Feedforward networks lack persistent internal states to hold context across arbitrary time delays.

The Dynamical System Perspective (Slides 12–17)

An RNN formalizes sequence processing by adapting the classical mathematical framework of a discrete-time dynamical system:

  • Autonomous (Isolated) Dynamical System: Information in this system does not grow; it decays or stays constant: .

  • Driven Dynamical System (Driven by External Signal ): Information in the hidden state is bounded by the joint information of the past state and the current input:


Unfolding the Computational Graph

By recursively substituting into :

  • The Core Invariance: Regardless of sequence length , the model maintains a constant number of parameters because transition function and weight matrices () are shared across all time steps.

2. Forward Propagation in Standard RNNs (Slide 20)

At each time step :

Weight Matrix Dimensions:

  • : Input-to-hidden weights
  • : Hidden-to-hidden recurrent weights
  • : Hidden-to-output weights
  • : Hidden bias vector
  • : Output bias vector

Sequence Loss Formulation (Slide 21)

For sequential classification, the total sequence loss is the sum of cross-entropy losses across all steps:

For sequential mean squared error (regression):


3. Keras SimpleRNN Parameter Calculations (Slides 27–28)

Given a SimpleRNN layer with:

  • = input feature dimension per time step
  • = number of hidden units (units)

The Master Parameter Formula:


Step-by-Step Code Example from Class Slides:

model = Sequential()
# Layer 1: 50 units, 1 input feature per timestep, full sequence output
model.add(SimpleRNN(50, input_shape=(None, 1), return_sequences=True))
model.add(Dropout(0.2))
 
# Layer 2: 100 units, 50 input features, vector output
model.add(SimpleRNN(100, return_sequences=False))
model.add(Dropout(0.2))
 
# Layer 3: Dense output regression
model.add(Dense(1))

Layer 1: SimpleRNN(50, input_shape=(None, 1))

  • Input weights ():
  • Recurrent weights ():
  • Biases ():
  • Total:
  • Output Shape: (None, None, 50) because return_sequences=True.

Layer 2: SimpleRNN(100, return_sequences=False)

  • (from Layer 1),
  • Input weights ():
  • Recurrent weights ():
  • Biases ():
  • Total:
  • Output Shape: (None, 100) because return_sequences=False (only the final time step is emitted).

Layer 3: Dense(1)

  • Weights:
  • Bias:
  • Total:
  • Output Shape: (None, 1)

4. Backpropagation Through Time (BPTT) Math (Slides 31–37)

Consider a 2-step unrolled network with squared loss:

Recall: .

              L1                          L2
              ▲                           ▲
              │                           │
              Y1                          Y2
              ▲                           ▲
              │ V                         │ V
  h0 ───W───► h1 ───────────W───────────► h2
              ▲                           ▲
              │ U                         │ U
              X1                          X2

Derivation of (Multi-Path Chain Rule)

influences the total loss through three distinct computational paths:

  1. Path to through :
  2. Direct path to through :
  3. Indirect path to through :

Evaluating each factor:

Combining all terms:


Derivation of and

Following the identical branching structure:


Derivation of and

Because and act independently on each time step without temporal recurrence:


5. Deep-Dive: Teacher Forcing (Slides 23–24, 38–40)


1. Structural Comparison: RNN A vs. RNN B (Slide 39)

        RNN A (Hidden-to-Hidden)                   RNN B (Output-to-Hidden)
                o^(t)                                      o^(t)
                ▲                                          ▲   │
                │ V                                        │ V │ W
      ... ──► h^(t) ────W────► ...               ...       h^(t)▼       ...
                ▲                                          ▲
                │ U                                        │ U
              x^(t)                                      x^(t)
  • RNN A (Hidden-to-Hidden Recurrence):
    • The hidden state serves as an internal memory buffer.
    • It can store arbitrary context from the past without committing to an immediate output.
    • It is Turing-complete, but computing gradients requires running Backpropagation Through Time sequentially across all time steps, which cannot be parallelized.
  • RNN B (Output-to-Hidden Recurrence):
    • The only link to the future is the output prediction (or ).
    • Strictly less powerful: Unless the output is exceptionally high-dimensional, it creates an information bottleneck. Hidden state cannot store private contextual clues that are not directly reflected in the output target.
    • Major Operational Benefit: Because time steps do not share direct hidden state recurrences, they can be completely decoupled during training using Teacher Forcing.

2. Mathematical Foundation: Maximum Likelihood Derivation (Slide 40)

Teacher Forcing is not a heuristic; it is derived from applying the Maximum Likelihood Criterion to conditional sequential models.

By the probability chain rule, the joint conditional likelihood of generating target sequence given inputs factorizes as:

Notice the second conditional term:

To maximize the true conditional log-likelihood during training, the conditioning input at time must be the true ground-truth label , not the model’s stochastic or inaccurate guess .


3. Training Graph vs. Inference Graph (Slide 40)

       TRAINING TIME (Teacher Forcing)                      TEST / INFERENCE TIME (Autoregressive)
             y^(t-1)         y^(t)                                o^(t-1)         o^(t)
              │   ▲           │   ▲                                ▲   │           ▲
              │   │           │   │                                │   │           │
              │   │ L^(t-1)   │   │ L^(t)                          │   └──┐        │
              │   │           │   │                                │      ▼        │
              │  o^(t-1)      │  o^(t)                            o^(t-1)─►h^(t)  o^(t)
              │   ▲           │   ▲                                ▲      ▲        ▲
           W  │   │ V         │   │ V                              │ V    │ U      │ V
     ─────────┘  h^(t-1)  ────┘  h^(t)                            h^(t-1) x^(t)   h^(t)
                  ▲               ▲                                ▲               ▲
                  │ U             │ U                              │ U             │ U
                 x^(t-1)         x^(t)                            x^(t-1)         x^(t)

During Training (Teacher Forcing Active):

  • At step , the recurrence input fed into hidden state is forced to be the ground truth target :
  • Full Parallelization: Because is already known from the training data, does not need to wait for step to compute its forward pass. All time steps can be processed simultaneously as independent feedforward examples in parallel.

During Testing / Inference (Teacher Forcing Inactive):

  • Ground-truth labels do not exist.
  • The network operates autoregressively: the model’s own predicted output (or ) is fed back into :
  • Processing is sequential; step must wait for step to produce an output.

4. Failure Mode: Exposure Bias (Compounding Errors)

While Teacher Forcing provides fast, stable training, it creates a fundamental train-test discrepancy known as Exposure Bias:

  • During training, the model is never exposed to its own errors. It only practices predicting the next step given an immaculate, perfect history.
  • At test time, if the network makes a small error at step , the hidden state is fed an out-of-distribution input. The model cannot recover from this unfamiliar state, causing errors to compound rapidly across subsequent steps, leading to degenerate or repetitive sequences.

5. Solutions to Exposure Bias

To resolve this discrepancy, training procedures mix ground truth with model predictions:

  1. Scheduled Sampling (Bengio et al.): During training, flip a coin at each time step with probability : starts at (pure teacher forcing) at the beginning of training and gradually decays toward (free running) as epochs progress.
  2. Beam Search at Inference: Instead of greedily picking at each step, maintain a beam of the top- most probable cumulative sequences to mitigate individual erroneous steps.
  3. Reinforcement Learning (Policy Gradient / Actor-Critic): Optimize sequence-level rewards (e.g., BLEU, ROUGE) directly using the model’s own rollouts.

6. The Long-Term Dependency Problem (Slides 51–56)

Mathematical Cause: Repeated Matrix Multiplication (Slide 52)

When an RNN is unfolded across steps, the gradient paths back to involve repeated products of the recurrent transition Jacobian:

Simplifying this on a linear path yields repeated powers of the recurrent weight matrix: .

Using the eigendecomposition :

  • If : as Exploding Gradients (leads to numerical overflows / NaN weights; mitigated by Gradient Clipping).
  • If : as Vanishing Gradients (the contribution of to the gradient at time step shrinks to zero; the network fails to learn long-range temporal associations).

Slide Solutions to the Vanishing Gradient Problem (Slides 53–56)

1. Leaky Units (Slide 55)

Instead of fully replacing the hidden state, introduce a linear self-connection controlled by parameter :

  • : Reverts to a standard, memoryless vanilla RNN.
  • : State is locked (), ignoring all new inputs.
  • Small : Gradients bypass non-linear saturations via the constant factor , preserving information over longer time horizons.

2. Temporal Skip Connections (Slide 54)

Construct recurrent connections spanning delays greater than : Gradients backpropagate in steps rather than steps, mitigating exponential decay.

3. Pruning Connections / Multi-Time Scales (Slide 56)

Actively remove length-1 connections and replace them with stride-2 or stride- connections: This forces different parts of the network to operate on distinct temporal resolutions (fine-grained vs. coarse-grained time scales).


7. Practice Exam Questions (RNN Focused)


Exam Question 1: Parameter Count & Multi-Layer RNN Pipeline

Problem

Consider the following Keras model:

model = Sequential()
model.add(SimpleRNN(64, input_shape=(None, 8), return_sequences=True))
model.add(SimpleRNN(32, return_sequences=False))
model.add(Dense(10, activation="softmax"))
  1. State the role and output shape of each layer.
  2. Derive and calculate the exact number of learnable parameters for each layer.
  3. What is the total number of learnable parameters in the entire network?

Solution

  • Layer 1: SimpleRNN(64, input_shape=(None, 8), return_sequences=True)

    • Role: Processes input sequences of 8-dimensional vectors. Emits full sequence of 64-dimensional hidden states.
    • Output Shape: (None, None, 64)
    • Parameters:
  • Layer 2: SimpleRNN(32, return_sequences=False)

    • Role: Takes sequence of 64-dimensional vectors from Layer 1; summarizes sequence into a single 32-dimensional context vector at the final time step.
    • Output Shape: (None, 32)
    • Parameters:
  • Layer 3: Dense(10, activation='softmax')

    • Role: Classifies the 32-dimensional summary vector into 10 class probabilities.
    • Output Shape: (None, 10)
    • Parameters:
  • Total Parameters in Network:


Exam Question 2: BPTT Derivation & Teacher Forcing Analysis

Problem

  1. Write down the gradient of the loss with respect to output bias and output matrix for an unrolled 2-step RNN:
  2. Explain why training an Output-to-Hidden recurrent network (RNN B) using Teacher Forcing eliminates the need for BPTT.
  3. What is the fundamental disadvantage of Teacher Forcing during test time?

Solution

  1. Gradients for and :

  2. Why Teacher Forcing eliminates BPTT in RNN B: In an Output-to-Hidden architecture under Teacher Forcing, the input fed into hidden state is the fixed, known training target : Because is a constant provided by the dataset rather than a function of the model’s parameters , there is no mathematical dependency of on . The computational graph splits into independent single-step feedforward networks. Gradients do not propagate backward across time steps, allowing training steps to run in parallel without BPTT.

  3. Disadvantage at Test Time (Exposure Bias): At test time, true labels are unavailable, forcing the model to rely on its own generated outputs . Because the network was trained exclusively on ground-truth inputs, errors at early inference steps push the hidden state into unfamiliar regions of the feature space, leading to compounding errors along the generated sequence.

Here is the complete, dedicated breakdown of Section 7: RNN Architectural Variants (from Slides 41–50 of your lecture), covering every variant, its computational graph structure, mathematical equations, pros/cons, and real-world applications.


8. RNN Architectural Variants (Slides 41–50)

Standard RNNs assume a causal, sequence-in to sequence-out mapping of identical lengths. In practice, sequence modeling requires several architectural variants:


1. Sequence Conditioned on Context (Slide 42)

  • Goal: Map a single, fixed-length context vector to a distribution over an output sequence .
  • Primary Application: Image Captioning (a single image feature vector is transformed into a natural language sentence describing the scene).

Three Ways to Provide the Context Vector :

  1. As the initial hidden state only:
  2. As an input at every single time step: (where is the context-to-hidden projection matrix).
  3. Both (as initial state AND recurrent input at every step): (Allows the network to continuously reference the original context image throughout sentence generation without forgetting it).

2. Bidirectional RNNs (BRNNs) (Slide 43)

       y^(t-1)                  y^(t)                  y^(t+1)
          ▲                       ▲                       ▲
          │                       │                       │
     ┌────┴────┐             ┌────┴────┐             ┌────┴────┐
     │  Output │             │  Output │             │  Output │
     └────▲────┘             └────▲────┘             └────▲────┘
       ┌──┴────────┬───────────┐  │  ┌────────────┬───────┴──┐
       │           │           │  │  │            │          │
  ... ─┼───────────┼──────────► g^(t-1) ◄─────────┼──────────┼─ ... (Backward)
       │           │              ▲               │          │
  ... ─┼──────────►h^(t-1)────────┼──────────────►h^(t)──────┼─ ... (Forward)
       │           ▲              │               ▲          │
       │           └──────────────┼───────────────┘          │
       ▲                          ▲                          ▲
     x^(t-1)                     x^(t)                     x^(t+1)
  • Motivation: Standard causal RNNs only capture the past (). In many offline sequence tasks, the meaning of a word at step depends on words that come after it.
    • Example: “I saw a bank … of the river” vs. “I saw a bank … robbery”.
  • Mechanism: Maintains two independent recurrent hidden layers:
    1. Forward RNN (): Reads sequence from left to right ():
    2. Backward RNN (): Reads sequence from right to left ():
  • Combined Output: Hidden states are concatenated at each step to produce the final prediction:
  • Use Cases: Speech recognition, protein structure prediction, handwriting recognition, machine translation encoding.
  • Limitation: Cannot be used for real-time / online streaming applications because the entire future sequence must be observed before computation can begin.

3. Sequence-to-Sequence (Seq2Seq / Encoder-Decoder) (Slides 44–47)

        ENCODER RNN                                         DECODER RNN
                                         Context C
   (x1)      (x2)      (x3)                 │            (y1)      (y2)      (y3)
    │         │         │                   │             ▲         ▲         ▲
    ▼         ▼         ▼                   ▼             │         │         │
  [h1] ───► [h2] ───► [h3] ─────────────► [ C ] ───────► [d1] ───► [d2] ───► [d3]
                                                          ▲         ▲         ▲
                                                          │         │         │
                                                        <SOS>      (y1)      (y2)
  • Motivation: Handles sequence tasks where input length and output length are different ().
  • Components:
    1. Encoder RNN:
      • Iterates over variable-length input sequence .
      • Generates a final hidden state that serves as the summary context vector:
    2. Decoder RNN:
      • Conditioned on the fixed context vector (either as initial hidden state , or fed at every step).
      • Autoregressively generates target sequence one element at a time until an end-of-sequence token "<EOS>" is emitted.
  • Use Cases: Machine translation (e.g., English to Thai), speech-to-text, question answering, text summarization.
  • Key Limitation (Slide 47): The Context Bottleneck. Forcing an entire sequence into a single, fixed-size vector creates an information bottleneck, causing performance to degrade sharply on long sentences.

4. Deep Recurrent Neural Networks (Stacked RNNs) (Slides 48–50)

Computation in an RNN occurs across three parameter blocks:

  1. Input-to-hidden ()
  2. Hidden-to-hidden ()
  3. Hidden-to-output ()

Introducing depth into each operation allows the model to learn hierarchical features across time.

       Hierarchical Stacking (Left)              Skip Connections (Right)
                 y^(t)                                    y^(t)
                   ▲                                        ▲
                   │                                        │
             ┌───────────┐                            ┌───────────┐
             │ Layer 2 h2│                            │ Layer 2 h2│◄──┐
             └─────▲─────┘                            └─────▲─────┘   │
                   │                                        │         │ (Skip)
             ┌─────┴─────┐                            ┌─────┴─────┐   │
             │ Layer 1 h1│                            │ Layer 1 h1├───┘
             └─────▲─────┘                            └─────▲─────┘
                   │                                        │
                 x^(t)                                    x^(t)

The Three Deep RNN Topologies (Slide 50):

1. Hierarchically Stacked Hidden States (Slide 50, Left)

  • Multiple recurrent layers stacked vertically on top of one another.
  • The output sequence of hidden layer becomes the input sequence to hidden layer :
  • Benefit: Lower recurrent layers extract low-level temporal features (e.g., phonemes/characters), while higher layers learn abstract temporal concepts (e.g., grammar/semantics).

2. Deep Feedforward Transitions within Steps (Slide 50, Middle)

  • Deep computation (e.g., an MLP with multiple non-linear layers) is placed inside the state transitions:
    • Deep input-to-hidden
    • Deep hidden-to-hidden
    • Deep hidden-to-output
  • Drawback: Greatly lengthens the path gradients must travel per time step, exacerbating the vanishing/exploding gradient problem and making optimization difficult.

3. Temporal & Hierarchical Skip Connections (Slide 50, Right)

  • Adds shortcut/residual connections across layers (e.g., feeding directly to , or connecting directly to output ).
  • Benefit: Mitigates the path-lengthening effect of deep architectures, giving gradients direct highways to propagate without vanishing.

Summary Comparison of Architectural Variants

ArchitectureInput Output MappingRecurrence DirectionTemporal Dimension MatchingCore Limitation / Trade-off
Context-ConditionedVector SequenceForwardMust preserve context across long generations
Bidirectional RNNSequence SequenceBoth ( and )Cannot run online/real-time (requires future inputs)
Seq2Seq (Encoder-Decoder)Sequence SequenceEncoder , Decoder (Arbitrary)Context vector forms an information bottleneck
Deep / Stacked RNNHierarchical layersForward per layerLayer-dependentHarder to optimize due to increased gradient path length