class Muon(torch.optim.Optimizer):
"""Steepest descent under the spectral norm: orthogonalized momentum."""
def __init__(self, params, lr, momentum=0.95, weight_decay=0.0):
super().__init__(params, dict(lr=lr, momentum=momentum,
weight_decay=weight_decay))
@torch.no_grad()
def step(self):
for group in self.param_groups:
for p in group['params']:
if p.grad is None: # A parameter that received no gradient
continue
state = self.state[p]
if not state: # First step: allocate the momentum buffer
state['buf'] = torch.zeros_like(p)
buf = state['buf'].mul_(group['momentum']).add_(p.grad)
G = p.grad + group['momentum'] * buf # Nesterov momentum
M = G.reshape(len(G), -1) # Flattens conv kernels
O = newton_schulz(M).reshape(p.shape)
rms_scale = 0.2 * math.sqrt(max(M.shape)) # AdamW's RMS
p.mul_(1 - group['lr'] * group['weight_decay']) # Decoupled
p.add_(O, alpha=-group['lr'] * rms_scale)