cognitivecomputations / grokadamw

Apache License 2.0
119 stars 7 forks source link

GrokAdamW: A PyTorch Optimizer for Accelerated Grokking

by Eric Hartford

image

Quick divergence in loss, training gemma-2-2b with adamw-fused vs grokadamw

GrokAdamW is a novel optimizer designed to enhance AI training by combining the strengths of Grokfast (a technique for accelerating "grokking" in deep learning models) with the robustness and efficiency of the AdamW optimizer. It's particularly useful for models exhibiting delayed generalization, where performance on validation data improves significantly after a period of overfitting to the training data.

Update: This optimizer was used to train the awesome tiny model nisten/Biggie-SmoLlm-0.15B-Base

This implementation was inspired by the following papers:

Table of Contents

  1. Overview
  2. Theory
  3. Mathematical Explanation
  4. Installation
  5. Usage
  6. Configuration
  7. Common Pitfalls and Debugging Tips
  8. Contribution
  9. License

Overview

Grokking is a phenomenon where deep learning models achieve sudden generalization after a long period of overfitting. Research suggests that this delayed generalization is related to the slow-varying components of gradients during training. Grokfast, inspired by this research, accelerates grokking by amplifying these slow-varying gradients.

GrokAdamW builds upon this concept by integrating Grokfast's adaptive frequency amplification into the AdamW optimization algorithm. It introduces several key innovations:

  1. Adaptive Momentum: The momentum of the Grokfast component (which controls the emphasis on slow-varying gradients) dynamically adjusts based on a "Grokking Signal" that reflects the model's generalization progress.
  2. Layer-Wise Momentum Decay: Recognizing that different layers learn at different rates, GrokAdamW implements a gradual decay of the AdamW momentum parameter (β1) from earlier to later layers, promoting faster generalization in early layers while preventing overfitting in later layers.
  3. Multiple Grokking Signals: Allows for flexibility in defining the Grokking Signal by supporting multiple signal functions, which can be combined to capture different aspects of generalization performance.
  4. Optional Gradient Clipping: Provides the option to clip gradients, enhancing training stability and preventing exploding gradients, a common issue in deep learning.

Theory:

Mathematical Explanation:

Core AdamW Updates: For each layer l, parameter p, and training step t:

Grokfast Integration:

Optional Gradient Clipping:

Installation

You can easily install GrokAdamW using pip:

pip install grokadamw

Usage:

import torch
import torch.nn as nn
from grokadamw import GrokAdamW

# Define your model
model = nn.Linear(10, 1)

# Define your grokking signal function(s)
def grokking_signal_fn(training_loss: float, validation_loss: float) -> float:
    if training_loss == 0:
        return 0.0  # Avoid division by zero
    return (validation_loss - training_loss) / training_loss

# Initialize GrokAdamW optimizer
optimizer = GrokAdamW(model.parameters(), lr=1e-3, grokking_signal_fn=grokking_signal_fn)

# Training loop
for epoch in range(num_epochs):
    # ... [Your training code] ...

    # Calculate validation loss (val_loss)

    # Perform optimization step
    loss = optimizer.step(closure=lambda: your_loss_function(model, data)) 

Configuration:

GrokAdamW supports standard AdamW parameters (lr, betas, eps, weight_decay) and additional parameters for Grokfast:

Common Pitfalls and Debugging Tips

  1. Grokking Signal Functions Not Providing Useful Signals:

    • Ensure that the functions return meaningful values, reflecting aspects like validation vs. training loss differences.
    • Consider normalizing the output of signal functions.
  2. Issues with Gradient Clipping:

    • If gradients are frequently being clipped, it may indicate a need to adjust the learning rate or other hyperparameters.
  3. Unexpected Behavior with Layer-wise Momentum Decay:

    • Monitor the learning dynamics for different layers. If some layers are learning too slowly or too quickly, adjust gamma or individual layer hyperparameters accordingly.
  4. Monitoring Grokking Signal and Alpha Values:

    • Use tools like TensorBoard or custom logging to track the grokking signal, alpha values, and gradient norms. This can help in understanding the optimizer's behavior and making necessary adjustments.

Contribution

GrokAdamW is an ongoing research project. Your feedback and contributions are welcome! Please feel free to submit issues, feature requests, or pull requests. For more details, see our CONTRIBUTING.md file.

License

GrokAdamW is licensed under the Apache 2.0 License. See the LICENSE file for more details.