⚡ Recurrent Networks: RNN and LSTM from Scratch

Before the Transformer, sequences were read one token at a time by recurrent networks, and the book explains the wall they hit: in long sequences the information of the first tokens fades. This notebook writes an RNN and backpropagation through time with NumPy, measures how the gradient fades, and compares the RNN with the LSTM on a task where the network must remember a penicillin allergy across a growing number of words.

The interactive notebook includes:

  • The book's RNN equations applied step by step to the book's sentence.
  • A task that needs memory: the allergy at the start, the prescription at the end.
  • Backpropagation through time in NumPy, checked against PyTorch.
  • Training the RNN, with gradient clipping.
  • The gradient that fades on its way back through 40 words.
  • The LSTM and its forget, input and output gates.
  • How far each network remembers: RNN, LSTM and LSTM with the forget gate open from the start.

Want to modify the code and experiment on your own?
Open the notebook in Google Colab

Bibliography