The optimizers lesson ended with AdamW, a diagonal preconditioner: every coordinate gets its own step size, and the “rotated valley” showed its limit — once the curvature’s principal axes are not the coordinate axes, per-coordinate scaling cannot round the bowl. A transformer’s parameters are mostly matrices, and the natural axes of a matrix are not its entries but its singular vectors. Muon (MomentUm Orthogonalized by Newton–Schulz; Jordan et al. 2024) takes that seriously: it runs SGD-momentum and then replaces each matrix’s momentum with , i.e. it throws away the singular values and keeps only the directions. Within two years it trained Kimi K2, GLM-4.5/5, DeepSeek-V4, Qwen3.8-Flash-Next and MAI-Base-2.
This lesson builds Muon from first principles and then follows it to scale:
- why is the steepest-descent direction for a matrix (spectral norm), and what it does geometrically;
- which parameters must not use it;
- how Newton–Schulz computes with five matmul-only steps, and how its coefficients are designed;
- how big the step is: RMS matching to AdamW and weight decay;
- what it costs and how it is distributed;
- why attention logits explode under Muon and how K2’s QK-Clip stops them.
Notation: a weight acting as (PyTorch’s [out, in]), gradient , momentum , learning rate , weight decay . is the Frobenius norm, the spectral norm (largest singular value) and the nuclear norm (sum of singular values). for the reduced SVD , also called the polar factor.
1. Steepest descent depends on the norm
The gradient descent lesson derived “go along ” from a first-order Taylor expansion with the step length measured in the Euclidean norm. Change the ruler and the best direction changes. Bernstein & Newhouse (2024) write the general problem as
where is the dual norm. The direction is “the unit vector that has the largest inner product with the gradient”; the length is “dual norm / sharpness”. Three choices of ruler for a matrix:
| Norm on | Best unit direction | Dual norm (step length) | Optimizer it gives (no EMA) |
|---|---|---|---|
| Frobenius | (normalised) SGD | ||
| max-entry | Adam with (sign descent) | ||
| spectral | Shampoo without accumulation, Muon without momentum |
Deriving the spectral row. Let and take any with . Then
because every entry of is . Equality needs for all , which achieves. So the maximiser is and the maximum is the nuclear norm. (The first NumPy block below checks this against random candidates.)
Why the spectral norm is the right ruler for a linear layer
A layer’s job is the map . Changing by changes the output by , and the worst-case relative change is an operator norm. With the RMS norm (activations are RMS-normalised in a transformer),
Bounding this bounds how much any input’s output can move, which is what keeps features stable and training predictable as width grows. A per-entry bound (Adam) says nothing about it: a matrix whose entries are all can have spectral norm up to (all signs aligned), or about if the signs are random. Bernstein & Newhouse’s “modular duality” dualises a Linear layer under exactly this norm, which gives
Keller Jordan’s implementation multiplies by , the same factor clamped at 1; PyTorch calls the unclamped version spectral_unclamped.
Muon in one line
Muon = this spectral-norm step applied to the momentum instead of the raw gradient:
The argument is the Nesterov form (Jordan found it “works a bit better than normal SGD-momentum in every case we have tested”); is a shape-dependent scale (§4). Two remarks:
- Momentum goes before orthogonalisation. Averaging gradients first and orthogonalising the average keeps the noise-averaging of momentum; orthogonalising each noisy gradient and averaging afterwards would not produce an orthogonal step.
- The momentum convention does not matter. Jordan’s code keeps an EMA (, update ); Moonlight and
torch.optim.Muonkeep a sum (, update ). The two arguments differ by the constant factor , and Newton–Schulz starts by dividing by the Frobenius norm, so the updates are identical.
Geometrically, keeps where to go (the singular directions of the momentum) and drops how much each direction weighs; the learning rate alone decides how far. And since for orthogonal , Muon is equivariant to rotations of the input and output spaces — the property the diagonal preconditioners lack.
옵티마이저 레슨은 대각 전처리기인 AdamW로 끝났다. 좌표마다 걸음 크기를 따로 주는데, “회전된 골짜기”가 그 한계를 보여 주었다. 곡률의 주축이 좌표축이 아니면 좌표별 스케일링으로는 그릇을 둥글게 만들 수 없다. Transformer의 매개변수는 대부분 행렬이고, 행렬의 자연스러운 축은 원소가 아니라 특이벡터다. Muon(MomentUm Orthogonalized by Newton–Schulz; Jordan et al. 2024)은 이것을 진지하게 받아들인다. SGD-momentum을 돌린 다음, 각 행렬의 momentum 를 로 바꾼다. 즉 특이값을 버리고 방향만 남긴다. 2년이 채 안 되어 Kimi K2, GLM-4.5/5, DeepSeek-V4, Qwen3.8-Flash-Next, MAI-Base-2가 이것으로 학습되었다.
이 레슨은 Muon을 첫 원리부터 세운 뒤 대규모로 따라간다.
- 왜 가 행렬에 대한 바로 그 최급강하 방향(스펙트럼 노름)인지, 기하적으로 무엇을 하는지
- 어떤 매개변수에는 쓰면 안 되는지
- Newton–Schulz가 행렬곱만으로 5단계 만에 를 어떻게 계산하고, 계수는 어떻게 설계하는지
- 걸음 크기: AdamW와의 RMS 맞춤, weight decay
- 비용과 분산 구현
- Muon에서 attention logit이 왜 폭주하고, K2의 QK-Clip이 어떻게 막는지
표기: 가중치 은 로 작용한다(PyTorch의 [out, in]). 기울기 , momentum , 학습률 , weight decay . 는 Frobenius 노름, 는 스펙트럼 노름(최대 특이값), 는 핵 노름(nuclear norm, 특이값의 합)이다. 축소 SVD 에 대해 이고, 이를 극분해 인자(polar factor) 라고도 한다.
1. 최급강하 방향은 노름에 달려 있다
경사하강법 레슨은 ” 방향으로 가라”를 1차 테일러 전개에서 유도했는데, 이때 걸음 길이를 유클리드 노름으로 쟀다. 자를 바꾸면 최선의 방향도 바뀐다. Bernstein & Newhouse(2024)는 일반형을 이렇게 쓴다.
는 쌍대 노름이다. 방향은 “기울기와 내적이 가장 큰 단위 벡터”, 길이는 “쌍대 노름 / 날카로움”이다. 행렬에 대한 세 가지 자:
| 에 대한 노름 | 최선의 단위 방향 | 쌍대 노름(걸음 길이) | 나오는 옵티마이저(EMA 없음) |
|---|---|---|---|
| Frobenius | (정규화된) SGD | ||
| 원소 최대 | 인 Adam(sign descent) | ||
| 스펙트럼 | 누적 없는 Shampoo, momentum 없는 Muon |
스펙트럼 행 유도. 이고 인 아무 를 잡으면
이다. 의 대각 원소는 이기 때문이다. 등호는 모든 에서 일 때 성립하고, 가 그렇다. 따라서 최대화하는 방향은 , 최댓값은 핵 노름이다(아래 첫 NumPy 블록이 무작위 후보들과 비교해 확인한다).
왜 선형 층에는 스펙트럼 노름이 맞는 자인가
층이 하는 일은 사상 다. 를 만큼 바꾸면 출력이 만큼 바뀌고, 최악의 상대 변화는 연산자 노름이다. RMS 노름 로 재면(transformer의 활성은 RMS 정규화되어 있다)
이다. 이것을 묶으면 어떤 입력이든 출력이 얼마나 움직일 수 있는지가 묶이고, 폭이 커져도 특징이 안정적이고 학습이 예측 가능해진다. 원소별 상한(Adam)은 이에 대해 아무것도 말하지 않는다. 모든 원소가 인 행렬의 스펙트럼 노름은 부호가 다 맞으면 까지, 부호가 무작위면 대략 이다. Bernstein & Newhouse의 “modular duality”는 Linear 층을 바로 이 노름으로 쌍대화해서
를 얻는다. Keller Jordan의 구현은 같은 인자를 1에서 자른 를 곱하고, PyTorch는 자르지 않은 형태를 spectral_unclamped라 부른다.
한 줄로 쓴 Muon
Muon = 이 스펙트럼 노름 걸음을 원래 기울기 대신 momentum에 적용한 것이다.
인자 는 Nesterov 꼴이다(Jordan은 “시험한 모든 경우에 일반 SGD-momentum보다 조금 낫다”고 했다). 는 모양에 따른 스케일이다(§4). 두 가지를 짚어 둔다.
- momentum이 직교화보다 먼저다. 기울기를 먼저 평균 내고 그 평균을 직교화하면 momentum의 잡음 평균 효과가 유지된다. 잡음 섞인 기울기를 하나씩 직교화한 뒤 평균하면 직교 걸음이 나오지도 않는다.
- momentum 표기 방식은 상관없다. Jordan의 코드는 EMA(, 업데이트 )를, Moonlight와
torch.optim.Muon은 합(, 업데이트 )을 쓴다. 두 인자는 상수배 만 다르고 Newton–Schulz는 Frobenius 노름으로 나누는 것부터 시작하므로 업데이트는 똑같다.
기하적으로 는 어디로 갈지(momentum의 특이 방향)를 남기고 각 방향에 얼마나 무게를 둘지를 버린다. 얼마나 멀리 갈지는 학습률만이 정한다. 그리고 직교행렬 에 대해 이므로 Muon은 입력·출력 공간의 회전에 대해 등변(equivariant) 이다. 대각 전처리기에 없는 성질이다.
What to take from the figure:
- At the default (κ = 100, θ = 0, η₀ = 0.2, β = 0), the hollow bars show SGD-m’s momentum with σ₁/σ₂ ≈ κ: almost all of the gradient lives in the steep direction, so normalised SGD spends its whole budget on , and — the direction with small gradient but just as much distance left to cover — hardly moves. Muon’s filled bars are equal: it splits the budget evenly and walks the diagonal.
- Adam also splits the budget, but only along coordinate axes. At θ = 0 the input eigenbasis coincides with the coordinates and Adam does as well as Muon or better; at θ = 45° its advantage disappears (the rotated-valley effect from the optimizers lesson). Muon’s path does not change with θ at all.
- With η₀ = 0.05 the total budget cannot reach the minimum, and the greedy choice (spend it where the gradient is big) wins. Orthogonalisation is a bet that all singular directions matter, which pays off over a long horizon, not in one step. Jordan’s empirical motivation is exactly this: the SGD-momentum and Adam updates of transformer matrices are “almost low-rank”, dominated by a few directions, and orthogonalisation “effectively increases the scale of other ‘rare directions’” that are small in the update but still important for learning.
This is a 2-parameter-direction toy with exact contours; it shows direction, not a benchmark. The NumPy experiment below runs a real (small) comparison.
2. Which parameters get Muon, and which stay on AdamW
Muon is defined for 2-D weights that act as linear maps on hidden activations. Everything else keeps AdamW, and each exclusion has a reason:
- Embeddings. The input is a one-hot token, so the natural input norm is , not RMS. Dualising an Embed layer under the norm gives column-wise normalisation (each token’s vector normalised separately; Bernstein & Newhouse), not . Orthogonalising the whole table would couple tokens that never co-occur in the batch.
- LM head. Jordan recommends AdamW for “the embedding and final classifier head layers” from experiment; its output feeds a softmax over the vocabulary, not another RMS-normalised layer.
- Vectors (norm gains, biases, per-head scalars). For a vector , : normalised SGD with no per-coordinate adaptivity. There is no matrix structure to exploit.
- Routers and other “each row is a separate unit” matrices. Qwen3.8-Flash-Next keeps the MoE router on AdamW because Muon amplified early fluctuations and destabilised routing — each output dimension is one expert, with no shared linear structure (report).
- Fused matrices are split. Jordan notes Muon works better on separately than on the fused QKV. Qwen3.8 splits fused QKV and gate/up per head or per half; GLM-5’s Muon Split and K3’s Per-Head Muon orthogonalise each attention head’s block separately, so a head with a large gradient does not dominate a shared orthogonal update (GLM-5, K3).
- Conv filters are flattened to 2-D over their last three dimensions.
3. Newton–Schulz: with five matmuls
An SVD per matrix per step is too slow on accelerators and unstable in bf16. Muon instead uses an odd matrix polynomial that only needs matmuls.
Odd polynomials act on singular values
Let and . Then and , so
The singular vectors never change; each singular value is pushed through the scalar map . iterations apply . Orthogonalising therefore means designing so that its -fold composition sends every to about 1. To start inside , divide by the Frobenius norm: . (By the same argument, for , so the normalisation costs nothing.)
Where the classic coefficients come from
The polar factor is . Write and expand , with :
- keep one term: — the cubic Newton–Schulz iteration, ;
- keep two terms: — the classic quintic.
Near they converge fast: with , the cubic gives (quadratic convergence, ) and the quintic has (cubic convergence). Near they are slow: , so lifting to order 1 takes about steps. For that is 17 steps for and 11 for . Gradient matrices have many tiny singular values, and Frobenius normalisation makes them tinier.
Jordan’s trade: a steep slope, no exact convergence
Jordan’s coefficients maximise the slope at zero, , subject to the iterates staying in a band around 1 rather than converging to 1. With , needs about steps. The price is visible in the fixed points: means , a quadratic in , with roots and . At those points and ; both have , so neither is stable and the iterates never settle — they keep bouncing inside a band (numerically after many steps). The docstring of the reference code says the output is “something like where ”, which “turns out not to hurt model performance at all”. Moonlight reports that 10 steps (more accurate) were no better than 5.
Better polynomials: hybrids and Polar Express
- DeepSeek-V4 runs 8 Jordan steps, then 2 steps of , which has , : quadratic convergence that flattens the band (report).
- Polar Express (Amsel et al. 2025) chooses a different quintic each step: the one that minimises the worst-case on the interval where the singular values currently are, . They prove that choosing greedily step by step yields the optimal composition. The first polynomial, built for , has slope ; later ones approach the classic . The paper reports Jordan’s polynomial “plateaus at an error of ≈0.3”, and in GPT-2-Large runs on 1B tokens a best validation loss of 3.340 for Polar Express versus 3.398 for Jordan’s coefficients (the gap is small, 2.913 vs 2.921, in a 10B-token run with weight decay). Qwen3.8-Flash-Next uses 8 Polar Express steps.
그림에서 읽을 것:
- 기본값(κ = 100, θ = 0, η₀ = 0.2, β = 0)에서 빈 막대를 보면 SGD-m의 momentum은 σ₁/σ₂ ≈ κ다. 기울기 거의 전부가 가파른 방향에 있으니 정규화된 SGD는 예산을 모두 에 쓰고, 기울기는 작지만 남은 거리는 똑같은 는 거의 움직이지 않는다. Muon의 채운 막대는 높이가 같다. 예산을 고르게 나눠 대각선을 따라간다.
- Adam도 예산을 나누지만 좌표축을 따라서만 나눈다. θ = 0이면 입력 고유기저가 좌표와 일치해 Adam이 Muon만큼 또는 더 잘하지만, θ = 45°에서는 그 이점이 사라진다(옵티마이저 레슨의 회전된 골짜기). Muon의 경로는 θ에 전혀 영향을 받지 않는다.
- η₀ = 0.05면 전체 예산으로 최솟값에 닿을 수 없고, 탐욕적인 선택(기울기가 큰 곳에 쓰기)이 이긴다. 직교화는 모든 특이 방향이 중요하다는 데 거는 내기이고, 한 step이 아니라 긴 시간에 걸쳐 이득을 본다. Jordan의 경험적 동기가 바로 이것이다. transformer 행렬의 SGD-momentum·Adam 업데이트는 “거의 저랭크”라 소수 방향이 지배하고, 직교화는 업데이트에서는 작지만 학습에는 중요한 “드문 방향(rare directions)“의 스케일을 키워 준다는 것이다.
이 그림은 등고선이 정확한 2방향 장난감이고, 벤치마크가 아니라 방향을 보여 준다. 실제(작은) 비교는 아래 NumPy 실험이 한다.
2. 어떤 매개변수가 Muon을 쓰고 어떤 것이 AdamW에 남는가
Muon은 은닉 활성에 선형 사상으로 작용하는 2차원 가중치를 위한 것이다. 나머지는 AdamW를 쓰고, 제외마다 이유가 있다.
- 임베딩. 입력이 one-hot 토큰이라 자연스러운 입력 노름은 RMS가 아니라 이다. Embed 층을 노름으로 쌍대화하면 가 아니라 열별 정규화(토큰 벡터마다 따로 정규화)가 나온다(Bernstein & Newhouse). 표 전체를 직교화하면 배치에서 함께 나오지도 않은 토큰들이 엮인다.
- LM head. Jordan은 실험에 근거해 “임베딩과 마지막 분류 head”에 AdamW를 권한다. 출력이 또 다른 RMS 정규화 층이 아니라 어휘 전체에 대한 softmax로 간다.
- 벡터(norm gain, bias, head별 스칼라). 벡터 에 대해 , 즉 좌표별 적응성이 없는 정규화 SGD가 된다. 활용할 행렬 구조가 없다.
- 라우터 등 “각 행이 따로 노는” 행렬. Qwen3.8-Flash-Next는 MoE 라우터를 AdamW에 남겼다. Muon이 초반 요동을 키워 라우팅을 불안정하게 했고, 출력 차원 하나가 expert 하나라 공유된 선형 구조가 없다는 이유다(보고서).
- 합쳐진 행렬은 쪼갠다. Jordan은 QKV를 합친 행렬보다 를 따로 직교화할 때 Muon이 낫다고 적었다. Qwen3.8은 합쳐진 QKV와 gate/up을 head별·절반별로 쪼개고, GLM-5의 Muon Split과 K3의 Per-Head Muon은 attention head 블록마다 따로 직교화해서 기울기가 큰 head가 공유된 직교 업데이트를 지배하지 않게 한다(GLM-5, K3).
- 합성곱 필터는 마지막 세 차원을 펼쳐 2차원으로 본다.
3. Newton–Schulz: 행렬곱 다섯 번으로
매 step 행렬마다 SVD를 하는 것은 가속기에서 너무 느리고 bf16에서 불안정하다. Muon은 대신 행렬곱만 필요한 홀수 행렬 다항식을 쓴다.
홀수 다항식은 특이값에 작용한다
, 라 하자. 그러면 , 이므로
이다. 특이벡터는 절대 바뀌지 않고, 각 특이값이 스칼라 함수 를 통과한다. 번 반복은 를 적용한다. 그러니 직교화란 번 합성한 가 의 모든 를 1 근처로 보내도록 를 설계하는 일이다. 안에서 출발하려고 Frobenius 노름으로 나눈다. 이기 때문이다. (같은 논리로 에 대해 이므로 이 정규화는 손해가 없다.)
고전 계수는 어디서 오는가
극분해 인자는 다. 로 두고 로 전개한다().
- 한 항까지: — cubic Newton–Schulz 반복,
- 두 항까지: — 고전 quintic
근처에서는 빠르다. 로 두면 cubic은 (2차 수렴, ), quintic은 (3차 수렴)이다. 근처에서는 느리다. 이므로 을 1 수준으로 올리는 데 대략 단계가 든다. 이면 로 17단계, 로 11단계다. 기울기 행렬에는 아주 작은 특이값이 많고, Frobenius 정규화가 그것을 더 작게 만든다.
Jordan의 거래: 가파른 기울기, 정확한 수렴은 포기
Jordan의 계수 는 반복값이 1로 수렴하는 대신 1 근처 띠 안에 머문다는 조건 아래 0에서의 기울기 를 최대화한 것이다. 면 에 대략 단계면 된다. 대가는 고정점에서 보인다. 는 , 즉 에 대한 이차식이고 근은 과 다. 거기서 , 로 둘 다 이므로 어느 쪽도 안정하지 않고, 반복값은 정착하지 못한 채 띠 안을 계속 튄다(수치적으로 많이 반복하면 ). 기준 코드의 docstring은 출력이 “인 비슷한 것”이며 “모델 성능을 전혀 해치지 않는다”고 적었다. Moonlight는 10단계(더 정확함)가 5단계보다 낫지 않았다고 보고했다.
더 나은 다항식: hybrid와 Polar Express
- DeepSeek-V4는 Jordan 계수로 8단계를 돈 뒤 로 2단계를 더 돈다. 이 다항식은 , 이라 2차 수렴으로 띠를 평평하게 만든다(보고서).
- Polar Express(Amsel et al. 2025)는 단계마다 다른 quintic을 고른다. 지금 특이값들이 놓인 구간 에서 최악의 을 최소화하는 다항식이다. 단계별로 탐욕적으로 고르는 것이 최적 합성임을 증명했다. 용으로 만든 첫 다항식은 기울기 이고, 뒤로 갈수록 고전 에 가까워진다. 논문은 Jordan 다항식이 “오차 ≈0.3에서 정체한다”고 하며, GPT-2-Large를 1B 토큰 학습했을 때 최고 검증 손실이 Polar Express 3.340, Jordan 계수 3.398이었다(weight decay를 쓴 10B 토큰 실험에서는 2.913 대 2.921로 차이가 작다). Qwen3.8-Flash-Next는 Polar Express 8단계를 쓴다.
import numpy as np
def polar(G):
"""Exact polar factor (msign) via SVD: G = U S V^T -> U V^T."""
U, s, Vt = np.linalg.svd(G, full_matrices=False)
return U @ Vt, s
def newton_schulz(G, coeffs, eps=1e-7, pre=1.0):
"""Odd-polynomial iteration X <- aX + b(XX^T)X + c(XX^T)^2 X, one (a, b, c) per step."""
X = G / (pre * np.linalg.norm(G) + eps) # Frobenius-normalise: every sigma <= 1
tall = X.shape[0] > X.shape[1]
if tall: X = X.T # iterate on the wide side: X X^T is the small Gram
for a, b, c in coeffs:
A = X @ X.T
X = a * X + (b * A + c * A @ A) @ X
return X.T if tall else X
rng = np.random.default_rng(0)
# (1) max <G, D> over ||D||_2 <= 1 is attained at D = U V^T and equals the nuclear norm
G = rng.normal(size=(6, 4)) @ np.diag([3, 1, 0.3, 0.03]) @ rng.normal(size=(4, 4))
O, s = polar(G)
D = rng.normal(size=(2000, 6, 4))
D /= np.linalg.norm(D, ord=2, axis=(1, 2))[:, None, None] # 2000 random D with ||D||_2 = 1
print(f"<G, UV^T> = {(G * O).sum():.4f} nuclear norm = {s.sum():.4f} best random D: {(D * G).sum((1, 2)).max():.4f}")
print(f"||UV^T||_2 = {np.linalg.norm(O, 2):.4f} sign(G) has ||.||_2 = {np.linalg.norm(np.sign(G), 2):.2f}")
Q1, _ = np.linalg.qr(rng.normal(size=(6, 6))); Q2, _ = np.linalg.qr(rng.normal(size=(4, 4)))
print("msign(Q1 G Q2) == Q1 msign(G) Q2 :", np.allclose(polar(Q1 @ G @ Q2)[0], Q1 @ O @ Q2),
"| sign(Q1 G Q2) == Q1 sign(G) Q2 :", np.allclose(np.sign(Q1 @ G @ Q2), Q1 @ np.sign(G) @ Q2))
# (2) Jordan's quintic: fixed points p(x) = x <=> a + b x^2 + c x^4 = 1, and the slope there
a, b, c = 3.4445, -4.7750, 2.0315
xs = np.sqrt(np.sort(np.roots([c, b, a - 1]).real))
print("fixed points:", np.round(xs, 4), " p'(x) there:", np.round(a + 3 * b * xs**2 + 5 * c * xs**4, 3))
x = np.logspace(-4, 0, 2000)
for _ in range(40):
x = a * x + b * x**3 + c * x**5
print(f"after 40 iterations every x0 in [1e-4, 1] sits in [{x.min():.3f}, {x.max():.3f}]")
# (3) five NS steps vs the exact polar factor, 64 x 192 matrix with condition number 1e3
PRESETS = {
"cubic NS ": [(1.5, -0.5, 0.0)] * 5,
"classic 15/8 ": [(15 / 8, -10 / 8, 3 / 8)] * 5,
"Jordan ": [(3.4445, -4.7750, 2.0315)] * 5,
"Polar Express": [(8.2373, -23.1577, 16.6806), (4.0824, -2.8930, 0.5253), (3.9263, -2.8547, 0.5318),
(3.2982, -2.4245, 0.4863), (2.2970, -1.6366, 0.4003)],
}
m, n = 64, 192
U, _ = np.linalg.qr(rng.normal(size=(n, m))); V, _ = np.linalg.qr(rng.normal(size=(m, m)))
M = (U * np.logspace(0, -3, m)) @ V.T
exact, _ = polar(M)
for name, co in PRESETS.items():
X = newton_schulz(M, co, pre=1.01 if name.startswith("Polar") else 1.0)
so = np.linalg.svd(X, compute_uv=False)
print(f"{name} 5 steps: sigma in [{so.min():.3f}, {so.max():.3f}] ||X - UV^T||_F / ||UV^T||_F = "
f"{np.linalg.norm(X - exact) / np.linalg.norm(exact):.3f}")Expected output: equals the nuclear norm exactly while the best of 2,000 random unit-spectral-norm candidates falls short; has spectral norm 1 while — Adam’s direction — has spectral norm above 4 for the same max-entry size; msign commutes with rotations and sign does not. The two fixed points come out at 0.868 and 1.264 with slopes −1.58 and 6.47, and the long-run band is [0.68, 1.13]. After five steps on a κ = 10³ matrix, the cubic and classic quintic leave the smallest singular value near 0.01 or below, Jordan’s lifts it to about 0.2 and Polar Express to about 0.4, with relative errors of roughly 0.78, 0.68, 0.31 and 0.17.
4. How big is the step: RMS matching and weight decay
The RMS of an orthogonal update depends on the shape
For a full-rank matrix, has singular values equal to 1, so and
Only the larger dimension matters. A projection and a expert matrix share and get the same per-entry step , but a matrix gets — larger from the same . Moonlight (Liu et al. 2025) states this as Lemma 1 (a full-rank matrix has theoretical Muon update RMS ) and cancels it by scaling every update by (their Eq. 4). For an ideal full-rank polar update this sets the update RMS to exactly 0.2 (a Newton–Schulz approximation or a rank-deficient update lands somewhat below, as the small-matrix experiment after §5 shows), chosen because “AdamW’s update RMS is usually around 0.2 to 0.4”. Then AdamW’s learning rate and weight decay can be reused: one drives both the Muon matrices and the AdamW parameters. In their 800M ablation, this per-matrix adjustment reached validation loss 2.789 versus 2.812 for a single global factor; RMS 0.2 and 0.4 performed similarly. Kimi K2 and GLM-4.5 use 0.2, DeepSeek-V4 uses 0.18.
The scale fixes what the learning rate means:
| Convention | Factor | Spectral norm of the step | Typical lr |
|---|---|---|---|
Jordan (original) | for — “lr in units of spectral norm per update” | 0.02 | |
Bernstein (spectral_unclamped) | , i.e. RMS→RMS norm | ||
Moonlight (match_rms_adamw) | AdamW’s, e.g. 2e-4 for K2 |
(original, spectral_unclamped and match_rms_adamw are the adjust_lr_fn names in torch.optim.Muon.) The last row matters for §6: with RMS matching, a -wide matrix takes a step of spectral norm .
Weight decay: necessary, and a weak cap
Moonlight found that without weight decay “both the weight and the layer output’s RMS keep growing to a large scale, exceeding the high-precision range of bf16”, and added decoupled decay: . How far does it cap growth? Take the worst case, where every update pushes the same top singular direction (the update has spectral norm exactly ):
The learning rate cancels: the cap depends only on the shape and . For and it is about 169 — enormous for a matrix whose initial spectral norm is around 1–2. Weight decay bounds the drift; it does not keep any single direction small. Keep this number in mind for §6.
5. Cost and distributed implementation
FLOPs. For an momentum with (iterate on the wide side), one quintic step costs : , : , : , i.e. . The forward+backward of that matrix on a batch of tokens costs . So steps add at most
of the layer’s training FLOPs — Jordan’s bound. For the NanoGPT speedrun (, ) it is 0.7%; for a Llama-405B-like setting (, M tokens) 0.5%. Muon is also lighter in memory than AdamW: one buffer () instead of two (, ).
The real problem is that NS needs the whole matrix, while large-scale training shards everything: ZeRO splits optimizer state and gradients across data-parallel (DP) ranks, and tensor parallelism splits the weight itself. Elementwise AdamW does not care; Muon does. Published answers:
- Gather, compute, keep your slice (Moonlight’s Distributed Muon, on ZeRO-1). Reduce-scatter gradients → update the local momentum shard → DP-gather the full momentum → run NS on the full matrix → keep the local slice of the update → all-gather parameters as usual. The paper reports communication between 1× and 1.25× of distributed AdamW and an optimizer step of 1–3% of forward–backward time.
- Own whole matrices. Jordan’s reference
Muonsorts matrices by size, assigns them round-robin to ranks, runs NS locally and all-gathers the updated parameters. The catch is load balance: NS cost is cubic in the short side, so equal-element partitions create stragglers. Qwen3.8’s Canzona reassigns whole parameters to DP ranks to balance NS cost; MAI-Base-2 groups same-shape matrices, all-to-alls them so each GPU holds a few whole matrices, and sends results back with another all-to-all — 2.1% of iteration time (165 ms against a 55 ms communication-bound minimum); GLM-5 lists a zero-redundancy Muon all-gather (MAI-Base-2, Qwen3.8). - Pipelining. Matrices are independent, so the gather of matrix can overlap the NS of matrix ; per-head splitting creates many small NS calls that Qwen3.8 captures in a CUDA graph.
- Don’t gather at all. Dion (Ahn et al. 2025) replaces NS with amortised power iteration on the momentum, producing a low-rank orthonormal update with error feedback that works directly on sharded matrices; the rank fraction trades update quality for cost. It was tested from 160M to 3B parameters.
import numpy as np
def polar(G):
"""SVD로 구한 정확한 극분해 인자(msign): G = U S V^T -> U V^T."""
U, s, Vt = np.linalg.svd(G, full_matrices=False)
return U @ Vt, s
def newton_schulz(G, coeffs, eps=1e-7, pre=1.0):
"""홀수 다항식 반복 X <- aX + b(XX^T)X + c(XX^T)^2 X, 단계마다 (a, b, c) 하나."""
X = G / (pre * np.linalg.norm(G) + eps) # Frobenius 정규화: 모든 sigma <= 1
tall = X.shape[0] > X.shape[1]
if tall: X = X.T # 넓은 쪽으로 반복: X X^T가 작은 Gram 행렬
for a, b, c in coeffs:
A = X @ X.T
X = a * X + (b * A + c * A @ A) @ X
return X.T if tall else X
rng = np.random.default_rng(0)
# (1) ||D||_2 <= 1에서 <G, D>의 최댓값은 D = U V^T에서 나오고 핵 노름과 같다
G = rng.normal(size=(6, 4)) @ np.diag([3, 1, 0.3, 0.03]) @ rng.normal(size=(4, 4))
O, s = polar(G)
D = rng.normal(size=(2000, 6, 4))
D /= np.linalg.norm(D, ord=2, axis=(1, 2))[:, None, None] # ||D||_2 = 1인 무작위 D 2000개
print(f"<G, UV^T> = {(G * O).sum():.4f} 핵 노름 = {s.sum():.4f} 무작위 D 최고: {(D * G).sum((1, 2)).max():.4f}")
print(f"||UV^T||_2 = {np.linalg.norm(O, 2):.4f} sign(G)의 ||.||_2 = {np.linalg.norm(np.sign(G), 2):.2f}")
Q1, _ = np.linalg.qr(rng.normal(size=(6, 6))); Q2, _ = np.linalg.qr(rng.normal(size=(4, 4)))
print("msign(Q1 G Q2) == Q1 msign(G) Q2 :", np.allclose(polar(Q1 @ G @ Q2)[0], Q1 @ O @ Q2),
"| sign(Q1 G Q2) == Q1 sign(G) Q2 :", np.allclose(np.sign(Q1 @ G @ Q2), Q1 @ np.sign(G) @ Q2))
# (2) Jordan quintic의 고정점: p(x) = x <=> a + b x^2 + c x^4 = 1, 그리고 거기서의 기울기
a, b, c = 3.4445, -4.7750, 2.0315
xs = np.sqrt(np.sort(np.roots([c, b, a - 1]).real))
print("고정점:", np.round(xs, 4), " 그곳의 p'(x):", np.round(a + 3 * b * xs**2 + 5 * c * xs**4, 3))
x = np.logspace(-4, 0, 2000)
for _ in range(40):
x = a * x + b * x**3 + c * x**5
print(f"40번 반복 뒤 [1e-4, 1]의 모든 x0이 [{x.min():.3f}, {x.max():.3f}] 안에 있다")
# (3) NS 5단계 대 정확한 극분해 인자, 조건수 1e3인 64 x 192 행렬
PRESETS = {
"cubic NS ": [(1.5, -0.5, 0.0)] * 5,
"classic 15/8 ": [(15 / 8, -10 / 8, 3 / 8)] * 5,
"Jordan ": [(3.4445, -4.7750, 2.0315)] * 5,
"Polar Express": [(8.2373, -23.1577, 16.6806), (4.0824, -2.8930, 0.5253), (3.9263, -2.8547, 0.5318),
(3.2982, -2.4245, 0.4863), (2.2970, -1.6366, 0.4003)],
}
m, n = 64, 192
U, _ = np.linalg.qr(rng.normal(size=(n, m))); V, _ = np.linalg.qr(rng.normal(size=(m, m)))
M = (U * np.logspace(0, -3, m)) @ V.T
exact, _ = polar(M)
for name, co in PRESETS.items():
X = newton_schulz(M, co, pre=1.01 if name.startswith("Polar") else 1.0)
so = np.linalg.svd(X, compute_uv=False)
print(f"{name} 5단계: sigma ∈ [{so.min():.3f}, {so.max():.3f}] ||X - UV^T||_F / ||UV^T||_F = "
f"{np.linalg.norm(X - exact) / np.linalg.norm(exact):.3f}")기대 출력: 은 핵 노름과 정확히 같고, 스펙트럼 노름 1인 무작위 후보 2,000개 중 최고도 그에 못 미친다. 의 스펙트럼 노름은 1인데, 같은 원소 최대 크기의 (Adam의 방향)는 4를 넘는다. msign은 회전과 교환되고 sign은 그렇지 않다. 두 고정점은 0.868과 1.264, 기울기는 −1.58과 6.47이고, 오래 돌린 뒤의 띠는 [0.68, 1.13]이다. κ = 10³ 행렬에서 5단계 뒤 cubic과 고전 quintic은 가장 작은 특이값을 0.01 근처 이하에 남기고, Jordan은 약 0.2, Polar Express는 약 0.4까지 올린다. 상대 오차는 대략 0.78, 0.68, 0.31, 0.17이다.
4. 걸음은 얼마나 큰가: RMS 맞춤과 weight decay
직교 업데이트의 RMS는 모양에 따라 다르다
full rank인 행렬에서 는 특이값 개가 모두 1이므로 이고
이다. 큰 쪽 차원만 중요하다. projection과 expert 행렬은 이 같아 원소당 걸음도 로 같지만, 행렬은 로, 같은 에서 배 크다. Moonlight(Liu et al. 2025)는 이것을 Lemma 1(full rank인 행렬의 이론적 Muon 업데이트 RMS는 )로 정리하고, 모든 업데이트에 를 곱해(논문의 식 4) 이를 상쇄한다. 이상적인 full rank polar 업데이트 라면 업데이트 RMS가 정확히 0.2가 된다(Newton–Schulz 근사나 rank가 모자란 업데이트는 §5 실험에서 보듯 조금 아래에 머문다. §5 뒤의 작은 행렬 실험이 그 예다). “AdamW의 업데이트 RMS가 보통 0.2–0.4”라서 고른 값이다. 그러면 AdamW의 학습률과 weight decay를 그대로 쓸 수 있다. 하나가 Muon 행렬과 AdamW 매개변수를 함께 움직인다. 800M 모델 ablation에서 행렬별로 맞춘 이 방식은 검증 손실 2.789로, 전역 인자 하나를 쓴 2.812보다 나았고, RMS 0.2와 0.4는 비슷했다. Kimi K2와 GLM-4.5는 0.2, DeepSeek-V4는 0.18을 쓴다.
스케일이 학습률의 의미를 정한다.
| 방식 | 인자 | 걸음의 스펙트럼 노름 | 전형적 lr |
|---|---|---|---|
Jordan (original) | 이면 — “업데이트당 스펙트럼 노름 단위의 lr” | 0.02 | |
Bernstein (spectral_unclamped) | , 즉 RMS→RMS 노름 | ||
Moonlight (match_rms_adamw) | AdamW 값, 예: K2의 2e-4 |
(original, spectral_unclamped, match_rms_adamw는 torch.optim.Muon의 adjust_lr_fn 이름이다.) 마지막 행은 §6에서 중요하다. RMS를 맞추면 폭 7168인 행렬은 스펙트럼 노름 짜리 걸음을 간다.
weight decay: 필요하지만 느슨한 상한
Moonlight는 weight decay 없이는 “가중치와 층 출력의 RMS가 계속 커져 bf16의 고정밀 범위를 넘어간다”는 것을 발견하고 분리된 decay를 더했다. . 이것이 성장을 어디서 막을까? 최악의 경우, 즉 모든 업데이트가 같은 최상위 특이 방향을 민다고 하자(업데이트의 스펙트럼 노름은 정확히 ).
학습률이 약분된다. 상한은 모양과 에만 달려 있다. , 이면 약 169다. 초기 스펙트럼 노름이 1–2 정도인 행렬에게는 엄청난 값이다. weight decay는 표류를 묶을 뿐, 특정 방향 하나를 작게 유지해 주지는 않는다. 이 숫자를 §6까지 기억해 두자.
5. 비용과 분산 구현
FLOPs. 인 momentum(넓은 쪽으로 반복)에서 quintic 한 단계는 : , : , : , 합쳐서 이다. 그 행렬의 토큰 배치 forward+backward는 다. 따라서 단계가 더하는 몫은 많아야
이다(Jordan의 상한). NanoGPT speedrun(, )에서는 0.7%, Llama-405B 같은 설정(, M 토큰)에서는 0.5%다. 메모리도 AdamW보다 가볍다. 버퍼가 둘(, )이 아니라 하나()다.
진짜 문제는 NS가 행렬 전체를 필요로 한다는 것이다. 대규모 학습은 모든 것을 쪼갠다. ZeRO는 optimizer 상태와 기울기를 data-parallel(DP) rank들에 나누고, tensor parallelism은 가중치 자체를 나눈다. 원소별인 AdamW는 상관없지만 Muon은 다르다. 공개된 해법:
- 모으고, 계산하고, 내 조각만 남긴다(Moonlight의 Distributed Muon, ZeRO-1 기반). 기울기 reduce-scatter → 로컬 momentum 조각 갱신 → 전체 momentum을 DP-gather → 전체 행렬에 NS → 업데이트의 로컬 조각만 남김 → 평소처럼 매개변수 all-gather. 논문은 통신량이 분산 AdamW의 1–1.25배, optimizer step이 forward–backward 시간의 1–3%라고 보고한다.
- 행렬을 통째로 맡는다. Jordan의 기준
Muon은 행렬을 크기순으로 정렬해 rank들에 돌아가며 배정하고, 로컬에서 NS를 돌린 뒤 갱신된 매개변수를 all-gather한다. 문제는 부하 균형이다. NS 비용은 짧은 변의 세제곱이라 원소 수로 똑같이 나누면 낙오자(straggler)가 생긴다. Qwen3.8의 Canzona는 NS 비용이 균형을 이루도록 매개변수를 통째로 DP rank에 다시 배정한다. MAI-Base-2는 같은 모양의 행렬을 묶어 all-to-all로 보내 GPU마다 행렬 몇 개를 통째로 갖게 하고, 결과를 다른 all-to-all로 돌려보낸다. 반복 시간의 2.1%(165 ms, 통신 한계 이론값 55 ms)다. GLM-5는 zero-redundancy Muon all-gather를 적었다(MAI-Base-2, Qwen3.8). - 파이프라이닝. 행렬들은 서로 독립이라 번 행렬의 gather를 번 행렬의 NS와 겹칠 수 있다. head별로 쪼개면 작은 NS 호출이 많이 생기는데, Qwen3.8은 이것을 CUDA graph로 묶는다.
- 아예 모으지 않는다. Dion(Ahn et al. 2025)은 NS를 momentum에 대한 amortized power iteration으로 바꿔, error feedback을 곁들인 저랭크 직교 업데이트를 sharded 행렬 위에서 바로 만든다. rank 비율로 업데이트 품질과 비용을 맞바꾼다. 160M–3B 매개변수에서 시험했다.
Muon against AdamW on a small matrix problem
A two-layer linear network () learns a teacher with a decaying spectrum from inputs whose covariance is ill-conditioned (eigenvalues ) and rotated away from the coordinate axes. Each optimizer gets 150 minibatch steps with linear decay and a small learning-rate grid; Muon uses Nesterov momentum 0.95, five NS steps and Moonlight’s RMS matching.
def ns5(G, steps=5, eps=1e-7):
return newton_schulz(G, [(3.4445, -4.7750, 2.0315)] * steps, eps)
def erank(s): # effective rank exp(H(p)), p = s / sum(s)
p = s / s.sum(); return float(np.exp(-(p * np.log(p + 1e-30)).sum()))
rng = np.random.default_rng(0)
d_in, d_h, d_out, N = 48, 64, 32, 4096
Ux, _ = np.linalg.qr(rng.normal(size=(d_in, d_in))) # random rotation of the input basis
cx = np.arange(1, d_in + 1) ** -2.0 # input covariance eigenvalues
Xtr = (rng.normal(size=(N, d_in)) * np.sqrt(cx)) @ Ux.T
Ut, _ = np.linalg.qr(rng.normal(size=(d_out, d_out))); Vt, _ = np.linalg.qr(rng.normal(size=(d_in, d_out)))
Wstar = (Ut * (3 * np.arange(1, d_out + 1) ** -0.5)) @ Vt.T # teacher, decaying spectrum
Ytr = Xtr @ Wstar.T + 0.01 * rng.normal(size=(N, d_out))
Xte = (rng.normal(size=(2048, d_in)) * np.sqrt(cx)) @ Ux.T
Yte = Xte @ Wstar.T
def test_loss(W):
return 0.5 * ((Xte @ W[0].T @ W[1].T - Yte) ** 2).sum(1).mean()
def grads(W, X, Y):
H = X @ W[0].T
R = H @ W[1].T - Y
return [(R @ W[1]).T @ X / len(X), R.T @ H / len(X)]
def train(opt, lr, steps=150, B=128):
r = np.random.default_rng(1)
W = [r.normal(size=(d_h, d_in)) / np.sqrt(d_in), 0.1 * r.normal(size=(d_out, d_h)) / np.sqrt(d_h)]
m = [np.zeros_like(w) for w in W]; v = [np.zeros_like(w) for w in W]
first = None
for t in range(1, steps + 1):
idx = r.integers(0, N, B)
G = grads(W, Xtr[idx], Ytr[idx])
lr_t = lr * (1 - t / (steps + 1)) # linear decay
for i in range(2):
if opt == "SGD-m":
m[i] = 0.9 * m[i] + G[i]; u = m[i]
elif opt == "AdamW": # betas (0.9, 0.95)
m[i] = 0.9 * m[i] + 0.1 * G[i]; v[i] = 0.95 * v[i] + 0.05 * G[i] ** 2
u = (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.95 ** t)) + 1e-8)
else: # Muon: Nesterov, NS5, RMS matched to 0.2
m[i] = 0.95 * m[i] + G[i]
u = ns5(0.95 * m[i] + G[i]) * 0.2 * np.sqrt(max(W[i].shape))
if t == 1 and i == 1: # look at the first W2 update
first = (np.linalg.svd(G[i], compute_uv=False), np.linalg.svd(u, compute_uv=False), np.sqrt((u ** 2).mean()))
W[i] = W[i] - lr_t * u
if not np.isfinite(W[0]).all() or np.abs(W[0]).max() > 1e3:
return np.inf, first
return test_loss(W), first
print(f"initial test loss {test_loss([np.zeros((d_h, d_in)), np.zeros((d_out, d_h))]):.3f}")
GRID = {"SGD-m": [0.1, 0.3, 1.0], "AdamW": [3e-3, 1e-2, 3e-2, 1e-1], "Muon": [1e-2, 3e-2, 1e-1]}
for opt, grid in GRID.items():
res = [(train(opt, lr), lr) for lr in grid]
(best, first), lr = min(res, key=lambda z: z[0][0])
sg, su, rms = first
print(f"{opt:5s} test loss by lr: " + " ".join(f"{lr:g}:{r[0]:.4f}" for r, lr in res)
+ f" | best {best:.5f} @ lr {lr:g}")
print(f" step-1 W2 update: effective rank G {erank(sg):.1f} -> update {erank(su):.1f} (of 32), update RMS = {rms:.3f}")At the best learning rate of each, Muon ends around , AdamW around and SGD-momentum around (from 0.606). The first update shows why: the gradient of has an effective rank of about 4 of 32, SGD keeps it at 4, Adam’s elementwise normalisation spreads it to about 16, and Muon’s orthogonalisation to about 28. Two side notes. Muon’s update RMS is 0.145, not 0.2, because the momentum is rank-deficient on step 1 and five NS steps leave the small singular values below 1 — the 0.2 figure assumes a full-rank, fully orthogonalised update. And Adam’s first update has RMS exactly 1, because a bias-corrected first step is ; its typical 0.2–0.4 appears only once noise makes smaller than 1. This is one small, rotated, ill-conditioned problem: it shows the mechanism, not a general ranking. Moonlight’s scaling-law fits are the evidence at scale: Muon matched AdamW with about 52% of the training FLOPs under compute-optimal settings.
6. MuonClip: why attention logits explode, and QK-Clip
The bound and the observation
An attention logit is with , . With RMS-normalised inputs, is fixed, so
and logits can only grow through the spectral norms of and . Kimi K2 reports that a 9B-active / 53B-total MoE trained with vanilla Muon saw its max attention logit “quickly exceed a magnitude of 1000”. Moonlight had already noted that some layers’ max logits exceeded 100 early in training and that AdamW “demonstrated healthier behavior” on this metric.
Why Muon makes it worse (K2, App. E, stated as a hypothesis)
- Full-rank updates. has all singular values equal, so it always carries a component along every singular direction of the weight, including the top one. Adam’s updates are dominated by a few directions.
- Additive growth on alignment. If the update’s singular pair aligns with the weight’s top pair, that singular value grows additively. With RMS matching each step can add up to (§4), so and can each grow linearly in steps, and the logit bound — their product — quadratically.
- Bilinear amplification. The logit depends on ; growth in either factor multiplies.
- Weight decay doesn’t stop it: the §4 cap is far above any healthy logit.
Why not soft-capping or QK-Norm
A logit soft-cap () bounds what the softmax sees, but itself — and the weights — keep growing behind it. QK-Norm (normalise and per head) is the standard fix in MHA/GQA models (see stability components), but K2 uses MLA, whose per-head keys “are not fully materialized during inference”, so there is nothing to normalise. (DeepSeek-V4 sidesteps the problem differently: it applies RMSNorm to each query head and the KV entries, and needs no QK-Clip; GLM-5 found logits stable with per-head Muon Split.)
The QK-Clip rule, derived
Let be head ‘s max logit in the current batch (already computed in the forward pass). After the optimizer step, if , set and rescale
Every logit of head is bilinear in , so it is multiplied by exactly, and the largest one on this batch lands exactly on . The rest of the attention pattern is unchanged up to that temperature-like factor. Design choices:
- When. The step’s forward and backward are untouched; only decides how much to shrink the weights for the next step. It is a projection onto “max logit ≤ τ” applied after the update, not a loss term.
- splits the shrink evenly between and ; the figure below lets you move it.
- Per head. The naive version uses one for the whole layer and over-regularises healthy heads; in K2 only a few heads explode.
- MLA. A head’s logit is (content part + decoupled RoPE part), where is shared by all heads. Scaling by each scales the content term by ; the RoPE term must also scale by , and since cannot be touched without affecting every other head, takes the whole factor .
K2 trained with : the max logit sat at the cap early on and decayed into a stable range after about 30% of training; in the first 70,000 steps 12.7% of heads triggered QK-Clip at least once, and after that every head had dropped below 100 and the clip went inactive. In a 0.5B-active / 3B-total ablation an aggressive had a negligible effect on the loss curve.
작은 행렬 문제에서 Muon 대 AdamW
2층 선형 망 ()가 스펙트럼이 감소하는 teacher를 배운다. 입력의 공분산은 조건수가 나쁘고(고유값 ) 좌표축에서 회전되어 있다. 각 옵티마이저는 선형 감쇠로 미니배치 150 step, 작은 학습률 격자를 받는다. Muon은 Nesterov momentum 0.95, NS 5단계, Moonlight의 RMS 맞춤을 쓴다.
def ns5(G, steps=5, eps=1e-7):
return newton_schulz(G, [(3.4445, -4.7750, 2.0315)] * steps, eps)
def erank(s): # effective rank exp(H(p)), p = s / sum(s)
p = s / s.sum(); return float(np.exp(-(p * np.log(p + 1e-30)).sum()))
rng = np.random.default_rng(0)
d_in, d_h, d_out, N = 48, 64, 32, 4096
Ux, _ = np.linalg.qr(rng.normal(size=(d_in, d_in))) # 입력 기저의 무작위 회전
cx = np.arange(1, d_in + 1) ** -2.0 # 입력 공분산 고유값
Xtr = (rng.normal(size=(N, d_in)) * np.sqrt(cx)) @ Ux.T
Ut, _ = np.linalg.qr(rng.normal(size=(d_out, d_out))); Vt, _ = np.linalg.qr(rng.normal(size=(d_in, d_out)))
Wstar = (Ut * (3 * np.arange(1, d_out + 1) ** -0.5)) @ Vt.T # teacher, 감소하는 스펙트럼
Ytr = Xtr @ Wstar.T + 0.01 * rng.normal(size=(N, d_out))
Xte = (rng.normal(size=(2048, d_in)) * np.sqrt(cx)) @ Ux.T
Yte = Xte @ Wstar.T
def test_loss(W):
return 0.5 * ((Xte @ W[0].T @ W[1].T - Yte) ** 2).sum(1).mean()
def grads(W, X, Y):
H = X @ W[0].T
R = H @ W[1].T - Y
return [(R @ W[1]).T @ X / len(X), R.T @ H / len(X)]
def train(opt, lr, steps=150, B=128):
r = np.random.default_rng(1)
W = [r.normal(size=(d_h, d_in)) / np.sqrt(d_in), 0.1 * r.normal(size=(d_out, d_h)) / np.sqrt(d_h)]
m = [np.zeros_like(w) for w in W]; v = [np.zeros_like(w) for w in W]
first = None
for t in range(1, steps + 1):
idx = r.integers(0, N, B)
G = grads(W, Xtr[idx], Ytr[idx])
lr_t = lr * (1 - t / (steps + 1)) # 선형 감쇠
for i in range(2):
if opt == "SGD-m":
m[i] = 0.9 * m[i] + G[i]; u = m[i]
elif opt == "AdamW": # betas (0.9, 0.95)
m[i] = 0.9 * m[i] + 0.1 * G[i]; v[i] = 0.95 * v[i] + 0.05 * G[i] ** 2
u = (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.95 ** t)) + 1e-8)
else: # Muon: Nesterov, NS5, RMS 0.2로 맞춤
m[i] = 0.95 * m[i] + G[i]
u = ns5(0.95 * m[i] + G[i]) * 0.2 * np.sqrt(max(W[i].shape))
if t == 1 and i == 1: # 첫 W2 업데이트를 살펴본다
first = (np.linalg.svd(G[i], compute_uv=False), np.linalg.svd(u, compute_uv=False), np.sqrt((u ** 2).mean()))
W[i] = W[i] - lr_t * u
if not np.isfinite(W[0]).all() or np.abs(W[0]).max() > 1e3:
return np.inf, first
return test_loss(W), first
print(f"초기 test loss {test_loss([np.zeros((d_h, d_in)), np.zeros((d_out, d_h))]):.3f}")
GRID = {"SGD-m": [0.1, 0.3, 1.0], "AdamW": [3e-3, 1e-2, 3e-2, 1e-1], "Muon": [1e-2, 3e-2, 1e-1]}
for opt, grid in GRID.items():
res = [(train(opt, lr), lr) for lr in grid]
(best, first), lr = min(res, key=lambda z: z[0][0])
sg, su, rms = first
print(f"{opt:5s} lr별 test loss: " + " ".join(f"{lr:g}:{r[0]:.4f}" for r, lr in res)
+ f" | 최고 {best:.5f} @ lr {lr:g}")
print(f" 1 step W2 업데이트: effective rank G {erank(sg):.1f} -> 업데이트 {erank(su):.1f} (32 중), 업데이트 RMS = {rms:.3f}")각자의 최적 학습률에서 Muon은 약 , AdamW는 약 , SGD-momentum은 약 에서 끝난다(시작 0.606). 첫 업데이트가 이유를 보여 준다. 의 기울기는 effective rank가 32 중 약 4이고, SGD는 4 그대로, Adam의 원소별 정규화는 약 16으로, Muon의 직교화는 약 28로 펼친다. 곁가지 두 가지. Muon의 업데이트 RMS가 0.2가 아니라 0.145인 것은 1 step의 momentum이 rank가 모자라고 NS 5단계가 작은 특이값을 1 아래에 남기기 때문이다. 0.2라는 값은 full rank이고 완전히 직교화된 업데이트를 가정한다. 그리고 Adam의 첫 업데이트 RMS가 정확히 1인 것은 편향 보정된 첫 걸음이 이기 때문이다. 전형적인 0.2–0.4는 잡음 때문에 가 1보다 작아진 뒤에야 나온다. 이것은 작고, 회전되고, 조건수가 나쁜 문제 하나다. 메커니즘을 보여 줄 뿐 일반적인 순위가 아니다. 대규모에서의 근거는 Moonlight의 스케일링 법칙 적합이다. compute-optimal 설정에서 Muon은 AdamW의 학습 FLOPs 약 52% 로 같은 성능을 냈다.
6. MuonClip: attention logit은 왜 폭주하고, QK-Clip은 무엇을 하나
상한과 관찰
attention logit은 , 에 대해 다. 입력이 RMS 정규화되어 가 고정이므로
이고, logit은 , 의 스펙트럼 노름을 통해서만 커질 수 있다. Kimi K2는 vanilla Muon으로 학습한 9B 활성 / 53B 전체 MoE에서 최대 attention logit이 “금세 1000을 넘었다”고 보고했다. Moonlight도 일부 층의 최대 logit이 학습 초반 100을 넘었고 이 지표에서 AdamW가 “더 건강한 거동을 보였다”고 이미 적었다.
왜 Muon에서 더 심한가(K2 App. E, 가설로 제시)
- full rank 업데이트. 는 특이값이 모두 같아서 가중치의 모든 특이 방향, 맨 위 방향에도 항상 성분을 갖는다. Adam의 업데이트는 소수 방향이 지배한다.
- 정렬되면 더해지는 성장. 업데이트의 특이쌍이 가중치의 최상위 특이쌍과 정렬되면 그 특이값이 더해지며 커진다. RMS를 맞추면 step마다 최대 씩 더해질 수 있으므로(§4) , 는 각각 step 수에 선형으로, 그 곱인 logit 상한은 이차로 자랄 수 있다.
- 쌍선형 증폭. logit은 에 달려 있어 어느 쪽이 커지든 곱해진다.
- weight decay로는 못 막는다. §4의 상한 는 건강한 logit보다 한참 위다.
soft-cap이나 QK-Norm은 왜 안 되나
logit soft-cap()은 softmax가 보는 값을 묶지만, 그 뒤에서 자체와 가중치는 계속 자란다. QK-Norm(head마다 , 를 정규화)은 MHA/GQA 모델의 표준 해법이지만(안정화 부품 참고), K2는 MLA를 쓰고 MLA의 head별 key는 “추론 중에 완전히 만들어지지 않으므로” 정규화할 대상이 없다. (DeepSeek-V4는 다른 방식으로 비켜 간다. query head마다, 그리고 KV entry에 RMSNorm을 걸어 QK-Clip이 필요 없다. GLM-5는 head별 Muon Split으로 logit이 안정적이었다.)
QK-Clip 규칙의 유도
를 현재 배치에서 head 의 최대 logit이라 하자(forward에서 이미 계산된다). optimizer step 뒤 이면 로 두고 다시 스케일한다.
head 의 모든 logit은 에 대해 쌍선형이므로 정확히 배가 되고, 이 배치에서 가장 큰 logit은 정확히 에 떨어진다. 나머지 attention 패턴은 온도 같은 그 인자를 빼면 그대로다. 설계상의 선택:
- 언제. 이번 step의 forward·backward는 건드리지 않는다. 는 다음 step을 위해 가중치를 얼마나 줄일지만 정한다. 손실 항이 아니라, 업데이트 뒤에 “최대 logit ≤ τ”로 사영하는 것이다.
- 는 축소를 와 에 반씩 나눈다. 아래 그림에서 움직여 볼 수 있다.
- head별. 순진한 판은 층 전체에 하나를 써서 멀쩡한 head까지 과하게 규제한다. K2에서 폭주하는 head는 소수다.
- MLA. head의 logit은 (내용 부분 + 분리된 RoPE 부분)이고 는 모든 head가 공유한다. 를 각각 배 하면 내용 항이 배가 된다. RoPE 항도 배가 되어야 하는데 를 건드리면 다른 head 모두가 영향을 받으므로 가 인자 전체를 떠맡는다.
K2는 으로 학습했다. 최대 logit은 초반에 상한에 붙어 있다가 학습의 약 30% 뒤 안정 범위로 내려왔다. 처음 70,000 step 동안 head의 12.7%가 한 번 이상 QK-Clip을 발동했고, 그 뒤에는 모든 head가 100 아래로 내려와 clip이 꺼졌다. 0.5B 활성 / 3B 전체 ablation에서 공격적인 도 손실 곡선에 미미한 영향만 주었다.
Things to try in the figure:
- Muon, clip off, then raise η. Head 0’s max logit grows roughly with the square of — each doubling of the learning rate (0.015 → 0.03 → 0.06) ends it about 4–5× higher (≈ 35 → 150 → 700), below the dotted spectral bound. That is the “two spectral norms growing linearly” mechanism. Switch to AdamW at the same η: in this toy its logit levels off (≈ 26 → 29 → 41).
- Weight decay. Raise λ to 0.5 and head 0 does stay small here — but only because this layer is tiny: the §4 cap is . Watch head 1’s loss: decay shrinks every head, so it rises too. At width 7168 and λ = 0.1 the same cap is about 169, and decay no longer restrains the logit.
- Per head vs all heads. Per-head clipping holds head 0 at τ with no change to head 1’s loss. The all-heads version shrinks head 1 too, and its loss goes up.
- α. At α = 0.5 both and of head 0 end small; at α → 1 the whole clip lands on and keeps growing, which hides the problem in one factor rather than solving it.
Clipping a head costs little when its softmax is already nearly one-hot at the clipped scale, so the extra logit only buys numerical risk. That is the case QK-Clip is designed for. Whether it holds depends on the gaps between the logits of a row, not on the max alone: logits still give , while a top logit that sits 10 above every rival leaves each rival of its weight. Since clipping multiplies every logit by , it shrinks the gaps by too. The check below verifies the MLA bookkeeping: per-head factors on scale every logit of a clipped head by exactly and leave other heads untouched, while any attempt to put part of the factor on the shared changes the other heads. It computes , which is 1 for any head at or below ; the naive goes wrong for a head whose logits are all negative (−20 for , then NaN under the square root).
r = np.random.default_rng(3)
H, T, dc, dr = 4, 10, 16, 8 # heads, tokens, content dim, decoupled-RoPE dim
scale = np.array([1.0, 4.0, 1.0, 2.5])[:, None, None]
qC = r.normal(size=(H, T, dc)) * scale # per-head content query/key (head 1 is "exploding")
kC = r.normal(size=(H, T, dc)) * scale
qR = r.normal(size=(H, T, dr)) * 2 # per-head RoPE query
kR = r.normal(size=(T, dr)) * 2 # RoPE key SHARED by all heads
def logits(qC, kC, qR, kR):
return (qC @ kC.transpose(0, 2, 1) + qR @ kR.T) / np.sqrt(dc + dr)
S = logits(qC, kC, qR, kR)
Smax = S.max((1, 2)); tau = 20.0
gam = tau / np.maximum(Smax, tau) # gamma_h = tau / max(S_max^h, tau): 1 unless S_max^h > tau
print("S_max per head before:", np.round(Smax, 1), " gamma:", np.round(gam, 3))
S_neg = -1.0 # a head whose logits are all -1 never exceeds tau
with np.errstate(invalid="ignore"):
print("all-logits -1 head: naive min(1, tau/S) =", min(1.0, tau / S_neg),
"-> sqrt", np.sqrt(min(1.0, tau / S_neg)), "| tau/max(S, tau) =", tau / max(S_neg, tau))
# K2 rule: q^C, k^C by sqrt(gamma_h); q^R by gamma_h; shared k^R untouched
S2 = logits(qC * np.sqrt(gam)[:, None, None], kC * np.sqrt(gam)[:, None, None], qR * gam[:, None, None], kR)
print("S_max per head after :", np.round(S2.max((1, 2)), 2),
" every logit scaled by exactly gamma_h:", np.allclose(S2, S * gam[:, None, None]))
# alternative: split the RoPE factor as sqrt(gamma) on q^R and sqrt(gamma_1) on the shared k^R
S3 = logits(qC * np.sqrt(gam)[:, None, None], kC * np.sqrt(gam)[:, None, None],
qR * np.sqrt(gam)[:, None, None], kR * np.sqrt(gam[1]))
print("shared k^R touched -> healthy heads 0, 2, 3 unchanged?", np.allclose(S3[[0, 2, 3]], S[[0, 2, 3]]),
" their S_max now:", np.round(S3.max((1, 2))[[0, 2, 3]], 2))7. A complete Muon step in PyTorch
The optimizer below is the whole algorithm of this lesson — Nesterov momentum, five Newton–Schulz steps in bf16, Moonlight’s RMS matching and decoupled weight decay — plus the parameter split of §2. On PyTorch ≥ 2.9 the built-in torch.optim.Muon(params, lr, weight_decay, adjust_lr_fn="match_rms_adamw") implements the same update for 2-D parameters; QK-Clip is not in it (a minimal version for MHA is in the Kimi K2 lesson).
import torch
from torch import nn
@torch.no_grad()
def zeropower_ns5(G: torch.Tensor, steps: int = 5, eps: float = 1e-7) -> torch.Tensor:
"""≈ U Vᵀ for G = U Σ Vᵀ (Jordan's quintic; output singular values land in roughly [0.7, 1.2])."""
a, b, c = 3.4445, -4.7750, 2.0315
X = G.bfloat16()
tall = X.size(-2) > X.size(-1)
if tall:
X = X.mT # iterate on the wide side (smaller Gram matrix)
X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
for _ in range(steps):
A = X @ X.mT
X = a * X + (b * A + c * A @ A) @ X
if tall:
X = X.mT
return X.to(G.dtype)
class Muon(torch.optim.Optimizer):
"""Muon for 2-D hidden weights: Nesterov momentum -> NS5 -> update RMS matched to AdamW."""
def __init__(self, params, lr=2e-4, momentum=0.95, weight_decay=0.1, ns_steps=5, rms=0.2):
super().__init__(params, dict(lr=lr, momentum=momentum, weight_decay=weight_decay,
ns_steps=ns_steps, rms=rms))
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr, mu, wd = group["lr"], group["momentum"], group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
assert p.ndim == 2, "Muon is for 2-D weight matrices; give other params to AdamW"
g = p.grad
state = self.state[p]
if "momentum_buffer" not in state:
state["momentum_buffer"] = torch.zeros_like(g)
buf = state["momentum_buffer"]
buf.mul_(mu).add_(g) # M_t = mu M_{t-1} + G_t
u = zeropower_ns5(g.add(buf, alpha=mu), group["ns_steps"]) # Nesterov: G_t + mu M_t
u.mul_(group["rms"] * max(p.shape) ** 0.5) # RMS(u) ≈ 0.2 for any shape
p.mul_(1 - lr * wd) # decoupled weight decay
p.add_(u, alpha=-lr)
return loss
def build_optimizers(model: nn.Module, lr=2e-4, wd=0.1, adam_betas=(0.9, 0.95)):
"""Hidden 2-D weights -> Muon; embeddings, LM head, routers -> AdamW (decay); 1-D -> AdamW (no decay)."""
special = {id(m.weight) for m in model.modules() if isinstance(m, nn.Embedding)}
head = getattr(model, "lm_head", None)
if head is not None:
special.add(id(head.weight)) # tied weights are the same tensor
muon, adam_decay, adam_no_decay = [], [], []
for name, p in model.named_parameters(): # yields each shared tensor once
if not p.requires_grad:
continue
if p.ndim == 2 and id(p) not in special and "router" not in name:
muon.append(p) # fused QKV / gate-up: split per head before NS for best results
elif p.ndim >= 2:
adam_decay.append(p)
else:
adam_no_decay.append(p) # norm gains, biases
return [
Muon(muon, lr=lr, weight_decay=wd),
torch.optim.AdamW([{"params": adam_decay, "weight_decay": wd},
{"params": adam_no_decay, "weight_decay": 0.0}],
lr=lr, betas=adam_betas, eps=1e-8),
]
# usage: one lr and one schedule drive both (RMS matching makes AdamW's lr meaningful for Muon)
# opts = build_optimizers(model)
# loss.backward(); [o.step() for o in opts]; [o.zero_grad(set_to_none=True) for o in opts]Muon in recent reports
| Model | What they changed | Lesson |
|---|---|---|
| Kimi K2 | Muon + weight decay + RMS 0.2 + QK-Clip (τ = 100, per head, MLA-aware); Muon also in SFT and RL | Kimi K2 |
| Kimi K3 | Per-Head Muon (Q·K·V momentum split per head) + QK-Clip | K3 |
| GLM-4.5 | Muon except embeddings, biases, RMSNorm weights; 5 NS steps, μ = 0.95, RMS 0.2 | GLM-4.5 |
| GLM-5 | Muon Split (per-head) lets MLA match GQA-8; logits stable without clipping | GLM-5 |
| DeepSeek-V4 | Hybrid NS (8 Jordan + 2 stabilising steps), RMS 0.18; q/KV RMSNorm instead of QK-Clip | DeepSeek-V4 |
| Qwen3.8-Flash-Next | Polar Express, 8 steps; fused matrices split; router, gates, embeddings, head on AdamW; Canzona partitioner; no qk-clip | Qwen3.8 |
| MAI-Base-2 | All-to-all resharding for NS, 2.1% of iteration time | MAI-Base-2 |
| MiMo-V2 | AdamW in pre-training, then Muown (row-norm-controlled Muon) from mid-training through RL | MiMo-V2 |
→ Go deeper, lab by lab and variant by variant — per-head splitting and why it matters for MLA, hybrid and Polar Express Newton–Schulz, NorMuon / Muown / Sinkhorn, four answers to logit growth, distributed schemes and hyperparameter transfer: Muon variants at frontier labs.
A 4096 × 1024 weight is updated with the exact orthogonalised update UVᵀ (no scaling). What is the RMS of the update's entries, and what factor does Moonlight multiply by to make it 0.2?
over entries, so , i.e. . Multiplying by gives RMS 0.2. The step’s spectral norm is then , which is why the same learning rate means a much larger step for wide matrices than “spectral-norm-unit” Muon.
In an MLA layer, head h has S_max = 400 on this batch and τ = 100 (α = 0.5). By what factors does QK-Clip multiply the head's content query q^C, content key k^C, RoPE query q^R and the shared RoPE key k^R?
. The content term must shrink by , so each side takes . The RoPE term must also shrink by , but is shared by every head, so it stays at 1 and takes the whole . Every logit of head is then exactly times its old value, and the max lands on 100.
Summary
- For a matrix, steepest descent under the spectral norm gives (maximiser of at ; the step length is the nuclear norm). The spectral norm is the right ruler because it bounds how much any input’s output can change. Muon = Nesterov momentum, then this orthogonalisation; it is rotation-equivariant and lifts the “rare directions” that dominate neither SGD’s nor Adam’s updates.
- Only hidden 2-D weights use it: embeddings (ℓ1→RMS norm ⇒ column normalisation), LM head, vectors and routers stay on AdamW; fused matrices are split, ideally per head.
- Newton–Schulz applies to every singular value. The slope sets how fast tiny are lifted ( steps); Jordan’s trades exact convergence (no stable fixed point, band ≈ [0.68, 1.13]) for 5 steps; DeepSeek-V4’s 8+2 and Polar Express’s per-step minimax polynomials tighten the band.
- , so Moonlight scales by to reuse AdamW’s lr and decay. Weight decay is required but caps a singular value only at . Overhead is ≤ FLOPs; the engineering problem is that NS needs whole matrices under ZeRO/TP (gather-and-slice, whole-matrix ownership, all-to-all resharding, or Dion’s sharded low-rank updates).
- Full-rank, RMS-matched updates can grow and linearly and the logit bound quadratically. QK-Clip rescales by with after the step, so every logit of that head shrinks by exactly ; in MLA the per-head takes all of because is shared.
그림에서 해 볼 것:
- Muon, clip 끔, η를 올려 보라. head 0의 최대 logit은 대략 의 제곱으로 자란다. 학습률을 두 배씩 올리면(0.015 → 0.03 → 0.06) 매번 약 4–5배 높이에서 끝나고(≈ 35 → 150 → 700), 점선 스펙트럼 상한 아래에 있다. “두 스펙트럼 노름이 선형으로 자라는” 메커니즘이다. 같은 η에서 AdamW로 바꾸면 이 장난감에서는 logit이 평평해진다(≈ 26 → 29 → 41).
- weight decay. λ를 0.5로 올리면 여기서는 head 0이 작게 유지된다. 하지만 이 층이 아주 작아서일 뿐이다. §4의 상한이 이다. head 1의 손실을 보라. decay는 모든 head를 줄이므로 그것도 오른다. 폭 7168, λ = 0.1이면 같은 상한이 약 169라서 decay는 더 이상 logit을 붙잡지 못한다.
- head별 대 전체 공통. head별 clip은 head 1의 손실을 바꾸지 않고 head 0을 τ에 묶는다. 전체 공통 판은 head 1까지 줄여 손실이 오른다.
- α. α = 0.5면 head 0의 와 가 둘 다 작게 끝난다. α → 1이면 clip이 모두 에 떨어지고 는 계속 자란다. 문제를 푸는 게 아니라 한쪽 인자에 숨기는 것이다.
clip된 크기에서도 softmax가 이미 거의 one-hot이면 head를 clip해도 손해가 적고, 더 커진 logit은 수치적 위험만 산다. QK-Clip이 겨냥하는 바로 그 경우다. 그런지는 최댓값 하나가 아니라 한 행 안의 logit 간격에 달려 있다. logit 은 여전히 이고, 최대 logit이 다른 모든 logit보다 10 크면 나머지 각각에는 의 가중치만 남는다. clip은 모든 logit에 를 곱하므로 간격도 배로 줄인다. 아래 확인은 MLA 장부를 검증한다. head별 인자를 에 걸면 clip된 head의 모든 logit이 정확히 배가 되고 다른 head는 그대로지만, 인자 일부를 공유된 에 걸려는 순간 다른 head가 바뀐다. 코드는 로 계산하므로 이하인 head는 모두 1이다. 순진한 는 logit이 모두 음수인 head에서 틀린다(이면 −20, 제곱근을 거치면 NaN).
r = np.random.default_rng(3)
H, T, dc, dr = 4, 10, 16, 8 # head 수, 토큰 수, 내용 차원, 분리된 RoPE 차원
scale = np.array([1.0, 4.0, 1.0, 2.5])[:, None, None]
qC = r.normal(size=(H, T, dc)) * scale # head별 내용 query/key (head 1이 "폭주" 중)
kC = r.normal(size=(H, T, dc)) * scale
qR = r.normal(size=(H, T, dr)) * 2 # head별 RoPE query
kR = r.normal(size=(T, dr)) * 2 # 모든 head가 공유하는 RoPE key
def logits(qC, kC, qR, kR):
return (qC @ kC.transpose(0, 2, 1) + qR @ kR.T) / np.sqrt(dc + dr)
S = logits(qC, kC, qR, kR)
Smax = S.max((1, 2)); tau = 20.0
gam = tau / np.maximum(Smax, tau) # gamma_h = tau / max(S_max^h, tau): 1 unless S_max^h > tau
print("head별 S_max (전):", np.round(Smax, 1), " gamma:", np.round(gam, 3))
S_neg = -1.0 # logit이 모두 -1인 head는 tau를 넘지 않는다
with np.errstate(invalid="ignore"):
print("logit 전부 -1인 head: 순진한 min(1, tau/S) =", min(1.0, tau / S_neg),
"-> sqrt", np.sqrt(min(1.0, tau / S_neg)), "| tau/max(S, tau) =", tau / max(S_neg, tau))
# K2 규칙: q^C, k^C에 sqrt(gamma_h), q^R에 gamma_h, 공유 k^R는 그대로
S2 = logits(qC * np.sqrt(gam)[:, None, None], kC * np.sqrt(gam)[:, None, None], qR * gam[:, None, None], kR)
print("head별 S_max (후):", np.round(S2.max((1, 2)), 2),
" 모든 logit이 정확히 gamma_h배:", np.allclose(S2, S * gam[:, None, None]))
# 대안: RoPE 인자를 q^R에 sqrt(gamma), 공유 k^R에 sqrt(gamma_1)로 나누면
S3 = logits(qC * np.sqrt(gam)[:, None, None], kC * np.sqrt(gam)[:, None, None],
qR * np.sqrt(gam)[:, None, None], kR * np.sqrt(gam[1]))
print("공유 k^R를 건드림 -> 멀쩡한 head 0, 2, 3 그대로?", np.allclose(S3[[0, 2, 3]], S[[0, 2, 3]]),
" 그 head들의 S_max:", np.round(S3.max((1, 2))[[0, 2, 3]], 2))7. PyTorch로 쓴 완전한 Muon step
아래 옵티마이저가 이 레슨의 알고리즘 전체다. Nesterov momentum, bf16에서의 Newton–Schulz 5단계, Moonlight의 RMS 맞춤, 분리된 weight decay, 그리고 §2의 매개변수 분할. PyTorch 2.9 이상에서는 내장 torch.optim.Muon(params, lr, weight_decay, adjust_lr_fn="match_rms_adamw")가 2차원 매개변수에 같은 업데이트를 구현한다. QK-Clip은 들어 있지 않다(MHA용 최소 구현은 Kimi K2 레슨에 있다).
import torch
from torch import nn
@torch.no_grad()
def zeropower_ns5(G: torch.Tensor, steps: int = 5, eps: float = 1e-7) -> torch.Tensor:
"""G = U Σ Vᵀ에 대해 ≈ U Vᵀ (Jordan quintic; 출력 특이값은 대략 [0.7, 1.2]에 놓인다)."""
a, b, c = 3.4445, -4.7750, 2.0315
X = G.bfloat16()
tall = X.size(-2) > X.size(-1)
if tall:
X = X.mT # 넓은 쪽으로 반복 (Gram 행렬이 작다)
X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
for _ in range(steps):
A = X @ X.mT
X = a * X + (b * A + c * A @ A) @ X
if tall:
X = X.mT
return X.to(G.dtype)
class Muon(torch.optim.Optimizer):
"""2차원 은닉 가중치용 Muon: Nesterov momentum -> NS5 -> 업데이트 RMS를 AdamW에 맞춤."""
def __init__(self, params, lr=2e-4, momentum=0.95, weight_decay=0.1, ns_steps=5, rms=0.2):
super().__init__(params, dict(lr=lr, momentum=momentum, weight_decay=weight_decay,
ns_steps=ns_steps, rms=rms))
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr, mu, wd = group["lr"], group["momentum"], group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
assert p.ndim == 2, "Muon은 2차원 가중치 행렬용; 나머지는 AdamW에"
g = p.grad
state = self.state[p]
if "momentum_buffer" not in state:
state["momentum_buffer"] = torch.zeros_like(g)
buf = state["momentum_buffer"]
buf.mul_(mu).add_(g) # M_t = mu M_{t-1} + G_t
u = zeropower_ns5(g.add(buf, alpha=mu), group["ns_steps"]) # Nesterov: G_t + mu M_t
u.mul_(group["rms"] * max(p.shape) ** 0.5) # 어떤 모양이든 RMS(u) ≈ 0.2
p.mul_(1 - lr * wd) # 분리된 weight decay
p.add_(u, alpha=-lr)
return loss
def build_optimizers(model: nn.Module, lr=2e-4, wd=0.1, adam_betas=(0.9, 0.95)):
"""은닉 2차원 가중치 -> Muon; 임베딩·LM head·라우터 -> AdamW(decay); 1차원 -> AdamW(decay 없음)."""
special = {id(m.weight) for m in model.modules() if isinstance(m, nn.Embedding)}
head = getattr(model, "lm_head", None)
if head is not None:
special.add(id(head.weight)) # tie된 가중치는 같은 텐서
muon, adam_decay, adam_no_decay = [], [], []
for name, p in model.named_parameters(): # 공유 텐서는 한 번만 나온다
if not p.requires_grad:
continue
if p.ndim == 2 and id(p) not in special and "router" not in name:
muon.append(p) # 합쳐진 QKV·gate-up: NS 전에 head별로 쪼개면 더 좋다
elif p.ndim >= 2:
adam_decay.append(p)
else:
adam_no_decay.append(p) # norm gain, bias
return [
Muon(muon, lr=lr, weight_decay=wd),
torch.optim.AdamW([{"params": adam_decay, "weight_decay": wd},
{"params": adam_no_decay, "weight_decay": 0.0}],
lr=lr, betas=adam_betas, eps=1e-8),
]
# 사용법: lr 하나와 스케줄 하나가 둘 다 움직인다 (RMS 맞춤 덕분에 AdamW의 lr이 Muon에도 통한다)
# opts = build_optimizers(model)
# loss.backward(); [o.step() for o in opts]; [o.zero_grad(set_to_none=True) for o in opts]최근 보고서 속의 Muon
| 모델 | 바꾼 것 | 레슨 |
|---|---|---|
| Kimi K2 | Muon + weight decay + RMS 0.2 + QK-Clip(τ = 100, head별, MLA 대응). SFT와 RL도 Muon | Kimi K2 |
| Kimi K3 | Per-Head Muon(Q·K·V momentum을 head별로 분할) + QK-Clip | K3 |
| GLM-4.5 | 임베딩·bias·RMSNorm 가중치 외 Muon. NS 5단계, μ = 0.95, RMS 0.2 | GLM-4.5 |
| GLM-5 | Muon Split(head별)으로 MLA가 GQA-8과 대등. clip 없이 logit 안정 | GLM-5 |
| DeepSeek-V4 | hybrid NS(Jordan 8 + 안정화 2단계), RMS 0.18. QK-Clip 대신 q/KV RMSNorm | DeepSeek-V4 |
| Qwen3.8-Flash-Next | Polar Express 8단계. 합쳐진 행렬 분할. 라우터·gate·임베딩·head는 AdamW. Canzona 분배기. qk-clip 없음 | Qwen3.8 |
| MAI-Base-2 | NS용 all-to-all 재분할, 반복 시간의 2.1% | MAI-Base-2 |
| MiMo-V2 | 사전학습은 AdamW, mid-training부터 RL까지 Muown(행 노름을 제어하는 Muon 변형) | MiMo-V2 |
→ lab별·변형별로 더 깊이: head별 분할과 그것이 MLA에서 중요한 이유, 하이브리드·Polar Express Newton–Schulz, NorMuon·Muown·Sinkhorn, logit 증가에 대한 네 가지 답, 분산 방식과 하이퍼파라미터 이전은 Frontier lab들의 Muon 변형에서.
4096 × 1024 가중치를 스케일 없이 정확히 직교화한 업데이트 UVᵀ로 갱신한다. 업데이트 원소의 RMS는 얼마이고, Moonlight는 이를 0.2로 만들려고 무엇을 곱하나?
원소 개에 대해 이므로 , 즉 이다. 을 곱하면 RMS가 0.2가 된다. 그러면 걸음의 스펙트럼 노름은 이고, 같은 학습률이라도 넓은 행렬일수록 “스펙트럼 노름 단위” Muon보다 훨씬 큰 걸음이 되는 이유다.
MLA 층에서 head h의 이번 배치 S_max = 400, τ = 100(α = 0.5)이다. QK-Clip은 그 head의 내용 query q^C, 내용 key k^C, RoPE query q^R, 공유 RoPE key k^R에 각각 몇 배를 곱하나?
. 내용 항 가 배 줄어야 하므로 양쪽이 씩 맡는다. RoPE 항 도 배 줄어야 하는데 는 모든 head가 공유하므로 1로 두고 가 전체를 맡는다. 그러면 head 의 모든 logit이 정확히 이전의 배가 되고 최댓값은 100에 떨어진다.
정리
- 행렬에 대해 스펙트럼 노름 아래의 최급강하는 다(에서 를 최대화, 걸음 길이는 핵 노름). 스펙트럼 노름이 맞는 자인 이유는 어떤 입력이든 출력 변화를 묶어 주기 때문이다. Muon = Nesterov momentum 후 이 직교화. 회전에 등변이고, SGD·Adam 업데이트 어디서도 주도권을 갖지 못하는 “드문 방향”을 끌어올린다.
- 은닉 2차원 가중치만 쓴다. 임베딩(ℓ1→RMS 노름 ⇒ 열별 정규화), LM head, 벡터, 라우터는 AdamW에 남고, 합쳐진 행렬은 가능하면 head별로 쪼갠다.
- Newton–Schulz는 모든 특이값에 를 적용한다. 기울기 가 작은 σ를 끌어올리는 속도를 정한다(단계). Jordan의 는 정확한 수렴(안정 고정점 없음, 띠 ≈ [0.68, 1.13])을 5단계와 맞바꾸고, DeepSeek-V4의 8+2와 Polar Express의 단계별 minimax 다항식이 띠를 좁힌다.
- 이라 Moonlight는 를 곱해 AdamW의 lr과 decay를 재사용한다. weight decay는 필요하지만 특이값을 에서만 막는다. 오버헤드는 FLOPs의 이하이고, 공학적 문제는 ZeRO/TP 아래에서 NS가 행렬 전체를 필요로 한다는 것이다(모아서 자르기, 행렬 통째 소유, all-to-all 재분할, Dion의 sharded 저랭크 업데이트).
- full rank이고 RMS를 맞춘 업데이트는 , 를 선형으로, logit 상한을 이차로 키울 수 있다. QK-Clip은 step 뒤 로 를 배 해서 그 head의 모든 logit을 정확히 배로 줄인다. MLA에서는 가 공유되므로 head별 가 전체를 맡는다.
더 읽을거리Further reading
- Jordan et al., Muon: An optimizer for hidden layers in neural networks (blog, 2024) and github.com/KellerJordan/Muon — Muon의 원출처. quintic 계수(3.4445, −4.7750, 2.0315)를 고른 기준, FLOP 오버헤드 Tm/B, AdamW로 남길 매개변수, speedrun 결과. 저장소의 muon.py가 기준 구현이다.The original source of Muon: how the quintic coefficients (3.4445, −4.7750, 2.0315) were chosen, the Tm/B FLOP overhead, which parameters stay on AdamW, the speedrun results. muon.py in the repository is the reference implementation.
- Bernstein & Newhouse, Old Optimizer, New Norm: An Anthology (2024) — EMA를 끈 Adam·Shampoo가 각각 특정 노름 아래의 최급강하라는 관점. 스펙트럼 노름의 해가 −(tr Σ/λ)UVᵀ다.Adam and Shampoo with their EMAs switched off are steepest descent under particular norms; under the spectral norm the solution is −(tr Σ/λ)UVᵀ.
- Bernstein & Newhouse, Modular Duality in Deep Learning (2024) — Linear 층은 RMS→RMS 연산자 노름, Embed 층은 ℓ1→RMS 노름으로 쌍대화한다. √(d_out/d_in)·UVᵀ와 열별 정규화가 여기서 나온다.Dualises a Linear layer under the RMS→RMS operator norm and an Embed layer under the ℓ1→RMS norm, which gives √(d_out/d_in)·UVᵀ and column-wise normalisation.
- Liu et al. (Moonshot AI), Muon is Scalable for LLM Training (2025) — weight decay와 0.2·√max(A,B) RMS 맞춤으로 Muon을 대규모로 쓴 Moonlight. ZeRO-1 기반 Distributed Muon, 약 2배 계산 효율, SFT 옵티마이저 불일치 실험.Moonlight: Muon at scale with weight decay and 0.2·√max(A,B) RMS matching, ZeRO-1-based Distributed Muon, about 2× compute efficiency, and the SFT optimiser-mismatch experiment.
- Kimi Team, Kimi K2: Open Agentic Intelligence (2025) — MuonClip. Muon에서 attention logit이 폭주하는 현상, head별 QK-Clip 규칙과 MLA에서의 적용, App. D·E의 분석.MuonClip: attention-logit explosion under Muon, the per-head QK-Clip rule and how it applies to MLA, and the analyses in App. D and E.
- Amsel, Persson, Musco, Gower, The Polar Express: Optimal Matrix Sign Methods and Their Application to the Muon Algorithm (2025) — 단계마다 minimax 최적 quintic을 고르는 Newton–Schulz. 탐욕적 선택이 최적 합성임을 보이고 bf16 안정화 장치를 정리했다.Newton–Schulz with a minimax-optimal quintic chosen per step; shows the greedy choice is the optimal composition and lists bf16 stabilisers.
- Ahn et al., Dion: Distributed Orthonormalized Updates (2025) — 전체 행렬을 모으지 않고 sharded 상태에서 amortized power iteration으로 저랭크 직교 업데이트를 만드는 대안.An alternative that builds low-rank orthonormal updates by amortised power iteration on sharded matrices, without gathering the full matrix.
- PyTorch, torch.optim.Muon (docs) — PyTorch 내장 Muon. adjust_lr_fn으로 Jordan식(original), Moonshot식(match_rms_adamw) 스케일을 고른다.PyTorch's built-in Muon; adjust_lr_fn selects Jordan's (original) or Moonshot's (match_rms_adamw) scaling.