import torch
import torch.nn as nn
def newton_schulz5(G, steps=5, eps=1e-7):
# ブログ・公式実装と同じ 5 次のニュートン・シュルツ反復(O ≈ UV^T)
a, b, c = (3.4445, -4.7750, 2.0315)
X = G / (G.norm() + eps) # 特異値を [0, 1] に収める
transposed = G.size(0) > G.size(1)
if transposed:
X = X.T
for _ in range(steps):
A = X @ X.T
X = a * X + (b * A + c * A @ A) @ X
return X.T if transposed else X
class MiniMuon(torch.optim.Optimizer):
# 2 次元の重みだけに使う。式:B ← μB + G、M = G + μB、W ← (1 − ηλ)W − η·s·NS(M)
def __init__(self, params, lr=0.02, 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 g in self.param_groups:
for p in g["params"]:
if p.grad is None:
continue
st = self.state[p]
if not st:
st["buf"] = torch.zeros_like(p)
st["buf"].mul_(g["momentum"]).add_(p.grad) # B_t = μB_{t−1} + G_t
m = p.grad + g["momentum"] * st["buf"] # Nesterov 型
o = newton_schulz5(m)
scale = max(1.0, p.size(0) / p.size(1)) ** 0.5 # 公式実装の倍率
p.mul_(1 - g["lr"] * g["weight_decay"])
p.add_(o, alpha=-g["lr"] * scale)
model = nn.Sequential(nn.Embedding(1000, 64), nn.Linear(64, 256), nn.GELU(), nn.Linear(256, 64), nn.Linear(64, 1000))
emb, head = model[0], model[4]
hidden = [p for n, p in model.named_parameters() if p.ndim == 2 and not n.startswith(("0.", "4."))]
others = [p for n, p in model.named_parameters() if not (p.ndim == 2 and not n.startswith(("0.", "4.")))]
# 隠れ層の行列は Muon、埋め込み・出力層・バイアスは AdamW
opt_muon = MiniMuon(hidden, lr=0.02, momentum=0.95)
opt_adamw = torch.optim.AdamW(others, lr=3e-4, weight_decay=0.01)
# PyTorch の組み込みを使う場合:torch.optim.Muon(hidden, lr=0.02, momentum=0.95)
model.train()
x = torch.randint(0, 1000, (8, 16))
y = torch.randint(0, 1000, (8, 16))
logits = model(x)
loss = nn.functional.cross_entropy(logits.reshape(-1, 1000), y.reshape(-1))
opt_muon.zero_grad(); opt_adamw.zero_grad()
loss.backward()
opt_muon.step(); opt_adamw.step()
よくある質問
Q. Muon の原典は論文ですか?
A.
論文ではなく、キーラー・ジョーダンのブログ記事(2024 年 12 月)が原典です。式は公式実装(GitHub)でも確かめられます。その後、リウらの技術報告「Muon is Scalable for LLM Training」(2025 年)が大規模な学習向けの改良(重み減衰と更新の大きさの調整)を示しています。