Info

Adam (Adaptive Moment Estimation) is a popular optimization algorithm for training neural networks. It combines the advantages of two other popular optimization algorithms: AdaGrad and RMSProp.

  • Different parameters can have different natural scales, sensitivities, and optimization histories.
  • Adam tries to adapt the scale of the update independently for each parameter.

Adam combines two kinds of memory: direction + typical magnitude. First moment: (smoothed gradient), helps answer “which direction have gradients been pointing?” Second moment: (smoothed squared gradient), helps answer “how large have gradients typically been?”

Where:

  • is the first moment (mean) of the gradients.
  • is the second moment (uncentered variance) of the gradients.
  • and are hyperparameters that control the decay rates of the first and second moments, respectively.
  • is the learning rate.
  • is a small constant to prevent division by zero.
  • are the parameters being optimized.
  • is the gradient of the loss function with respect to the parameters at time step .
  • and are bias-corrected estimates of the first and second moments, respectively.
import numpy as np
class Adam:
    def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.m = None
        self.v = None
        self.t = 0
 
    def update(self, params, grads):
        if self.m is None:
            self.m = np.zeros_like(params)
            self.v = np.zeros_like(params)
 
        self.t += 1
        self.m = self.beta1 * self.m + (1 - self.beta1) * grads
        self.v = self.beta2 * self.v + (1 - self.beta2) * (grads ** 2)
 
        m_hat = self.m / (1 - self.beta1 ** self.t)
        v_hat = self.v / (1 - self.beta2 ** self.t)
 
        params -= self.learning_rate * m_hat / (np.sqrt(v_hat) + self.epsilon)

AdamW

= weight decay, which pushes parameters towards zero during optimization.

AdamW separates weight decay from the adaptive gradient step: