Zero Labs
Industry News / AI

Vanishing and Exploding Gradient

Source · Towards AI By Mohit Tayal

From the publisher’s feed, collected in the ZeroLabs newsroom.

If you’ve ever tried to train a deep neural network and watched the loss stay flat no matter how long you waited, you’ve likely met the twin villains of deep learning: Vanishing and Exploding Gradients.Analogy:Imagine making a photocopy of a photocopy. With each new copy, the image gets a little fainter until it’s just a blurry mess. This is exactly what happens with vanishing gradients.Now, imagine the opposite. What if you shouted into a canyon and the echo came back louder each time? Soon, you’d have a deafening, chaotic roar. This is an exploding gradient.What We’ll Cover in This Post:The Origin of the Problem: How early activation functions like Sigmoid and Tanh accidentally created the vanishing gradient crisis.ReLU to the Rescue: Why the ReLU activation function became the new standard, and how it introduced its own set of challenges like exploding gradients and “dying neurons.”Why RNNs Suffer the Most: A deep dive into why these gradient issues are particularly brutal for Recurrent Neural Networks, making it hard for them to remember long-term patterns.The Practical Fixes: A look at the essential toolkit for stabilizing training, including Gradient Clipping, Weight Initialization, and smarter architectures.How LSTMs Solved the Memory Problem: Unpacking the magic of LSTMs, with their “cell states” and “gates” that act like a memory superhighway.The Transformer’s Edge: Understanding how modern Transformers use Residual Connections and Layer Normalization to effectively conquer gradient problems.The Origin Story: Sigmoid & TanhIn the early days of neural networks, we needed functions to introduce non-linearity (so the network could learn complex patterns) and to keep the numbers stable so they didn’t explode into infinity.We used Sigmoid and Tanh:Sigmoid: Squishes any input number into a range between 0 and 1.Tanh: Squishes any input number into a range between -1 and 1.They look like smooth ‘S’ curves. While they are great at keeping numbers bounded, this is a major issue when it comes to calculus.Look at the slope (derivative) of the Sigmoid and Tanh functions in below graph:So if a neuron is often in saturation, its gradient contribution becomes tiny.This is known as the vanishing gradient problem.So, what is the issue with the Vanishing Gradient:When Backpropagation happens, if the gradient is too small, the earlier layers of the network may learn more slowly than the later layers. This can lead to the weight parameters becoming so small as to be insignificant, meaning the algorithm would no longer be learning.Think of it like a game of telephone. During training (a process called Backpropagation), the network sends an “error” signal backward from the end to the beginning. But as this signal travels through each layer, it can get weaker and weaker. By the time it reaches the early layers — the ones that first process your data — the message can be just a faint whisper.Their weights become so small they’re practically insignificant, and your model’s ability to learn simply grinds to a halt.The Math LogicTo train a network, we use Backpropagation. We calculate the error at the end and push it backward to update weights using the Chain Rule. This means we are multiplying gradients together layer by layer.Source: https://towardsdatascience.com/neural-networks-backpropagation-by-dr-lihi-gur-arie-27be67d8fdce/Mathematically, if your gradient g is smaller than 1 (which it almost always is with Sigmoid), and you have T layered network, according to the ‘chain rule, we’ll construct the product of the derivatives along all paths connecting the variables (≈g1×g2×g3⋯×gT​):Imagine a network with 10 layers. If you multiply the gradients backward using the chain rule, and every gradient is roughly 0.25 (best case for Sigmoid), look what happens:0.25^10≈0.00000095That number is effectively zero. Because the gradient is the signal that tells the network how to change its weights, a zero gradient means no learning. The earlier layers (which detect basic features) stop updating entirely.The Fix: Enter ReLUTo fix the vanishing gradient, the community moved toward ReLU (Rectified Linear Unit).ReLU (Rectified Linear Unit) Output range: [0, ∞)Its derivative is: ReLU′(x) = { 1 if x > 0; 0 if x Dying ReLU: If inputs are negative, the gradient is 0, and the neuron “dies.” (Solution: Leaky ReLU, which allows a tiny gradient for negative values. Look at the graph below.)Exploding Gradients: Since ReLU doesn’t squash numbers, if your weights are large, multiplying them repeatedly causes the values to spiral to infinity.The Math LogicThe ReLU function itself doesn’t cause gradients to explode. Instead, its derivative is a constant 1 for all positive inputs. This means ReLU doesn't dampen or "shrink" the gradient signal as it passes backward through the network.As we know from chain rule:For all active neurons (X > 0), the derivative A` is exactly 1. The chain rule equation effectively becomes the multiplication of Ws. If the weights in the network are large (greater than 1), and you multiply these large weights repeatedly during Backpropagation without any dampening from the activation function, the gradient can grow exponentially and “explode.”Why vanishing/exploding gradients are especially associated with RNNsWhile RNNs were a breakthrough for processing sequences like text and time-series data, they have a fundamental weakness that can either erase their memory or cause them to completely lose control.This weakness boils down to two infamous problems: vanishing and exploding gradients.While these issues can pop up in any deep neural network, they are especially brutal for RNNs.The Core Problem: A Network Through TimeTo understand the issue, you have to picture how an RNN works. It processes a sequence step-by-step, feeding its own output from the previous step back into itself as an input for the current one. When we train it, we “unroll” this loop through time. An RNN processing a 100-word sentence effectively becomes a 100-layer-deep neural network.But here’s the catch: unlike a standard 100-layer network that has different weights at each layer, the RNN reuses the exact same weight matrix at every single time step.During training (a process called Backpropagation Through Time), the error gradient has to travel backward from the end of the sequence to the beginning. This means it gets repeatedly multiplied by that same weight matrix over and over again. This repetition is the source of all the trouble.source: https://www.geeksforgeeks.org/machine-learning/introduction-to-recurrent-neural-network/RNNs have 2 major problems for which they are not used widely, and instead other architectures like LSTM are used:1. Problem of long-term dependency: vanishing gradientIf the values in the weight matrix are small (less than 1), then repeatedly multiplying the gradient by them causes it to shrink exponentially. By the time the gradient signal travels back to the early time steps, it has become so tiny that it’s practically zero.The Impact: The network can’t learn from events that happened long ago. This is known as the problem of long-term dependency. The model updates its weights based only on recent events, effectively making it a short-term memory model. It might remember the last few words in a sentence but has no clue what the first paragraph was about.2. Problem of Stagnated Gradients: Exploding GradientIf the values in the weight matrix are large (greater than 1), the gradient signal gets amplified at every step as it travels back in time. It quickly balloons into an enormous number.The Impact: These massive gradients cause wildly unstable updates to the network’s weights. The training loss can spike unpredictably, and the model fails to learn anything useful. In worst-case scenarios, the numbers become so large they are registered as “Not a Number” (NaN), causing the training to crash completely. This is sometimes called stagnated training because the model makes no progress.Practical SolutionsFortunately, researchers developed clever ways to manage these problems, paving the way for the powerful sequence models we use today.Gradient Clipping: This is the go-to solution for exploding gradients. It’s simple: if a gradient exceeds a certain threshold, you just “clip” it and scale it down to a manageable size. It’s like putting a volume limit on the echo.Smarter Architectures (LSTMs & GRUs): The real breakthrough came from designing better RNN architectures. Long Short-Term Memory (LSTM) networks were created specifically to solve the vanishing gradient problem.Better Activation Functions: Switching from tanh or sigmoid (which squash their derivatives to be less than 1) to an activation like ReLU can help prevent gradients from vanishing. However, this must be done carefully, as ReLU can sometimes contribute to exploding gradients.Proper Weight Initialization: Using smart initialization techniques (like Xavier or He initialization) helps set the initial weights to values that keep the gradient signal stable from the very beginning.How does LSTM resolve the problem??Standard RNNs struggle to remember long sequences. LSTMs were designed specifically to fix the vanishing gradient problem using a concept called the Cell State.source: https://www.researchgate.net/figure/A-Long-short-term-memory-LSTM-unit-architecture_fig1_356018554The key components are:A. The Cell State (Ct)Think of the Cell State as a superhighway for gradients. In a standard RNN, data is constantly multiplied and transformed. In an LSTM, the Cell State allows information to be flow through unchanged if needed.B. The GatesGates are neural networks in themselves. LSTMs have three main gates to control the cell state:Forget Gate (f_t): To decide what information from the previous cell state (Ct−1) should be thrown away or forgotten.Input Gate (i_t): To decide what new information from the current time step should be stored in the cell state (CtCt​).Output Gate (o_t): To decide what part of the cell state should be used to create the output and the hidden state (htht​) for the current time step.How This Solves the Gradient ProblemsTraditional RNNs often forget long-term information because their memory either fades away (vanishing gradients) or becomes corrupted (exploding gradients). LSTMs fix this with a special component called the cell state.Think of it as a shared notebook passed between time steps. In a regular RNN, the entire notebook is rewritten at every step, causing old information to get lost. In an LSTM, the cell state allows the network to simply read from the notebook and make small, precise edits, ensuring the core message remains intact over long periods.But how do they do it?The magic lies in their clever internal design, which has two secret weapons: a memory superhighway and smart gates.1. The Memory Superhighway (Fixing Vanishing Gradients)Think of the LSTM’s core memory, its cell state, as a dedicated express lane on a highway.In a regular RNN, the memory signal has to pass through many intersections, getting weaker each time (like making a photocopy of a photocopy). This is because the signal is repeatedly multiplied, causing it to shrink into nothing.The LSTM’s cell state, however, is different. It acts like a conveyor belt. The network can put information on the belt, let it travel along for a long time, and then take it off when needed. The process is based on addition, not multiplication. Adding new information doesn’t weaken the old information in the same way.2. The Smart Gates (Fixing Exploding Gradients)Now, what stops this memory superhighway from getting clogged with junk or overflowing? That’s where the gates come in.Think of these gates as smart traffic controllers for the memory cell.The Forget Gate looks at the old memory and decides what’s no longer relevant and needs to be thrown out.The Input Gate looks at the new information and decides what is important enough to be added to the memory.These gates carefully regulate the flow of information. By deciding what to keep and what to add, they prevent the memory from getting overwhelmed and “exploding” into huge, nonsensical values. It’s a controlled process, not a chaotic free-for-all.What about TransformersWhile LSTMs are great, Transformers (like BERT or GPT) largely replaced them. Why? Because they solved these gradient issues even better, without needing sequential processing.They use two main tricks to keep gradients healthy:The Role of the Residual Connection :The purpose of this addition is to enable a residual connection, which helps in gradient flow during training and allows the model to learn more effectively without vanishing gradients. This ensures that even in a very deep stack of Transformer layers, the gradient has a direct, uninterrupted path back to the initial layers, preventing it from vanishing.Layer Normalization:Layer Normalization is applied before the input goes into each sub-layer (after the residual addition).It stabilizes the activations by normalizing them to have a mean of 0 and a standard deviation of 1. This keeps the numbers within a controlled, predictable range throughout the network. By preventing activations from becoming too large or too small, Layer Normalization directly counteracts both exploding and vanishing gradients, respectively.TakeawayThese problems aren’t showstoppers — they’re design constraints. With the right activations, architectures, normalization, initialization, and clipping, deep models learn reliably. Modern successes — from LSTMs to Transformers — are built on systematically managing gradient flow.Vanishing and Exploding Gradient was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.