import torch
from torch.optim import Optimizer
class NewOptimizer(Optimizer):
def __init__(self, params, lr=1e-4, eps=1):
if not 0.0 <= lr:
raise ValueError("Invalid learning rate: {}".format(lr))
if not 0.0 <= eps:
raise ValueError("Invalid epsilon value: {}".format(eps))
defaults = dict(lr=lr, eps=eps)
super(NewOptimizer, self).__init__(params, defaults)
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group['lr']
eps = group['eps']
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
# State initialization
if len(state) == 0:
state['step'] = 0
state['square_avg'] = torch.zeros_like(p.data)
state['momentum_buf'] = torch.zeros_like(p.data)
state['scaling_avg'] = torch.ones_like(p.data)
square_avg = state['square_avg']
state['step'] += 1
# Update the running average of the squared gradients
square_avg.addcmul_(grad, grad.conj())
# Compute the RMS of the gradients
denom = square_avg.sqrt().add_(eps)
mask = (grad * state['momentum_buf'] > 0).to(grad.dtype)
mask = mask * (mask.numel() / (mask.sum() + eps))
state['momentum_buf'] = mask * state['momentum_buf'] + grad
# Update the parameter
p.data.addcdiv_(state['momentum_buf'], denom, value=-lr)
# p.data = p.data - (lr * grad) / sqrt(square_avg + eps)
return loss
Assistant
Help me fix my optimizer. I think because of the denom division and the mask rescaling, it causes numbers to explode to NaN. Is there a way to fix this neatly?
You're right in identifying that the denominator (denom) and the mask rescaling are likely causing numerical instability, leading to NaNs in your optimizer. Specifically, the mask rescaling can cause large scaling factors when the number of positive mask elements is small, which in turn can make the momentum_buf explode.
Here's a step-by-step approach to fix the optimizer neatly:
Remove or Modify the Mask Rescaling:
The current mask scaling:
python
mask = mask * (mask.numel() / (mask.sum() + eps))
can lead to very large values if mask.sum() is small. To prevent this, you can either:
Remove the Rescaling: Use the mask as a binary indicator without scaling.
Apply a Safer Scaling: Use normalization techniques that prevent the scaling factor from becoming too large.
Ensure Numerical Stability:
While you've already added eps to denom, it's good practice to ensure all operations are numerically stable. Additionally, consider clamping the values of momentum_buf or denom if necessary.
Implement Gradient Clipping (Optional):
To further prevent exploding gradients, you can implement gradient clipping within the optimizer.
Below is the revised optimizer with the mask rescaling removed for numerical stability:
python
import torch
from torch.optim import Optimizer
class NewOptimizer(Optimizer):
def __init__(self, params, lr=1e-4, eps=1):
if not 0.0 <= lr:
raise ValueError(f"Invalid learning rate: {lr}")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon value: {eps}")
defaults = dict(lr=lr, eps=eps)
super(NewOptimizer, self).__init__(params, defaults)
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group['lr']
eps = group['eps']
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
# State initialization
if len(state) == 0:
state['step'] = 0
state['square_avg'] = torch.zeros_like(p.data)
state['momentum_buf'] = torch.zeros_like(p.data)
state['scaling_avg'] = torch.ones_like(p.data)
square_avg = state['square_avg']
momentum_buf = state['momentum_buf']
state['step'] += 1
# Update the running average of the squared gradients
square_avg.addcmul_(grad, grad.conj())
# Compute the RMS of the gradients
denom = square_avg.sqrt().add_(eps)
# Create mask without rescaling
mask = (grad * momentum_buf > 0).to(grad.dtype)
# Update the momentum buffer without scaling
momentum_buf.mul_(mask).add_(grad)
# Update the parameter
p.data.addcdiv_(momentum_buf, denom, value=-lr)
return loss
Learning Rate Adjustment: Sometimes, simply reducing the learning rate can mitigate numerical instability.
Logging and Debugging: Add logging statements to monitor the values of denom, mask, and momentum_buf during training to identify potential issues early.
Testing the Optimizer:
Before deploying the optimizer in a full training loop, it's a good idea to test it on a simple model and dataset to ensure stability:
python
import torch
import torch.nn as nn
# Simple model
model = nn.Linear(10, 1)
optimizer = NewOptimizer(model.parameters(), lr=1e-4, eps=1e-8)
criterion = nn.MSELoss()
# Dummy data
inputs = torch.randn(5, 10)
targets = torch.randn(5, 1)
# Training step
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
print("Loss after step:", loss.item())
This test ensures that the optimizer behaves correctly without producing NaNs. If the test passes, you can proceed to use the optimizer in more complex models and datasets.
Conclusion:
By removing the problematic mask rescaling, the optimizer should now maintain numerical stability and prevent the gradients from exploding to NaN. Always ensure to monitor training closely when introducing custom optimizers to catch and address any unforeseen issues promptly.