xbe.at Work with me

Python / Python for ML and AI

Implementing Adadelta Optimizer from Scratch in Python

10 min read7 sectionsCC0

Contents
  1. The Mathematical Intuition
  2. Implementing the Core Optimizer
  3. Tuning Hyperparameters: Rho and Epsilon
  4. Comparing Adadelta with SGD and Adam
  5. Training a Neural Network with Adadelta
  6. Common pitfalls
  7. Key takeaways

Adadelta is an adaptive learning rate method designed to resolve the aggressive, monotonically decreasing learning rate inherent in Adagrad. While Adagrad is effective for sparse data, its accumulation of all past squared gradients causes the learning rate to shrink to zero, halting learning entirely. Adadelta addresses this by restricting the window of accumulated past gradients to a fixed size, using an exponentially decaying average rather than a simple sum. This allows the optimizer to maintain a robust learning rate over long training periods without requiring manual tuning of the initial learning rate.

The primary appeal of Adadelta lies in its self-tuning capability. It adapts the learning rate based on the ratio of the root mean square (RMS) of past updates to the RMS of past gradients. This makes it particularly useful in scenarios where the optimal learning rate is unknown or difficult to estimate, such as in deep neural networks with varying gradient scales across layers. It is also highly effective for sparse gradient problems, such as those encountered in natural language processing with large vocabularies, where many parameters receive updates infrequently.

You should consider Adadelta when working with models that suffer from vanishing gradients due to aggressive learning rate decay, or when you want a "set and forget" optimizer that requires minimal hyperparameter adjustment. However, it is not always the best choice. For dense gradient problems where Adam is available, Adam often provides faster convergence. Adadelta is most valuable when you need the stability of adaptive methods but want to avoid the specific pitfalls of Adagrad’s infinite memory or when computational constraints favor a simpler adaptive rule than Adam’s momentum-based approach.

The Mathematical Intuition

To understand Adadelta, we must first look at the problem it solves. Adagrad updates parameters by dividing the gradient by the square root of the sum of all past squared gradients. This denominator grows monotonically, causing the step size to vanish. Adadelta replaces this infinite sum with a running average of past squared gradients, controlled by a decay rate \rho.

The core idea is to define a running average of squared gradients, E[g^2]_t, using an exponential decay:

E[g^2]_t = \rho E[g^2]_{t-1} + (1 - \rho) g_t^2

Here, \rho is a decay factor, typically set to 0.95. This ensures that only the most recent gradients significantly influence the current learning rate, preventing the denominator from growing indefinitely.

However, Adadelta goes a step further. Instead of using a fixed initial learning rate \eta, it uses the RMS of past parameter updates, E[\Delta x^2]_t, to scale the current update. The update rule for the parameter change \Delta x_t is:

\Delta x_t = - \frac{\text{RMS}[\Delta x]_{t-1}}{\text{RMS}[g]_t + \epsilon} g_t

Where \text{RMS}[g]_t = \sqrt{E[g^2]_t + \epsilon} and \text{RMS}[\Delta x]_t = \sqrt{E[\Delta x^2]_t + \epsilon}. The term \epsilon is a small constant for numerical stability. By using the RMS of updates in the numerator, Adadelta effectively estimates the magnitude of previous steps, allowing it to adapt the learning rate dynamically without an explicit \eta. This makes the method scale-invariant to the magnitude of the gradients.

Implementing the Core Optimizer

We will build a robust Adadelta optimizer in Python using NumPy. This implementation will handle multiple parameters and maintain the necessary state variables for the running averages. We start by defining a class that initializes the state for each parameter tensor.

import numpy as np

class Adadelta:
    def __init__(self, params, rho=0.95, eps=1e-6):
        """
        Initialize the Adadelta optimizer.
        
        Args:
            params: List of numpy arrays representing model parameters.
            rho: Decay rate for the running averages.
            eps: Small constant for numerical stability.
        """
        self.params = params
        self.rho = rho
        self.eps = eps
        # Initialize running averages of squared gradients and updates
        self.E_g2 = [np.zeros_like(p) for p in self.params]
        self.E_dx2 = [np.zeros_like(p) for p in self.params]

    def step(self, grads):
        """
        Perform a single optimization step.
        
        Args:
            grads: List of numpy arrays representing gradients for each parameter.
        """
        for i, (param, grad) in enumerate(zip(self.params, grads)):
            # Update running average of squared gradients
            self.E_g2[i] = self.rho * self.E_g2[i] + (1 - self.rho) * grad**2
            
            # Compute RMS of gradients and updates
            RMS_g = np.sqrt(self.E_g2[i] + self.eps)
            RMS_dx = np.sqrt(self.E_dx2[i] + self.eps)
            
            # Compute the update step
            # Note: The negative sign is included here to descend the gradient
            dx = -(RMS_dx / RMS_g) * grad
            
            # Update running average of squared updates
            self.E_dx2[i] = self.rho * self.E_dx2[i] + (1 - self.rho) * dx**2
            
            # Apply the update to the parameter
            param += dx

This code implements the mathematical definition directly. The step function iterates through each parameter and its corresponding gradient. It updates the exponential moving averages for both the gradient squares and the update squares. The key line is the calculation of dx, which scales the gradient by the ratio of the RMS of past updates to the RMS of past gradients. This ratio acts as the adaptive learning rate. Because E_dx2 starts at zero, the first few steps might be small, but the optimizer quickly adapts as E_dx2 accumulates information about the step sizes.

Tuning Hyperparameters: Rho and Epsilon

The two hyperparameters in Adadelta are rho and eps. The rho parameter controls the window size of the past gradients. A higher rho (e.g., 0.99) means the optimizer remembers gradients for a longer period, leading to smoother but slower adaptation. A lower rho (e.g., 0.9) makes the optimizer more responsive to recent changes but potentially noisier. The default value of 0.95 is a robust choice for most problems.

The eps parameter prevents division by zero. While theoretically, the RMS should never be zero, floating-point arithmetic can lead to numerical instability. Setting eps to 10^{-6} is standard. If you encounter NaN values during training, increasing eps slightly can help. Conversely, if eps is too large, it can dampen the adaptive nature of the optimizer, making it behave more like standard SGD with a very small learning rate.

When tuning these parameters, observe the loss curve. If the loss plateaus too early, try decreasing rho to allow faster adaptation. If the loss oscillates wildly, increase rho to smooth out the gradient estimates. Unlike SGD, where you tune the learning rate directly, here you tune the memory of the optimizer.

Comparing Adadelta with SGD and Adam

To visualize the behavior of Adadelta, we can compare it against Stochastic Gradient Descent (SGD) and Adam on a challenging optimization landscape. The Rosenbrock function is a classic test case because it has a narrow, curved valley that is difficult to navigate.

import matplotlib.pyplot as plt

def rosenbrock(x, y):
    return (1 - x)**2 + 100 * (y - x**2)**2

def rosenbrock_grad(x, y):
    dx = -2 * (1 - x) - 400 * x * (y - x**2)
    dy = 200 * (y - x**2)
    return np.array([dx, dy])

def optimize_trajectory(optimizer_class, initial_params, num_iterations, **kwargs):
    params = initial_params.copy()
    trajectory = [params.copy()]
    # Create optimizer instance
    opt = optimizer_class([params], **kwargs)
    
    for _ in range(num_iterations):
        grad = rosenbrock_grad(params[0], params[1])
        opt.step([grad])
        trajectory.append(params.copy())
        
    return np.array(trajectory)

# Define a simple SGD for comparison (using Adadelta with rho=0 approximates SGD with fixed lr)
# For a true SGD comparison, we'd need a separate class, but here we focus on Adadelta's adaptivity.
# Let's compare Adadelta with different rho values.

initial_params = np.array([-1.0, 2.0])
num_iterations = 500

traj_rho_90 = optimize_trajectory(Adadelta, initial_params, num_iterations, rho=0.90)
traj_rho_95 = optimize_trajectory(Adadelta, initial_params, num_iterations, rho=0.95)
traj_rho_99 = optimize_trajectory(Adadelta, initial_params, num_iterations, rho=0.99)

# Plotting
x = np.linspace(-2, 2, 100)
y = np.linspace(-1, 3, 100)
X, Y = np.meshgrid(x, y)
Z = rosenbrock(X, Y)

plt.figure(figsize=(10, 8))
plt.contour(X, Y, Z, levels=np.logspace(-1, 3, 20), cmap='viridis')
plt.plot(traj_rho_90[:, 0], traj_rho_90[:, 1], label='rho=0.90', color='red')
plt.plot(traj_rho_95[:, 0], traj_rho_95[:, 1], label='rho=0.95', color='blue')
plt.plot(traj_rho_99[:, 0], traj_rho_99[:, 1], label='rho=0.99', color='green')
plt.legend()
plt.title('Adadelta Trajectories on Rosenbrock Function')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Figure drawn by the code above

In the resulting plot, you will likely see that rho=0.99 follows the valley more smoothly but may take longer to reach the minimum, while rho=0.90 might be more erratic but potentially faster in the initial stages. rho=0.95 usually offers a good balance. The key observation is that Adadelta does not require a learning rate parameter; the step size is determined entirely by the history of gradients and updates.

Training a Neural Network with Adadelta

Adadelta shines in neural network training, particularly when dealing with sparse gradients. Let's train a simple two-layer neural network for binary classification on synthetic data. We will implement the forward and backward passes manually to integrate our custom optimizer.

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def binary_cross_entropy(y_true, y_pred):
    # Clip predictions to avoid log(0)
    y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15)
    return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))

class SimpleNN:
    def __init__(self, input_dim, hidden_dim, output_dim):
        # Xavier initialization
        self.W1 = np.random.randn(input_dim, hidden_dim) * np.sqrt(2 / input_dim)
        self.b1 = np.zeros((1, hidden_dim))
        self.W2 = np.random.randn(hidden_dim, output_dim) * np.sqrt(2 / hidden_dim)
        self.b2 = np.zeros((1, output_dim))
    
    def forward(self, X):
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = np.tanh(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        self.a2 = sigmoid(self.z2)
        return self.a2
    
    def backward(self, X, y, y_pred):
        m = X.shape[0]
        # Output layer gradients
        dz2 = y_pred - y
        dW2 = np.dot(self.a1.T, dz2) / m
        db2 = np.sum(dz2, axis=0, keepdims=True) / m
        
        # Hidden layer gradients
        da1 = np.dot(dz2, self.W2.T)
        dz1 = da1 * (1 - np.power(self.a1, 2)) # Derivative of tanh
        dW1 = np.dot(X.T, dz1) / m
        db1 = np.sum(dz1, axis=0, keepdims=True) / m
        
        return [dW1, db1, dW2, db2]

# Generate synthetic data
np.random.seed(42)
X = np.random.randn(1000, 2)
y = (X[:, 0] + X[:, 1] > 0).astype(float).reshape(-1, 1)

# Initialize model and optimizer
model = SimpleNN(2, 10, 1)
params = [model.W1, model.b1, model.W2, model.b2]
optimizer = Adadelta(params, rho=0.95, eps=1e-6)

# Training loop
epochs = 1000
losses = []
for epoch in range(epochs):
    y_pred = model.forward(X)
    loss = binary_cross_entropy(y, y_pred)
    losses.append(loss)
    
    grads = model.backward(X, y, y_pred)
    optimizer.step(grads)
    
    if epoch % 200 == 0:
        print(f"Epoch {epoch}, Loss: {loss:.4f}")

# Evaluate
y_pred_final = model.forward(X)
accuracy = np.mean((y_pred_final > 0.5) == y)
print(f"Final Accuracy: {accuracy:.4f}")
Epoch 0, Loss: 0.9758
Epoch 200, Loss: 0.1310
Epoch 400, Loss: 0.0520
Epoch 600, Loss: 0.0293
Epoch 800, Loss: 0.0202
Final Accuracy: 1.0000

This example demonstrates how to plug the Adadelta optimizer into a standard training loop. The gradients are computed via backpropagation, and the optimizer updates the weights. You should observe the loss decreasing steadily. Adadelta often provides more stable convergence than vanilla SGD, especially if the initial learning rate for SGD is not perfectly tuned. The lack of a learning rate parameter simplifies the setup, but you must ensure that the gradient magnitudes are reasonable; extremely large gradients can still cause instability, though the RMS normalization helps mitigate this.

Common pitfalls

One major pitfall is assuming Adadelta is a universal replacement for Adam. While both are adaptive, Adam includes momentum (first moment estimation), which helps accelerate convergence in directions with consistent gradients. Adadelta lacks this momentum term, so it may converge slower in dense gradient scenarios where momentum is beneficial. If you find Adadelta converging too slowly, consider adding momentum manually or switching to Adam.

Another issue is the initialization of the running averages. Since E_dx2 starts at zero, the first few updates are very small. This can lead to a slow start. Some implementations initialize E_dx2 with a small positive value or use a warmup period. Additionally, if your gradients are extremely sparse (many zeros), the RMS of gradients might remain very small, leading to large effective learning rates for the non-zero gradients. Monitoring the effective learning rate (the ratio RMS_dx / RMS_g) can help diagnose this.

Finally, be cautious with the eps value. In float32 precision, if gradients are very small, eps can dominate the denominator, effectively turning Adadelta into a method with a fixed, tiny learning rate. Ensure your data is normalized to prevent gradient magnitudes from becoming too small or too large.

Key takeaways

  • Adadelta solves the vanishing learning rate problem of Adagrad by using an exponentially decaying average of past squared gradients.
  • It is self-tuning: it does not require an initial learning rate, making it robust to unknown gradient scales.
  • The update rule relies on the ratio of the RMS of past updates to the RMS of past gradients.
  • It is particularly effective for sparse gradient problems, such as those in NLP.
  • It lacks momentum, so it may converge slower than Adam in dense gradient scenarios.
  • Key hyperparameters are rho (decay rate, default 0.95) and eps (numerical stability, default 1e-6).

Keep going

More in Python for ML and AI

All of them