LSTM Networks: A Comprehensive Guide

human sleep cycle
Title: Human Sleep Cycle
Source: Simply Psychology website

Why You Should Still Care About LSTMs

Long Short-Term Memory (LSTM) networks can seem like relics of deep learning history in a time of Transformer architectures. After all, models like BERT and GPT have radically changed the field of artificial intelligence, attaining performance once thought unreachable across many tasks. Declaring LSTMs useless would be a mistake, though, because these flexible networks still handle important real-world problems in ways their more advanced successors cannot. From high-frequency trading systems analysing market data to medical devices tracking patient vital signs, they excel in time-critical applications where every millisecond matters, and their relatively low computational weight makes them a natural fit for edge computing and IoT devices where resources and power are limited.

Knowing LSTMs is therefore an investment in practical problem-solving, not just a study of history. Their design ideas still echo through modern architectures, and their handling of sequential data offers lessons for building hybrid solutions today. LSTMs are a reminder that as we push the limits of artificial intelligence with ever-larger Transformer models, the most efficient answer is not always the most complex one.

Let’s First Talk About Sleep

Sleep is your brain’s nightly maintenance routine, a dynamic blend of tidying up, recharging, and creative problem-solving. Far from being just a time of stillness, it’s an intricately orchestrated process where your body and mind collaborate, traveling through various stages to prepare you for the day ahead. Think of it as a magical journey, designed to ensure you’re at your best.

Sleep Cycle
Title: Sleep Cycle

The Three Acts of Sleep

Sleep unfolds in three distinct stages: light sleep, deep sleep, and Rapid Eye Movement (REM) sleep. The first two stages, collectively known as Non-Rapid Eye Movement (NREM) sleep, focus on recovery and repair. REM sleep, on the other hand, is the stage where your mind becomes a workshop for processing memories and igniting imagination. Let’s take a closer look at these stages:

Act 1: Light Sleep (NREM Stages 1 & 2)

Light sleep is your brain’s “decluttering” phase. During this stage, it filters out unnecessary or outdated memories like that awkward moment from a party years ago. By clearing mental clutter, your brain creates space for more relevant details, such as your grocery list or that catchy tune you just can’t stop humming.

Act 2: Deep Sleep (NREM Stage 3)

Deep sleep is like your brain’s data backup process. Here, short-term memories from the day are transferred into long-term storage, much like a computer saving vital information from its RAM to hard drive. This consolidation ensures the memories you need stay intact while less critical ones fade away.

Act 3: REM Sleep

REM sleep is your brain’s creative playground, a time for brainstorming and building connections. After clearing and consolidating during light and deep sleep, your brain uses REM sleep to synthesize new ideas by linking the old with the new. This stage fosters understanding, as your brain weaves fresh insights by forming and strengthening neural pathways.

LSTMs: A Fascinating Parallel

Long Short-Term Memory networks (LSTMs) are a type of artificial neural network designed to manage the flow of information in sequential data. Their structure includes three main gates: the Forget Gate, the Input Gate, and the Output Gate. Intriguingly, these gates mirror how your brain handles memories during sleep.

Here’s how they align:

  • Forget Gate → Light Sleep (NREM Stages 1 & 2): Filtering Out the Noise
    The Forget Gate discards irrelevant or outdated information, much like your brain during light sleep. Just as your mind filters out trivial details, like the color of a stranger’s shirt, this gate prepares the system for deeper processing.
  • Input Gate → REM Sleep: Learning and Integration
    The Input Gate decides which new information to store. Similarly, during REM sleep, your brain processes and integrates experiences, forming connections and sparking insights. This stage is akin to your brain’s creative epiphany phase.
  • Cell State (Memory Storage) → Deep Sleep (NREM Stage 3): Memory Consolidation
    In an LSTM, the Cell State retains critical information over time. Deep sleep serves a similar purpose, consolidating memories and locking in essential details for long-term use.
  • Output Gate → Waking Up: Applying What Matters
    The Output Gate selects the most relevant information to produce the LSTM’s output. When you wake up, your brain retrieves key insights and memories processed overnight, enabling you to tackle the day with clarity and purpose.
Side-by-side comparison mapping four stages of sleep to parts of an LSTM cell: light sleep to the forget gate, deep sleep to the cell state, REM sleep to the input gate, and waking up to the output gate.
Title: The sleep metaphor mapped to LSTM gates
Source: AIML.com Research

From Sleep to Sequential Processing

The metaphor of sleep isn’t just fascinating, it’s a practical way to understand LSTMs. Like sleep, LSTMs manage information systematically to optimize learning and memory.

RNNs (Recurrent Neural Networks) are well-suited for processing sequential data, retaining context from one step to the next. However, they struggle with long-term dependencies, often “forgetting” crucial details from many steps earlier, a limitation known as the vanishing gradient problem.

LSTMs address this by introducing a sophisticated memory management system that mimics the brain’s approach during sleep. By retaining vital information and selectively forgetting the rest, LSTMs are uniquely equipped to capture long-term relationships in sequential data.

Now that we’ve drawn the parallels between sleep and LSTMs, let’s delve into the inner workings of these remarkable networks and explore how they overcome the challenges of traditional RNNs.

Recurrent Neural Networks

Before diving into LSTM, we need to understand RNN first. Recurrent Neural Networks (RNNs) represent a fundamental shift in handling sequential data. Think of reading a book, as you read each word, you don’t start fresh; you remember what you read before to understand the current context. This is exactly how RNNs work! 

Recurrent Neural Network(RNN) explained using an example.
Title: Explaining Recurrent Neural Network (RNN) using an example
Source: Stanford NLP Course

Key Features of RNNs

  • Sequential Processing: Unlike traditional feedforward neural networks, RNNs are designed to process input sequences one element at a time while maintaining a memory of the past through hidden states.
  • Shared Weights: RNNs use the same set of weights across all time steps, allowing them to model temporal dependencies.
  • Feedback Loops: They introduce feedback connections, which enable information to cycle through the network, making it suitable for tasks involving sequential data.

Example: Speech Recognition

In a task like speech recognition, where we analyze a sentence such as, “The sky has floating clouds”:

  1. When the RNN processes the first word, “The,” it initializes its understanding.
  2. As it moves to “sky,” the network doesn’t start over but builds on the context from “The.”
  3. By the time it reaches “clouds,” the RNN leverages the cumulative information from all the previous words to derive meaning and context.

This ability to retain context makes RNNs a powerful tool for various applications like language modeling, machine translation, and time-series forecasting.

Drawbacks of RNN

  1. Memory Fade (Short-Term Memory Challenges)
    RNNs often struggle to retain information from the distant past, especially as sequence lengths increase.

    Why It Happens: As RNNs process sequential data, they repeatedly apply the same weights across many time steps. Over time, the influence of earlier information diminishes, effectively causing the model to “forget” it.

    Impact: This makes it difficult for RNNs to capture long-range dependencies, such as identifying the antecedent of a pronoun that was mentioned several sentences earlier.

  1. Learning Difficulties (Vanishing and Exploding Gradients)
    RNNs face significant challenges during training due to issues inherent in the backpropagation through time (BPTT) algorithm. These problems, vanishing and exploding gradients, can severely limit the network’s performance.

A Simple Example

  • Sentence 1: Amy bought an apple today, and the __ is so sweet.
  • Sentence 2: Amy bought an apple today. And when she was in the store, she met Alex and said hi. After she took a bite, she said, “The __ is so sweet!”

As humans, we can easily infer that both blanks should be filled with apple. However, RNNs are more likely to correctly predict the blank in Sentence 1 than in Sentence 2 because the dependency in Sentence 2 spans a much longer sequence.

Vanishing Gradient Problem

What Happens:
As the loss function gradients are propagated backward through many time steps, they become exceedingly small. This phenomenon prevents the model from effectively updating weights associated with earlier time steps.

Impact:
The network struggles to learn long-term dependencies. For example, when predicting the next word in a sentence, it might fail to remember a critical word mentioned earlier, leading to inaccurate predictions.

vanishing-and-exploding-gradient-1
Title: Vanishing and Exploding Gradient Problem
Source: SuperAnnotate

Exploding Gradient Problem

What Happens:
In some cases, gradients grow uncontrollably large during backpropagation through long sequences. This results in numerical instability and can cause the training process to diverge entirely.

Why It Happens:
When weights are repeatedly multiplied over many time steps, they can exponentially increase, creating instability in the optimization process.

By addressing these issues, modern architectures like LSTMs and GRUs were developed to overcome the limitations of traditional RNNs, enabling more effective learning of long-term dependencies.

LSTM: An Introduction

RNNs are typically limited in their ability to look back more than approximately ten timesteps. This limitation arises from the challenges of vanishing or exploding gradients, which hinder their ability to retain information over longer sequences.

In contrast, LSTMs (Long Short-Term Memory networks) are designed to overcome these limitations, capable of learning dependencies spanning over 1,000 timesteps. As their name suggests, LSTMs excel at managing both long-term and short-term memory through a sophisticated memory mechanism.

If traditional RNNs can be compared to a learner who relies solely on rote memorization, LSTMs are like a smarter learner who can discern what’s important and what’s not. Imagine LSTMs working with a notepad for long-term memory and sticky notes for short-term memory, enabling them to efficiently organize and prioritize information over time.

Side-by-side comparison of a recurrent neural network and an LSTM unrolled over three time steps, where the RNN passes a single densely connected hidden state forward while the LSTM maintains a separate cell state line for long-term memory alongside its hidden state and output at each step.
Title: Comparing the structure of an RNN and an LSTM across time steps

A key feature of LSTMs is their ability to control the flow of information through a combination of gates. Each gate uses specific activation functions to decide how much information to retain or discard. Two essential activation functions in LSTMs are the sigmoid and tanh functions. You can think of the sigmoid as a filter and the tanh as a mapping. Imagine a box: first, we create a filter (sigmoid) to determine which parts of the information to keep, and then we pass everything through the box (tanh) to map the values to an appropriate range. By multiplying the outputs of the sigmoid and tanh, we obtain the exact information we need. In fact, the core steps of LSTMs frequently involve the multiplication of a sigmoid and a tanh. We will explore these steps in more detail later.

Activation functions compared
Title: Comparison of common activation functions
Source: Article by Binay Dhakal on Medium

Sigmoid Function

The sigmoid function, defined as $σ(x)=\frac{1}{1 + e^{-x}}$​, is a nonlinear activation function that maps input values to a range between 0 and 1. This makes it ideal for gates in LSTMs, as it can represent probabilities or the extent to which information should be retained or forgotten.

In LSTMs, the sigmoid function is used in:

  • Forget Gate: Determines how much of the past information should be forgotten.
  • Input Gate: Decides how much new information should be written to the cell state.
  • Output Gate: Controls the extent of information to output from the cell state.

The sigmoid function’s bounded range ensures smooth and gradual updates to the network’s state, preventing abrupt changes and aiding in stable learning.

Tanh Function

The hyperbolic tangent function, or tanh, is defined as $tanh(x)= \frac{e^x – e^{-x}}{e^x + e^{-x}}$​. It maps input values to a range between -1 and 1, offering both positive and negative outputs. This symmetric range makes tanh suitable for capturing and representing values with polarity, such as temporal patterns in sequential data.

In LSTMs, the tanh function is primarily used to:

  • Regulate the candidate values that could be added to the cell state.
  • Scale the final output of the cell, ensuring balanced propagation of information with gradients that remain within a manageable range.

The combination of sigmoid and tanh functions allows LSTMs to effectively balance memory retention and information flow, ensuring they can learn and model long-term dependencies in complex datasets.

Cell State

The cell state in LSTMs acts like the memory of the network. It is designed to store important details for a long time while deciding what to keep and what to remove. Here’s how it works:

  1. Long-Term Memory Path:
    The cell state provides a clear path for information to flow without being changed too much. This helps the network remember patterns from far in the past, solving the problem of “forgetting” that happens in simpler networks like basic RNNs.
  1. Protected Memory:
    Think of the cell state as a well-guarded memory box. Instead of rewriting everything at each step, the LSTM carefully decides what to keep and what to remove. This means the important stuff stays safe, and the less important stuff gets thrown away.
  1. Smart Updates:
    The cell state uses “gates” to decide how to handle information. For example, the forget gate throws away details that are no longer useful. The input gate adds new, important details to the memory. By balancing these actions, the LSTM keeps the information it needs while ignoring unnecessary noise.

This combination of memory and smart updates allows LSTMs to handle tasks like understanding language or predicting time-series data, where remembering long-term patterns is really important.

Diagram of a single LSTM cell showing the cell state running along the top as long-term memory and the hidden state along the bottom, with the forget, input, and output gates feeding into pointwise multiply and add operations that update the memory.
Title: Anatomy of an LSTM cell
Source: AIML.com Research

Forget Gate: Deciding What to Let Go

Mathematically, the forget gate is expressed as:

The forget gate determines which parts of the existing memory (cell state) are no longer useful and should be discarded. Think of it as a filter that sifts through the memory, keeping what’s relevant and removing the rest.

$$f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)$$

$Where:$
$f_t$: Output of the forget gate, a vector indicating what to forget
$W_f$: Weight matrix for the forget gate.
$h_{t-1}$: Previous hidden state.
$x_t$​: Current input.
$b_f$​: Bias vector
$h_{t-1}$, $x_t$ : Concatenation of the previous hidden state and current input.
$\sigma$: Sigmoid activation function, which maps values to [0,1].

How it works

The forget gate outputs values between 0 and 1:

  • 0 means “completely forget this information.”
  • 1 means “retain this information entirely.”

Example

Imagine you’re reading a novel. The forget gate might:

  • Keep gender information like “she” or “he” to ensure pronouns are used correctly.
  • Forget temporary details, like a character’s brief description, that don’t affect the story.
  • Reset information when a new chapter or topic begins.

This selective forgetting helps the model focus on what matters most for future processing.

LSTM cell diagram with the forget gate highlighted, showing how it multiplies the previous cell state to decide what information to erase before new information is added.
Title: The forget gate within an LSTM cell
Source: AIML.com Research

Input Gate: Deciding What to Remember

The input gate decides what new information should be added to the memory and how it should be incorporated. It involves two components:

  1. Determining which parts of the input are significant.
  2. Generating candidate updates for the memory.

The formulas are:

$$i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i) \quad \text{(Input gate activation)}$$
$$\tilde{C}_t = \tanh(W_c \cdot [h_{t-1}, x_t] + b_c) \quad \text{(Candidate values)}$$

$Where:$
$i_t​$: Controls which new information to store
$\tilde{C}_t$: Candidate values for updating the memory, scaled to [−1,1]
$\tanh$: Hyperbolic tangent function that scales values to [−1,1]

The updated cell state combines these:

$$C_t​=f_t​∗C_{t−1}​+i_t​∗\tilde{C}_t​$$

$Where:$

$f_t​∗C_{t−1}​$: Keeps relevant past information.

$i_t​∗\tilde{C}_t​$:  Adds new significant information.


An Example: Reading that same novel, the input gate is what writes a newly introduced character’s name into memory so it is available later.

LSTM cell diagram with the input gate highlighted, showing how it uses a sigmoid and a tanh to decide which new information is written into the cell state.
Title: The input gate within an LSTM cell
Source: AIML.com Research

Output Gate: Deciding What to Share

The output gate determines what information from the cell state should be shared with the next layer or used for generating outputs. It selects and regulates the relevant details to expose.

The formulas are:

$$o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o) \quad \text{(Output gate activation)}$$
$$h_t = o_t \ast \tanh(C_t) \quad \text{(Final output)}$$

$Where:$
$o_t​$: Controls what information to reveal from the memory
$\tanh(C_t)$: Scales the cell state values to [−1,1], ensuring they are manageable
$h_t$: Final output and updated hidden state

How It Works

  1. The output gate examines the current input and the previous hidden state.
  2. The sigmoid function determines which parts of the memory to share.
  3. The tanh function scales the memory values.
  4. These components are combined to produce the final output.

Example: Continuing the novel, the output gate is what surfaces the character’s gender at the moment a pronoun needs to agree with it.

LSTM cell diagram with the output gate highlighted, showing how it filters the cell state through a tanh to produce the hidden state output for the current step.
Title: The output gate within an LSTM cell
Source: AIML.com Research

Gate Interactions

The three gates in an LSTM work together to manage the flow of information, which is what lets the network handle tasks like language modeling, time-series prediction, and sequence-to-sequence learning:

  • Forget gate: This gate determines which information from the previous cell state is no longer relevant and should be discarded. For example, in a sequence processing task, it might remove outdated details about earlier parts of a sentence that are no longer needed for understanding the current context. By selectively forgetting, the LSTM prevents its memory from becoming cluttered with irrelevant data.
  • Input gate: This gate is responsible for updating the cell state with new, important information. It evaluates the significance of the incoming data and decides what should be added to the memory. For instance, when encountering a key piece of information in a text, the input gate ensures it is integrated into the memory while ignoring less critical details.
  • Output gate: The output gate extracts relevant parts of the internal state and makes them available for the current task. It decides which aspects of the updated memory are most useful for generating outputs, such as predicting the next word in a sequence or maintaining agreement in a sentence.

Example: How the Gates Coordinate

Consider the sentence: “The dog, which loves to play, is running…”. Here’s how the gates in an LSTM process this information:

  • Forget gate: Retains the essential subject “dog” while discarding irrelevant details from previous context.
  • Input gate: Updates the memory by recognizing that the sentence has entered a relative clause, storing the information “loves to play.”
  • Output gate: Ensures that “dog” remains accessible for tasks like maintaining agreement with the verb “is running” later in the sentence.

This coordination allows the LSTM to handle complex structures, ensuring important information is preserved while adapting to new inputs.

Go deeper into LSTM

The Constant Error Carousel (CEC) is a fundamental component of Long Short-Term Memory (LSTM) networks, designed to address the vanishing gradient problem in traditional Recurrent Neural Networks (RNNs). The vanishing gradient problem hampers the training of RNNs over long sequences because gradients diminish exponentially as they are backpropagated through time, making it difficult for the network to learn long-term dependencies.

Why Does RNN Suffer from Gradient Explosion or Vanishing?

The Gradient Propagation Formula

In RNNs, errors propagate backward through time from the output layer to the hidden layers. The key point is that the gradient at the current time step depends on the gradients from all previous time steps.

The gradient propagation formula for RNNs can be simplified as:

\[ \frac{\partial E}{\partial W} = \sum_{t} \left( \prod_{\tau=1}^t W \cdot f'(z_\tau) \right) \cdot x_t \] where \[ \begin{aligned} E &:\ \text{Loss function}, \\ W &:\ \text{Weight matrix connecting hidden layers}, \\ f'(z_\tau) &:\ \text{Derivative of the activation function, , reflecting the non-linear impact}, \\ x_t &:\ \text{Input signal} \end{aligned} \]

Looking at this formula, the key part is the product term inside the sum. To send an error signal from the current step all the way back to an earlier one, the network multiplies the same weight matrix and the same activation derivative together once for every step in between. A sequence of fifty steps means roughly fifty of these terms multiplied in a chain.

Two Ways the Gradient Breaks Down

That repeated multiplication is the whole problem, and it can go wrong in two opposite directions:

  • Vanishing gradients: when each term in the chain is a little less than one, multiplying many of them together drives the result toward zero. The error signal fades as it travels backward, so the weights tied to earlier steps barely move during training. The network effectively cannot learn from anything that happened long ago, which is the memory-fade limitation described earlier.
  • Exploding gradients: when each term is a little more than one, the same multiplication drives the result toward infinity. The error signal grows out of control as it travels back, the weight updates become huge, and training destabilises or breaks entirely.

Either way, the root cause is the same: an error has to survive being multiplied through the full length of the sequence, and a long chain of multiplications rarely stays near a usable size. This is precisely the obstacle the Constant Error Carousel was designed to remove. Instead of forcing the error through that repeated multiplication, the LSTM gives it a protected path along the cell state where it can flow backward largely unchanged. The sections below work through why the problem happens in detail and how the carousel keeps the gradient stable.

Why Gradient Explosion or Vanishing Occurs

  • The product of repeated weight matrices and activation derivatives causes the issue:
    • Explosion: If |W| > 1 → $$\prod_{\tau=1}^t W \to \infty$$
    • Vanishing: If |W| < 1 → $$\prod_{\tau=1}^t W \to 0$$

How to Solve Gradient Explosion and Vanishing?

  • Gradient Clipping: Caps the gradient to prevent explosion.
  • LSTM + Constant Error Carousel: Stabilizes gradient flow through the memory cell.

How Does CEC Solve the Problem?

  • Memory Cell: LSTM maintains a memory cell updated with gated mechanisms:

$$c_t = f_t \ast c_{t-1} + i_t \ast \tilde{C}_t$$

  • The memory cell allows direct information flow, unaffected by vanishing/exploding gradients.
  • Gradient Stability: CEC aims to keep the following product approximately stable:

$$\left|\prod_{\tau=1}^t f'(z_\tau) \cdot W \right| \approx 1$$

  • This avoids exponential growth or decay of gradients over time.
Line chart showing gradient strength across time steps, where the plain RNN curve decays toward zero as the signal vanishes while the LSTM with the Constant Error Carousel stays stable across many steps.
Title: Gradient flow in a plain RNN versus an LSTM with the Constant Error Carousel
Source: AIML.com Research

Development and Evolution

  • Origins: LSTM was developed to address the limitations of traditional Recurrent Neural Networks (RNNs), specifically the vanishing gradient problem that hindered learning long-term dependencies. The original LSTM architecture included cells, input gates, and output gates to manage information flow.
  • Enhancements: In 1999, Felix Gers and colleagues introduced the forget gate, enabling LSTM networks to reset their state, which is now a standard component of LSTM architectures. Subsequent improvements included peephole connections, allowing gates to access cell state information directly.

Variants of LSTM

  • Peephole LSTM: Introduced by Gers et al. in 2000, this variant allows gates to access the cell state directly, enhancing the network’s ability to learn precise timing.
  • Bidirectional LSTM (BiLSTM): This architecture processes data in both forward and backward directions, capturing context from both past and future states, which is particularly beneficial in tasks like speech recognition and handwriting recognition.
  • Gated Recurrent Unit (GRU): Proposed by Kyunghyun Cho et al. in 2014, GRU is a simplified version of LSTM that combines the cell state and hidden state and merges the forget and input gates into a single update gate, reducing complexity while maintaining performance.
  • SLIM LSTMs: These are simplified LSTM variants that remove certain components to speed up training and runtime with minimal performance loss. Studies have shown that some SLIM LSTM layers can perform comparably to standard LSTM layers in specific architectures.

Video Explanations

  • In this video, “What is LSTM (Long Short Term Memory)?”, presented by Martin Keen of IBM, a lightboard walkthrough explains why LSTMs are needed to handle long-term dependencies, how the cell state and its gates pass relevant information along a sequence chain, and where LSTMs are used in practice. (Watch time: ~8 mins)
YouTube video
LSTM explained By IBM Technology
  • In this video, “Long Short-Term Memory (LSTM), Clearly Explained”, presented by Josh Starmer of StatQuest, LSTMs are built up step by step from the limitations of a basic recurrent network, working through the sigmoid and tanh activation functions and then the three stages of the cell: deciding what percentage of the long-term memory to keep, updating the long-term memory, and updating the short-term memory. (Watch time: ~21 mins)
YouTube video
CNNs,RNNs,LSTMs, and Transformers By Roboflow

Authors

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Partner Ad
Find out all the ways that you can
Contribute