sahoosk's picture
Upload folder using huggingface_hub
5407bdc verified
Raw History Blame Contribute Delete
4.4 kB
"""Category 4 -- matrix-based: Muon (Jordan et al., 2024).
AdamW normalises each weight *coordinate* independently, which ignores the
fact that a weight matrix acts as a linear map. Muon instead normalises the
momentum matrix as a whole: it replaces ``M`` by the nearest semi-orthogonal
matrix ``UV^T`` from its SVD, so every singular direction is stepped by the
same amount and no single direction dominates because it happened to have a
large singular value.
Computing an SVD every step would be hopeless, so the orthogonalisation is
done with a quintic Newton-Schulz iteration on the normalised matrix. The
coefficients (3.4445, -4.7750, 2.0315) are tuned to push singular values
towards 1 aggressively in five steps; they do not converge to exactly 1, but
Muon does not need them to -- only the direction matters.
Muon applies to 2D hidden matrices only. Embeddings, the LM head and the
1D gains are shape-special (their "matrix" structure is not a linear map
between hidden spaces) and are handed to an internal AdamW, as in the
reference implementation.
Optimizer state: 1 tensor per 2D parameter, 2 per AdamW-handled parameter.
"""
import torch
from .base import BaseOptimizer
@torch.no_grad()
def newton_schulz(G: torch.Tensor, steps: int = 5, eps: float = 1e-7):
"""Approximate the orthogonal polar factor of G via a quintic iteration."""
a, b, c = 3.4445, -4.7750, 2.0315
X = G.bfloat16()
X = X / (X.norm() + eps)
transposed = G.size(0) > G.size(1)
if transposed: # iterate on the wide orientation
X = X.T
for _ in range(steps):
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
if transposed:
X = X.T
return X.to(G.dtype)
class Muon(BaseOptimizer):
def __init__(self, params, lr=2e-2, momentum=0.95, nesterov=True,
ns_steps=5, weight_decay=0.1,
adamw_lr=3e-4, adamw_betas=(0.9, 0.95), adamw_eps=1e-8):
defaults = dict(lr=lr, momentum=momentum, nesterov=nesterov,
ns_steps=ns_steps, weight_decay=weight_decay,
adamw_lr=adamw_lr, adamw_betas=adamw_betas,
adamw_eps=adamw_eps, use_muon=True)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = self._closure(closure)
for group in self.param_groups:
lr, wd = group["lr"], group["weight_decay"]
mom, nesterov = group["momentum"], group["nesterov"]
use_muon = group.get("use_muon", True)
for p in group["params"]:
if p.grad is None:
continue
g = p.grad
st = self.state[p]
if use_muon and p.ndim == 2:
if not st:
st["buf"] = torch.zeros_like(p)
buf = st["buf"]
buf.mul_(mom).add_(g)
d = g.add(buf, alpha=mom) if nesterov else buf
o = newton_schulz(d, group["ns_steps"])
# The orthogonal factor has unit singular values, so its
# RMS scale depends on the shape; this puts the update on
# a comparable footing to AdamW's per-coordinate ~1.
scale = max(1.0, p.size(0) / p.size(1)) ** 0.5
if wd != 0:
p.mul_(1 - lr * wd)
p.add_(o, alpha=-lr * scale)
else:
# AdamW fallback for embeddings / head / 1D gains.
b1, b2 = group["adamw_betas"]
alr, eps = group["adamw_lr"], group["adamw_eps"]
if not st:
st["step"] = 0
st["m"] = torch.zeros_like(p)
st["v"] = torch.zeros_like(p)
st["step"] += 1
t = st["step"]
m, v = st["m"], st["v"]
m.mul_(b1).add_(g, alpha=1 - b1)
v.mul_(b2).addcmul_(g, g, value=1 - b2)
m_hat = m / (1 - b1 ** t)
v_hat = v / (1 - b2 ** t)
if wd != 0 and p.ndim >= 2:
p.mul_(1 - alr * wd)
p.addcdiv_(m_hat, v_hat.sqrt().add_(eps), value=-alr)
return loss