Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 23

Adam Optimizer from Scratch

Recommended resources

Hello, and welcome to our next lesson on optimization. In our previous session, we explored how momentum and Nesterov acceleration help overcome the slow convergence of gradient descent in ill-conditioned loss landscapes. By incorporating an exponentially weighted average of past gradients—the first moment—these methods dampen oscillations and build speed in the right direction. However, they still rely on a single, global learning rate for all parameters.

Today, we will build upon this foundation to derive the Adam (Adaptive Moment Estimation) optimizer. Adam is one of the most widely used and effective optimizers in deep learning. It achieves its power by combining the momentum concept with adaptive, per-parameter learning rates. To do this, it tracks not only the first moment of the gradients (the mean) but also the second moment (the uncentered variance). Our primary goal is to derive the full Adam update rule, with a particular focus on the crucial step of bias correction, which is essential for robust performance at the start of training.

1. Combining Momentum with Adaptive Learning Rates

The central idea behind Adam is to synthesize two powerful concepts we've touched upon:

  1. Momentum: Using a moving average of the gradient to determine the update direction, providing inertia and smoothing the optimization path. This is the first moment estimate.
  2. Adaptive Learning Rates: Scaling the learning rate for each parameter individually based on its past gradients. Parameters that receive large or noisy gradients get smaller updates, while those with small or consistent gradients get larger updates. This is achieved using the second moment estimate. Predecessors like Adagrad and RMSProp pioneered this idea.

Adam combines these into a single, cohesive algorithm. The following video provides a concise overview of how these pieces fit together.

Adam Optimizer in 20 min

This video, "Adam Optimizer in 20 min," provides an excellent intuitive breakdown of the algorithm's architecture.

Please watch the following two segments: The introduction lays out the four key components: first moment (momentum), second moment (adaptive rate), bias correction, and the final update rule. Then, watch the description of the first and second moments. This explains how Adam uses an exponentially weighted moving average (EWMA) for both the gradient's direction (first moment, m_t) and its magnitude (second moment, v_t).


2. The Moment Estimates and the Bias Problem

As introduced in the video, Adam maintains two running averages:

  • First Moment Estimate (): This is the EWMA of the gradients, which functions as the momentum component. Let be the gradient at timestep .

    Here, is the exponential decay rate, typically close to 1 (e.g., 0.9). This is exactly analogous to the velocity vector in the classical momentum method we studied previously.

  • Second Moment Estimate (): This is the EWMA of the squared gradients. This term will be used to scale the learning rate.

    Here, denotes the element-wise square of the gradient vector. is the decay rate for this average, usually set higher than (e.g., 0.999) to ensure the adaptive learning rate is stable.

A subtle but critical issue arises from the standard practice of initializing the moment vectors and to zero. Because they start at zero, and and are close to one, the estimates and will remain biased towards zero during the initial stages of training. This can lead to undesirably small update steps right when the model could be making rapid progress.

The same video explains this "startup problem" and the high-level idea behind its solution.

Adam Optimizer in 20 min

The video provides a clear, non-mathematical explanation for why the zero-initialization is a problem and how bias correction solves it.

Watch the segment on the startup correction. Pay attention to how the correction factor is large at the beginning and diminishes as training progresses.


3. Deriving the Bias Correction

Now, let's derive the correction factors that transform the biased estimates and into unbiased ones, and . This derivation is a classic example of analyzing the expected value of a recursive estimator, a technique you are likely familiar with from your work with time-series or signal processing.

Let's focus on the second moment, . The update rule is . If we unroll this recursion back to , assuming , we get:

To analyze the bias, we take the expectation of . We make a simplifying assumption that the second moment of the gradient is stationary, i.e., for all .

The summation is a finite geometric series . Substituting this in, we find:

This equation clearly shows the bias. The expected value of our estimator is not the true second moment , but is instead scaled by a factor of .

To correct this, we can simply divide our estimate by this factor. This gives us the bias-corrected second moment estimate:

By construction, , so our new estimator is unbiased. An identical derivation for the first moment yields the bias-corrected first moment estimate:

The following document provides a concise summary of this derivation.

Stochastic Gradient Descent and Adam Optimizer

This document provides a formal derivation of the bias correction, which will reinforce the steps we've just walked through.

Please read the section titled 4.1 Network Update. Focus on the derivation beginning with this paragraph. This text walks through the exact steps we just discussed for v_t, from expanding the moving average as a geometric series of past gradients to deriving the final correction term.


4. The Complete Adam Update Rule

With the bias-corrected moment estimates in hand, we can now formulate the final parameter update rule for Adam. At each step, the parameters are updated as follows:

Let's analyze this expression:

  • is the master learning rate.
  • The update direction is given by , our momentum-based estimate of the mean gradient.
  • The denominator, , provides the per-parameter adaptive learning rate. For parameters where the historical gradients have been large (large ), the effective learning rate is reduced. For parameters with small historical gradients, the effective learning rate is increased.
  • is a small constant (e.g., ) added for numerical stability to prevent division by zero, in case is very close to zero.

This single, elegant equation combines the smooth, directed path of momentum with the fine-grained, adaptive step sizes of RMSProp-like methods, all while correcting for initialization bias.

The two resources below give a full picture of the algorithm, from pseudocode to a concrete numerical example.

Stochastic Gradient Descent and Adam Optimizer

This document presents the final update rules and the complete algorithm in pseudocode format.

Review the equations and the algorithm just after the bias correction derivation you read. Focus on this section, which presents the bias-corrected estimators \hat{m}_i and \hat{v}_i, the final parameter update equation (35), and the full pseudocode in Algorithm 3.

Adam Optimizer in 20 min

To solidify your understanding, this video will now walk through the final update rule and a complete numerical calculation for the first step.

Watch these two key segments: First, the breakdown of the final update formula, which synthesizes all the components. Then, follow the step-by-step numerical example. This is a great way to see how the numbers flow through the formulas for a single iteration.


Conclusion

In this lesson, we have derived the Adam optimizer from its constituent parts. We saw how it elegantly merges the concepts of momentum and adaptive learning rates, and we performed the crucial derivation of the bias correction terms needed to ensure its stability and effectiveness from the very first step of training.

Key Takeaways:

  • Adaptive Moment Estimation (Adam) combines a first moment estimate (momentum) for update direction with a second moment estimate (uncentered variance) for per-parameter adaptive scaling of the learning rate.
  • The moment estimates and are calculated using exponentially weighted moving averages of the gradient and its square, respectively.
  • Initializing the moments to zero introduces a bias that causes initial update steps to be too small.
  • This bias can be mathematically derived and corrected by dividing the raw moment estimates by factors of and .
  • The final Adam update rule uses these bias-corrected estimates to provide robust and efficient optimization across a wide range of deep learning problems.

While Adam automates the tuning of per-parameter learning rates, the global learning rate remains a critical hyperparameter. In our next lesson, we will discuss strategies for managing this global learning rate over the course of training, such as learning rate schedules, to further improve convergence and final model performance.