smartyfy.mrindigi.com

AI & Machine Learning Master Course — 125. LSTM and GRU sequence models

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 125: LSTM and GRU sequence models

Prerequisites: Lesson 124. Learning outcome: Explain gating and train a small sequence model where practical.

Gates make state updates more selective

A basic recurrent cell repeatedly transforms its entire state. Gated architectures introduce learned controls over what to retain, write, reset, or expose. The gate values typically come from sigmoids and lie between zero and one. They are continuous multipliers, not necessarily binary switches or interpretable decisions.

Gating can ease information retention, but does not guarantee unlimited memory. Saturation, sequence length, and training objectives still matter.

LSTMs and GRUs are related designs with different state structures. Their equations and gate conventions must be read carefully when moving between descriptions or libraries. In particular, an “update gate” may be defined as the weight on the old state in one notation and on the candidate state in another.

Trace the LSTM cell

A common LSTM maintains a cell state c and an exposed hidden state h. Its forget gate f controls retained cell content, input gate i controls a candidate g, and output gate o controls exposure. The central updates are c_t=f_t*c_previous+i_t*g_t and h_t=o_t*tanh(c_t), with elementwise multiplication.

If the forget gate is near one and the input gate near zero, cell content can persist. If the input gate opens, candidate content can be added. The output gate can hide some stored information without erasing the cell itself. Thus the cell and hidden states are different quantities, even when they have the same dimension.

Holding gates fixed for a local calculation, the direct derivative along the cell-state path is f_t. Ten successive forget gates equal to 0.9 give a direct-path factor of 0.9¹⁰, approximately 0.3487. Additional paths exist because learned gates can depend on earlier states, so this simplified product is not the whole network Jacobian.

State comparison

Common gated-state designs
Cell State Gates
LSTM Cell and hidden Input, forget, output
GRU Hidden Reset, update

Trace the GRU convention used here

A GRU maintains one main hidden state rather than a separate LSTM cell state. A reset gate affects how previous-state information enters a candidate. An update gate blends old state and candidate. We use the convention h_t=z_t*h_previous+(1−z_t)*candidate, matching the old-state weighting described in the cited PyTorch documentation.

Under this convention, z near one favors retention and z near zero favors replacement. Read the equation instead of relying on the word “update.” The exact placement of the reset gate relative to matrix multiplication can differ between formulations; that matters when reproducing a library’s weights or equations.

For an ordinary comparison, control parameter count or at least report it, keep data and optimization budgets explicit, and use development evidence. Fewer gate groups can reduce parameters for a given width, but runtime depends on implementation and hardware. Neither architecture is universally superior for every sequence task.

CPU lab: a fixed gated memory with a trained readout

The fictional sequence begins with either −1 or +1, followed by zeros. The target is the sign of that first value. We fix the GRU-style retention gate at 0.9 and use candidate tanh(x), equivalent to setting the candidate’s recurrent weight to zero. In this special case the reset gate has no effect. Only the final scalar classifier weight and bias are trained.

Eighty length-three training rows contain repeated copies of the two possible patterns. They are not eighty diverse independent language examples. A logistic readout is fitted for 800 full-batch steps. We then inspect the two possible patterns at lengths three and eight without changing parameters.

Length-three states are approximately ±0.061689, with positive-class probabilities 0.1561 and 0.8439. Length-eight states shrink to approximately ±0.036427, with probabilities 0.2696 and 0.7304. The signs remain separable, but scores move toward 0.5 as memory decays. This is a controlled mechanism check, not a broad generalization benchmark.

The NumPy code executes completely on CPU. It trains only two readout parameters, not the recurrent gates or an end-to-end LSTM/GRU. Framework equations were documentation-reviewed; PyTorch is absent and no PyTorch execution is claimed.

import numpy as np
# GRU convention: z weights the old state. Fixed gates, trained head only.
def feature(first, length):
    h = np.zeros_like(first, dtype=float)
    for t in range(length):
        x = first if t == 0 else np.zeros_like(first)
        candidate = np.tanh(x)  # recurrent candidate weight is zero
        h = .9 * h + .1 * candidate
    return h

first = np.tile([-1., 1.], 40)
y = (first > 0).astype(float)
h = feature(first, 3)
w = b = 0.
for _ in range(800):
    p = 1 / (1 + np.exp(-(w * h + b)))
    d = (p - y) / len(y)
    w -= 2 * np.sum(d * h)
    b -= 2 * np.sum(d)
for length in [3, 8]:
    values = feature(np.array([-1., 1.]), length)
    probabilities = 1 / (1 + np.exp(-(w * values + b)))
    print('Length', length, 'states', values.round(6).tolist(),
          'probabilities', probabilities.round(4).tolist())
    assert np.array_equal(probabilities >= .5, [False, True])
assert np.isclose(feature(np.array([1.]), 8)[0], .1 * np.tanh(1) * .9 ** 7)
print('Trained parameters: 2; recurrent gates fixed')

From a demonstration to a genuine sequence experiment

A stronger experiment would use varied sequences, distractors, held-out sources, and several lengths. Remembering a symbol and classifying natural text require different supervision and failure analysis.

If all gates are trainable, backpropagate through their sigmoid and candidate computations as well as through the state blend. Check gradients on tiny sequences before scaling. Keep state reset and padding rules from the previous lesson; gating does not remove those requirements. For a bidirectional gated model, verify that future context is legitimately available.

Evaluate by length and difficulty. Compare with a suitable baseline, and report whether recurrent parameters were learned, frozen, or hand-set.

Four practice questions with worked answers

Practice 1

An LSTM has previous cell 2, forget gate 0.75, input gate 0.2, and candidate −1. Find the new cell.

Answer: The retained contribution is 0.75×2=1.5 and the new contribution is 0.2×(−1)=−0.2. Their sum is 1.3. The hidden state additionally depends on the output gate and tanh.

Practice 2

Using this lesson’s GRU convention, let old state be 2, candidate be −1, and z=0.8. Find the new state.

Answer: The state is 0.8×2+0.2×(−1)=1.4. Because z weights the old state here, increasing z favors retention rather than replacement.

Practice 3

What remains after ten fixed retention multipliers of 0.9?

Answer: A starting contribution is multiplied by 0.9¹⁰≈0.348678. About 34.9 percent remains along this simplified direct path. This is not the total derivative of a fully learned gated network.

Practice 4

What was actually learned in the lab?

Answer: Only one readout weight and one bias. The retention gate and candidate construction were fixed. The experiment demonstrates gated state decay and readout fitting, not successful learning of a recurrent memory policy.

Five multiple-choice questions

Question 1

What is distinctive about a standard LSTM state?

  • A. It uses only a hidden state and no separate cell state.
  • B. It stores one independent parameter vector for every time step.
  • C. It separates a cell state from the exposed hidden state.

Correct: C. The cell and hidden state support different roles. A single main state is closer to a GRU, and recurrent parameters are shared over time.

Question 2

In h=z*old+(1−z)*candidate, what does z near one do?

  • A. Favor retention of the old state.
  • B. Force the hidden state to zero independently of both terms.
  • C. Favor replacement by the candidate.

Correct: A. The equation assigns nearly all weight to the old state. Reversing the gate convention would reverse this interpretation.

Question 3

Why is the reset gate irrelevant in the lab’s candidate?

  • A. The trained readout automatically absorbs every reset-gate effect.
  • B. The recurrent candidate weight is zero.
  • C. GRUs never include a reset mechanism.

Correct: B. The candidate depends only on the input in this construction. General GRUs can use reset-gated recurrent information.

Question 4

Which parameters are trained in the executed experiment?

  • A. The scalar output weight and bias only.
  • B. All recurrent gates and the output head.
  • C. The embedding table and four LSTM gate matrices.

Correct: A. The recurrence is fixed and the code updates only w and b. Other parameters are neither defined nor optimized in this lab.

Question 5

Why do longer zero-filled sequences move the output scores toward 0.5 here?

  • A. The readout is retrained with smaller weights at each evaluated length.
  • B. The sigmoid subtracts a fixed probability amount for each extra token.
  • C. Repeated retention below one shrinks the signed state magnitude.

Correct: C. The state decays geometrically while the target and shared recurrence remain unchanged. The fixed readout receives a smaller logit; sigmoid probabilities do not decrease by a fixed amount per step.

Common pitfalls

Do not reverse a gate convention, confuse LSTM cell and hidden states, count repeated toy patterns as broad data coverage, or describe a trained readout as end-to-end recurrent learning. Report exactly which parameters were updated.

Summary

Gates provide selective information flow through sequences. LSTMs separate stored cell content from exposed state; GRUs blend a candidate with prior state. Explicit equations, numerical checks, and honest training scope are essential for interpreting either architecture.

Primary sources and further reading