python
import torch
import torch.nn as nn
class SophiaG(torch.optim.Optimizer):
# 論文の Algorithm 3。h の更新(k ステップに 1 回)は update_hessian() で行う
def __init__(self, params, lr=1e-4, betas=(0.96, 0.99), gamma=0.05, eps=1e-12, weight_decay=0.1):
super().__init__(params, dict(lr=lr, betas=betas, gamma=gamma, eps=eps, weight_decay=weight_decay))
@torch.no_grad()
def update_hessian(self, batch_size):
# Gauss-Newton-Bartlett:取り直したラベルでの勾配 ĝ から ĥ = B · ĝ ⊙ ĝ
for group in self.param_groups:
beta2 = group["betas"][1]
for p in group["params"]:
if p.grad is None:
continue
st = self.state[p]
if "h" not in st:
st["h"] = torch.zeros_like(p)
st["h"].mul_(beta2).add_(batch_size * p.grad * p.grad, alpha=1 - beta2)
@torch.no_grad()
def step(self):
for group in self.param_groups:
beta1 = group["betas"][0]
lr, gamma, eps, wd = group["lr"], group["gamma"], group["eps"], group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
st = self.state[p]
if "m" not in st:
st["m"] = torch.zeros_like(p)
if "h" not in st:
st["h"] = torch.zeros_like(p)
st["m"].mul_(beta1).add_(p.grad, alpha=1 - beta1) # m_t
p.mul_(1 - lr * wd) # 重み減衰
ratio = st["m"] / torch.clamp(gamma * st["h"], min=eps) # m_t / max{γ h_t, ε}
p.add_(ratio.clamp(-1, 1), alpha=-lr) # 要素ごとに ±1 で切り取る
vocab, dim, B, k = 100, 32, 16, 10
model = nn.Sequential(nn.Embedding(vocab, dim), nn.Linear(dim, vocab))
optimizer = SophiaG(model.parameters(), lr=1e-4)
model.train()
for t in range(1, 21):
x = torch.randint(0, vocab, (B,))
y = torch.randint(0, vocab, (B,))
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % k == 1: # k ステップに 1 回、対角ヘッセ行列を推定
logits = model(x)
y_hat = torch.distributions.Categorical(logits=logits).sample() # モデルの出力からラベルを取り直す
optimizer.zero_grad()
nn.functional.cross_entropy(logits, y_hat).backward()
optimizer.update_hessian(batch_size=B)
optimizer.zero_grad()