Track VII · Architecture Deep Dives · 06/12

안정화 부품 — norm 위치, logit 통제, residual 변형, 긴 문맥의 위치 인코딩Stability components — norm placement, logit control, residual variants, positions at long context

규모가 커질 때 깨지는 세 곳을 부품 단위로 본다. norm 위치(pre/post/sandwich/reordered/DeepNorm)가 신호 전파를 어떻게 바꾸는지, attention logit 성장을 QK-norm·QK-clip·soft-cap·z-loss가 각각 어떻게 막는지, residual stream을 넓히는 HC·mHC(Sinkhorn)·Gated Residual·Attention Residuals가 왜 필요한지, RoPE base·PI·NTK·YaRN·Llama 3 스케일링·partial RoPE·NoPE가 긴 문맥에서 무엇을 고치는지를 그림과 코드로 확인한다.The three places that break as models grow, one component at a time: how norm placement (pre/post/sandwich/reordered/DeepNorm) changes signal propagation; how QK-norm, QK-clip, soft-capping and z-loss each bound logit growth; why HC, mHC (Sinkhorn), Gated Residual and Attention Residuals widen the residual stream; and what RoPE base, PI, NTK, YaRN, Llama-3 scaling, partial RoPE and NoPE fix at long context — with figures and code.

60 분min RMSNorm · pre-norm · post-norm · QK-norm · QK-clip · soft-capping · z-loss · hyper-connections · mHC · Sinkhorn · gated residual · attention residuals · RoPE · YaRN · NTK · NoPE · partial RoPE 먼저 볼 것:Before this: 깊은 망 학습하기Training deep networks, Transformer 블록 해부Anatomy of a Transformer block, GPT를 바닥부터GPT from scratch, Attention과 KV: MHA → GQA → MLA, sliding window·sink, local/globalAttention and KV: MHA → GQA → MLA, sliding windows and sinks, local/global

A 1T-parameter run that diverges at 60% costs more than the whole ablation budget that would have prevented it. That is why frontier reports spend pages on components that do not change the model’s function at all at initialisation — where a norm goes, how big a logit may get, how the residual stream is wired, how positions are encoded beyond the training length. This lesson takes them one at a time, asks what breaks without each, and shows the mechanism in a figure you can push until it breaks.

Training deep nets introduced RMSNorm, pre- vs post-norm and residual connections; the Transformer lesson the residual-stream view; GPT from scratch derived RoPE. We start from there.

Who uses what, from the reports and released configs:

ModelNorm and logit controlResidual streamPositions
Gemma 2RMSNorm before and after each sublayer; soft-cap 50 (attention), 30 (final logits)standardRoPE
Gemma 3same norms; QK-norm replaces soft-cappingstandardRoPE base 10K local / 1M global, 5 local : 1 global, ×8 interpolation for 128K
OLMo 2reordered norm x+RMSNorm⁡(F(x))x+\operatorname{RMSNorm}(F(x)), QK-norm, z-lossstandardRoPE
Qwen3-Nextzero-centred RMSNorm with weight decay on the gains; sigmoid output gate on attentionstandardpartial RoPE (25% of 256 dims), base 10710^7
Qwen3.8-Flash-NextGated Residual read replaces the pre-norm; Muon without QK-clipGated Residual, 4 branchespartial RoPE 25%; NoPE tried and rejected
Kimi K2pre-norm; QK-Clip τ = 100 (MLA cannot use QK-norm)standarddecoupled RoPE, YaRN ×32 from 4K
Kimi K3gated MLA with channel-wise output gateBlock Attention Residuals (12-layer blocks)NoPE in MLA; KDA carries position
DeepSeek-V3pre-norm RMSNormstandarddecoupled RoPE on 64 dims, YaRN s=40s=40 from 4K
DeepSeek-V4RMSNorm on queries and KV entries (no QK-Clip needed under Muon)mHC, n=4n=4, Sinkhorn tmax⁡=20t_{\max}=20RoPE on the last 64 dims + output counter-rotation
MiniMax-M1post-norm with residual scale α=3.5566\alpha=3.5566 (config)standardRoPE on 64 of 128 dims, base 10710^7
MiniMax-M2QK-norm (use_qk_norm)standardRoPE on 64 of 128 dims, base 5×1065\times10^6
Llama 4 ScoutQK-norm (use_qk_norm)standardNoPE every 4th layer, attention temperature tuning; Llama-3 scaling ×16
Nemotron 3 Ultra—standardno positional encoding in attention; Mamba carries position
Sources: Gemma 2 §2 and Gemma 3 §2 reports; OLMo 2 §2–3; Qwen3-Next/Qwen3.8 config.json and Qwen lessons; K2, K3, V3, V4, Nemotron lessons; MiniMax-M1/M2 and Llama-4-Scout config.json.

Where the norm goes

Four placements are in use, plus one scaling trick:

pre-norm:  xl+1=xl+Fl(N(xl))post-norm:  xl+1=N(xl+Fl(xl))sandwich (Gemma):  xl+1=xl+N(Fl(N(xl)))reordered (OLMo 2):  xl+1=xl+N(Fl(xl))DeepNorm:  xl+1=N(α xl+Fl(xl)),  α=(2L)1/4, F’s init×(8L)−1/4\begin{aligned} \text{pre-norm:}&\ \ x_{l+1}=x_l+F_l(N(x_l)) &\qquad \text{post-norm:}&\ \ x_{l+1}=N\big(x_l+F_l(x_l)\big)\\ \text{sandwich (Gemma):}&\ \ x_{l+1}=x_l+N\big(F_l(N(x_l))\big) &\qquad \text{reordered (OLMo 2):}&\ \ x_{l+1}=x_l+N\big(F_l(x_l)\big)\\ \text{DeepNorm:}&\ \ x_{l+1}=N\big(\alpha\,x_l+F_l(x_l)\big),\ \ \alpha=(2L)^{1/4},\ F\text{'s init}\times(8L)^{-1/4} \end{aligned}

What each buys is a statement about two products along depth. Forward: in pre-norm, every branch adds an update of roughly constant size to an un-normalised stream, so ∥xl∥\|x_l\| grows like l\sqrt l and the ll-th layer’s update is a fraction ≈1/l\approx1/\sqrt l of the stream — late layers can barely move it. The Attention Residuals paper calls this PreNorm dilution. Post-norm resets the stream to RMS 1 every layer, so there is no dilution. Backward: pre-norm’s identity path carries the gradient untouched to every layer (the II term of ∏(I+∂F)\prod(I+\partial F)); post-norm’s identity path goes through LL normalisations, each multiplying by a Jacobian (I−x^x^⊤/d)/rms⁡(I-\hat x\hat x^\top/d)/\operatorname{rms}, so the gradient that reaches early layers depends on depth and branch gain — the reason post-norm Transformers needed warm-up (Xiong et al. 2020). Sandwich and reordered norms keep pre-norm’s clean identity path but bound what each branch can add; DeepNorm keeps post-norm but up-weights the identity path by α\alpha and shrinks the branches at init.

MiniMax-M1’s config, for what it is worth, sets postnorm: true with every residual scale α=3.5566\alpha=3.5566 — exactly (2⋅80)1/4(2\cdot80)^{1/4} for its 80 layers, DeepNet’s decoder-only formula (our observation; the report does not discuss it). Qwen3-Next made a smaller change: zero-centred RMSNorm, y=(1+w)⊙x/rms⁡(x)y=(1+w)\odot x/\operatorname{rms}(x) with ww initialised at 0 and weight decay on ww, so decay pulls the gain toward 1 instead of toward 0 — after it saw QK-norm gains in Qwen3 grow abnormally large.

60% 지점에서 발산한 1T 파라미터 run은 그것을 막았을 ablation 예산 전체보다 비싸다. 그래서 프런티어 보고서는 초기화 시점에는 모델의 함수를 전혀 바꾸지 않는 부품에 여러 쪽을 쓴다. norm을 어디 두는지, logit이 얼마나 커져도 되는지, residual stream을 어떻게 잇는지, 학습 길이 너머에서 위치를 어떻게 부호화하는지. 이 레슨은 그것들을 하나씩 보면서 각각이 없으면 무엇이 깨지는지 묻고, 깨질 때까지 밀어 볼 수 있는 그림으로 메커니즘을 보인다.

깊은 신경망 학습에서 RMSNorm, pre- vs post-norm, residual 연결을, Transformer 레슨에서 residual stream 관점을, GPT 바닥부터에서 RoPE를 유도했다. 거기서 출발한다.

보고서와 공개 config로 정리한 “누가 무엇을 쓰나”:

모델norm과 logit 통제residual stream위치
Gemma 2각 sublayer 앞뒤에 RMSNorm; soft-cap 50(attention), 30(최종 logit)표준RoPE
Gemma 3같은 norm; soft-cap 대신 QK-norm표준RoPE base local 10K / global 1M, local 5 : global 1, 128K용 ×8 보간
OLMo 2reordered norm x+RMSNorm⁡(F(x))x+\operatorname{RMSNorm}(F(x)), QK-norm, z-loss표준RoPE
Qwen3-Nextgain에 weight decay를 건 zero-centered RMSNorm; attention 출력 sigmoid gate표준partial RoPE(256차원 중 25%), base 10710^7
Qwen3.8-Flash-NextGated Residual 읽기가 pre-norm을 대체; QK-clip 없는 MuonGated Residual, branch 4개partial RoPE 25%; NoPE를 시험하고 기각
Kimi K2pre-norm; QK-Clip τ = 100 (MLA는 QK-norm을 못 씀)표준decoupled RoPE, 4K에서 YaRN ×32
Kimi K3채널별 출력 gate가 있는 gated MLABlock Attention Residuals (12층 block)MLA는 NoPE; 위치는 KDA가 맡음
DeepSeek-V3pre-norm RMSNorm표준64차원 decoupled RoPE, 4K에서 YaRN s=40s=40
DeepSeek-V4query와 KV 항목에 RMSNorm (Muon에서도 QK-Clip 불필요)mHC, n=4n=4, Sinkhorn tmax⁡=20t_{\max}=20마지막 64차원에 RoPE + 출력 역회전
MiniMax-M1residual 배율 α=3.5566\alpha=3.5566의 post-norm (config)표준128차원 중 64차원 RoPE, base 10710^7
MiniMax-M2QK-norm (use_qk_norm)표준128차원 중 64차원 RoPE, base 5×1065\times10^6
Llama 4 ScoutQK-norm (use_qk_norm)표준4층마다 NoPE, attention temperature tuning; Llama-3 스케일링 ×16
Nemotron 3 Ultra—표준attention에 위치 인코딩 없음; 위치는 Mamba가 맡음
출처: Gemma 2 §2, Gemma 3 §2 보고서; OLMo 2 §2–3; Qwen3-Next/Qwen3.8 config.json과 Qwen 레슨; K2, K3, V3, V4, Nemotron 레슨; MiniMax-M1/M2와 Llama-4-Scout config.json.

norm을 어디에 두나

쓰이는 배치는 넷, 그리고 배율 요령 하나다.

pre-norm:  xl+1=xl+Fl(N(xl))post-norm:  xl+1=N(xl+Fl(xl))sandwich (Gemma):  xl+1=xl+N(Fl(N(xl)))reordered (OLMo 2):  xl+1=xl+N(Fl(xl))DeepNorm:  xl+1=N(α xl+Fl(xl)),  α=(2L)1/4, F 초기화×(8L)−1/4\begin{aligned} \text{pre-norm:}&\ \ x_{l+1}=x_l+F_l(N(x_l)) &\qquad \text{post-norm:}&\ \ x_{l+1}=N\big(x_l+F_l(x_l)\big)\\ \text{sandwich (Gemma):}&\ \ x_{l+1}=x_l+N\big(F_l(N(x_l))\big) &\qquad \text{reordered (OLMo 2):}&\ \ x_{l+1}=x_l+N\big(F_l(x_l)\big)\\ \text{DeepNorm:}&\ \ x_{l+1}=N\big(\alpha\,x_l+F_l(x_l)\big),\ \ \alpha=(2L)^{1/4},\ F\text{ 초기화}\times(8L)^{-1/4} \end{aligned}

각각이 사 주는 것은 깊이 방향의 두 곱에 대한 진술이다. 순방향: pre-norm에서는 모든 branch가 정규화되지 않은 stream에 대략 일정한 크기의 갱신을 더하므로 ∥xl∥\|x_l\|이 l\sqrt l처럼 자라고, ll번째 층의 갱신은 stream의 약 1/l1/\sqrt l 비율이다. 뒤쪽 층은 stream을 거의 움직이지 못한다. Attention Residuals 논문은 이것을 PreNorm 희석(dilution) 이라 부른다. post-norm은 층마다 stream을 RMS 1로 되돌리므로 희석이 없다. 역방향: pre-norm의 항등 경로는 기울기를 모든 층에 그대로 나른다(∏(I+∂F)\prod(I+\partial F)의 II 항). post-norm의 항등 경로는 정규화 LL개를 지나며 매번 Jacobian (I−x^x^⊤/d)/rms⁡(I-\hat x\hat x^\top/d)/\operatorname{rms}를 곱하므로, 앞쪽 층에 닿는 기울기가 깊이와 branch 이득에 따라 달라진다. post-norm Transformer에 warm-up이 필요했던 이유다(Xiong et al. 2020). sandwich와 reordered norm은 pre-norm의 깨끗한 항등 경로를 지키면서 각 branch가 더할 수 있는 크기를 묶고, DeepNorm은 post-norm을 유지하되 항등 경로를 α\alpha로 키우고 branch를 초기화 때 줄인다.

참고로 MiniMax-M1의 config는 postnorm: true와 모든 residual 배율 α=3.5566\alpha=3.5566을 쓴다. 80층에 대한 DeepNet의 decoder-only 공식 (2⋅80)1/4(2\cdot80)^{1/4}과 정확히 같다(우리의 관찰이며 보고서는 이를 논하지 않는다). Qwen3-Next는 더 작은 것을 바꿨다. zero-centered RMSNorm y=(1+w)⊙x/rms⁡(x)y=(1+w)\odot x/\operatorname{rms}(x)에서 ww를 0으로 초기화하고 ww에 weight decay를 걸어, decay가 gain을 0이 아니라 1 쪽으로 당기게 했다. Qwen3에서 QK-norm gain이 비정상적으로 커지는 것을 본 뒤의 변경이다.

pre-norm 마지막 층의 상대 갱신pre-norm last-layer relative update ‖F‖/‖x‖ – post-norm 첫 층 기울기post-norm grad at layer 0 –
Left: RMS of the residual stream after each layer (log scale). Right: norm of the gradient reaching each layer when a unit gradient arrives at the top. Five placements: pre-norm x + F(N(x)); post-norm N(x + F(x)); sandwich x + N(F(N(x))) (Gemma 2/3); reordered x + N(F(x)) (OLMo 2); DeepNorm N(αx + F(x)) with α = (2L)1/4 and branch init scaled by (8L)−1/4. Drag L and σ: pre-norm streams grow like √L, so each later layer changes the stream relatively less (dilution) while the identity path keeps gradients ≥ 1; post-norm keeps the stream at RMS 1 but sends the identity path through L normalisations, so the gradient reaching early layers depends on σ and depth. A toy at initialisation — real training moves these curves. 왼쪽은 층마다 residual stream의 RMS(log), 오른쪽은 맨 위에 단위 기울기가 들어올 때 각 층에 닿는 기울기의 norm이다. 다섯 배치: pre-norm x + F(N(x)); post-norm N(x + F(x)); sandwich x + N(F(N(x)))(Gemma 2/3); reordered x + N(F(x))(OLMo 2); DeepNorm N(αx + F(x)), α = (2L)1/4, branch 초기화 (8L)−1/4배. L과 σ를 끌어 보면 pre-norm stream은 √L처럼 자라서 뒤쪽 층일수록 stream을 상대적으로 덜 바꾸고(희석), 항등 경로 덕에 기울기는 1 이상을 유지한다. post-norm은 stream을 RMS 1로 유지하지만 항등 경로가 정규화 L개를 지나가므로 앞쪽 층에 닿는 기울기가 σ와 깊이에 따라 달라진다. 초기화 시점의 장난감이다. 실제 학습은 이 곡선을 움직인다.

Attention-logit growth, and four ways to bound it

With RMSNorm’d inputs, an attention logit is bounded only by the weights:

∣1d qi⊤kj∣=∣1d xi⊤WqWk⊤xj∣≤1d ∥xi∥ ∥xj∥ ∥Wq∥2 ∥Wk∥2.\Big|\tfrac{1}{\sqrt d}\,q_i^\top k_j\Big|=\Big|\tfrac{1}{\sqrt d}\,x_i^\top W_qW_k^\top x_j\Big|\le\tfrac{1}{\sqrt d}\,\|x_i\|\,\|x_j\|\,\|W_q\|_2\,\|W_k\|_2 .

Nothing in the loss stops ∥Wq∥∥Wk∥\|W_q\|\|W_k\| from growing: once a head is confident, scaling its logits up makes the softmax sharper at almost no cost. Dehghani et al. saw it in ViT-22B (“attention logit growth”); Wortsman et al. reproduced it in small models and found that every run whose attention logits exceeded 10410^4 diverged, with the attention weights collapsing to one-hot vectors. Two mechanisms make large logits dangerous. The softmax Jacobian diag⁡(p)−pp⊤\operatorname{diag}(p)-pp^\top vanishes as pp becomes one-hot, so the head stops learning; and BF16 keeps 8 significant bits, so at a logit of 1000 the spacing between representable numbers is 4 — the logit differences that encode which key wins are rounded away. The K2 lesson shows Muon makes this worse: its full-rank updates grow the spectral norms of Wq,WkW_q,W_k faster.

The remedies act at different points of the computation:

RemedyWhere it actsGuaranteeCost / caveatUsed by
QK-normnormalise q,kq,k per head (RMSNorm with gain γ\gamma) before the dot product∣logit∣≤∥γq∥∞∥γk∥∞d\lvert\text{logit}\rvert\le\lVert\gamma_q\rVert_\infty\lVert\gamma_k\rVert_\infty\sqrt d, independent of Wq,WkW_q,W_kneeds kk materialised per head — incompatible with MLA’s absorbed keysGemma 3, OLMo 2, Qwen3, MiniMax-M2, Llama 4
QK-clipafter the optimiser step, if head hh‘s max logit Smax⁡h>τS^h_{\max}>\tau, scale Wqh,WkhW_q^h,W_k^h by τ/Smax⁡h\sqrt{\tau/S^h_{\max}}max logit ≤ τ from the next step on, ranking preservedneeds the max logit per head from the forward pass; a guard rail, not an entropy controlKimi K2 (τ = 100)
Soft-capz↦ctanh⁡(z/c)z\mapsto c\tanh(z/c) on the logits∣z∣<c\lvert z\rvert<ccompresses differences among large logits; gradient sech⁡2(z/c)→0\operatorname{sech}^2(z/c)\to0; needs kernel supportGemma 2 (50 / 30)
z-lossauxiliary λ (log⁡Z)2\lambda\,(\log Z)^2 on the output softmaxkeeps log⁡Z≈0\log Z\approx0one hyper-parameter, λ=10−4\lambda=10^{-4}PaLM, OLMo 2

QK-norm is the most direct: the logit becomes γ2d⋅cos⁡(q,k)\gamma^2\sqrt d\cdot\cos(q,k), so the model can sharpen a head only by growing a dd-dimensional gain, not two d×dmodeld\times d_{\text{model}} matrices. Wortsman et al. report that with qk-layernorm a 1.2B model trains at learning rate 0.3. It cannot be applied when keys are never formed per head, which is MLA’s situation at inference — the reason Kimi K2 invented QK-Clip, a weight-space version applied between steps. DeepSeek-V4 normalises queries and its compressed KV entries directly and says it therefore did not need QK-Clip under Muon.

→ Go deeper: why Muon in particular makes attention logits grow, and the per-head QK-Clip rescaling itself, are derived in Muon and orthogonalised optimisers (§6, MuonClip).

z-loss fixes a different degree of freedom. Cross-entropy is invariant to adding a constant to all output logits, log⁡softmax⁡(z+c)=log⁡softmax⁡(z)\log\operatorname{softmax}(z+c)=\log\operatorname{softmax}(z), so nothing pins the overall level log⁡Z=log⁡∑jezj\log Z=\log\sum_je^{z_j}. Wortsman et al. observed output logit divergence: logits drift very negative and training becomes unstable. Adding 10−4log⁡2Z10^{-4}\log^2Z (PaLM’s coefficient) gives the free direction a weak restoring force; its gradient 2⋅10−4log⁡Z⋅softmax⁡(z)2\cdot10^{-4}\log Z\cdot\operatorname{softmax}(z) shifts all logits together and leaves their differences — the prediction — alone.

attention logit 성장, 그리고 그것을 묶는 네 방법

RMSNorm한 입력에서 attention logit은 가중치로만 묶인다.

∣1d qi⊤kj∣=∣1d xi⊤WqWk⊤xj∣≤1d ∥xi∥ ∥xj∥ ∥Wq∥2 ∥Wk∥2.\Big|\tfrac{1}{\sqrt d}\,q_i^\top k_j\Big|=\Big|\tfrac{1}{\sqrt d}\,x_i^\top W_qW_k^\top x_j\Big|\le\tfrac{1}{\sqrt d}\,\|x_i\|\,\|x_j\|\,\|W_q\|_2\,\|W_k\|_2 .

손실에는 ∥Wq∥∥Wk∥\|W_q\|\|W_k\|가 커지는 것을 막는 항이 없다. head가 확신을 가지면 logit을 키울수록 softmax가 날카로워지고 비용은 거의 없다. Dehghani et al.은 ViT-22B에서 이것을 보았고(“attention logit growth”), Wortsman et al.은 작은 모델에서 재현해 attention logit이 10410^4을 넘은 run은 모두 발산했다는 것과 attention 가중치가 one-hot으로 무너진다는 것을 보였다. 큰 logit이 위험한 메커니즘은 둘이다. pp가 one-hot이 되면 softmax Jacobian diag⁡(p)−pp⊤\operatorname{diag}(p)-pp^\top이 사라져 head가 더 배우지 못한다. 그리고 BF16은 유효 비트가 8개라 logit 1000 근처에서 표현 가능한 수의 간격이 4다. 어느 key가 이기는지를 담은 logit 차이가 반올림으로 사라진다. K2 레슨은 Muon이 이것을 악화시킨다는 것을 보여 준다. full-rank 갱신이 Wq,WkW_q,W_k의 spectral norm을 더 빨리 키운다.

처방들은 계산의 서로 다른 지점에 작용한다.

처방작용 지점보장비용 / 단서쓰는 곳
QK-norm내적 전에 head별로 q,kq,k 정규화(gain γ\gamma가 있는 RMSNorm)∣logit∣≤∥γq∥∞∥γk∥∞d\lvert\text{logit}\rvert\le\lVert\gamma_q\rVert_\infty\lVert\gamma_k\rVert_\infty\sqrt d, Wq,WkW_q,W_k와 무관head별 kk가 실체화되어야 한다. MLA의 흡수된 key와 맞지 않는다Gemma 3, OLMo 2, Qwen3, MiniMax-M2, Llama 4
QK-clipoptimizer step 뒤, head hh의 최대 logit Smax⁡h>τS^h_{\max}>\tau이면 Wqh,WkhW_q^h,W_k^h를 τ/Smax⁡h\sqrt{\tau/S^h_{\max}}배다음 step부터 최대 logit ≤ τ, 순위 보존forward에서 head별 최대 logit이 필요; 엔트로피 조절이 아니라 가드레일Kimi K2 (τ = 100)
soft-caplogit에 z↦ctanh⁡(z/c)z\mapsto c\tanh(z/c)∣z∣<c\lvert z\rvert<c큰 logit 사이의 차이를 압축; 기울기 sech⁡2(z/c)→0\operatorname{sech}^2(z/c)\to0; 커널 지원 필요Gemma 2 (50 / 30)
z-loss출력 softmax에 보조항 λ (log⁡Z)2\lambda\,(\log Z)^2log⁡Z≈0\log Z\approx0 유지하이퍼파라미터 하나, λ=10−4\lambda=10^{-4}PaLM, OLMo 2

QK-norm이 가장 직접적이다. logit이 γ2d⋅cos⁡(q,k)\gamma^2\sqrt d\cdot\cos(q,k)가 되므로, 모델은 d×dmodeld\times d_{\text{model}} 행렬 둘이 아니라 dd차원 gain을 키워야만 head를 날카롭게 할 수 있다. Wortsman et al.은 qk-layernorm을 쓰면 1.2B 모델이 학습률 0.3에서도 학습된다고 보고한다. key가 head별로 만들어지지 않으면 쓸 수 없는데, 추론 시 MLA가 그런 경우다. Kimi K2가 step 사이에 가중치 공간에서 적용하는 QK-Clip을 만든 이유다. DeepSeek-V4는 query와 압축 KV 항목을 직접 정규화하고, 그래서 Muon에서도 QK-Clip이 필요 없었다고 쓴다.

→ 더 깊이: 왜 하필 Muon에서 attention logit이 커지는지, 그리고 head별 QK-Clip 재조정 자체는 Muon과 직교화 옵티마이저(6절, MuonClip)에서 유도한다.

z-loss는 다른 자유도를 고정한다. cross-entropy는 모든 출력 logit에 상수를 더해도 변하지 않으므로(log⁡softmax⁡(z+c)=log⁡softmax⁡(z)\log\operatorname{softmax}(z+c)=\log\operatorname{softmax}(z)) 전체 수준 log⁡Z=log⁡∑jezj\log Z=\log\sum_je^{z_j}을 붙잡는 것이 없다. Wortsman et al.은 출력 logit 발산을 관찰했다. logit이 크게 음수로 흘러가며 학습이 불안정해진다. 10−4log⁡2Z10^{-4}\log^2Z(PaLM의 계수)를 더하면 이 자유 방향에 약한 복원력이 생긴다. 기울기 2⋅10−4log⁡Z⋅softmax⁡(z)2\cdot10^{-4}\log Z\cdot\operatorname{softmax}(z)는 모든 logit을 함께 옮기고, 예측을 담은 logit 사이의 차이는 건드리지 않는다.

최대 logitmax logit – 엔트로피entropy – 상위 두 key 간격top-2 gap – ‖∂p/∂z‖ – BF16 간격 @ 최대BF16 spacing at max –
One query, 32 keys. The raw logits are multiplied by g — what slowly growing ‖Wq‖·‖Wk‖ does during training. Left: attention weights for the chosen method (grey outline: no control). Right: attention entropy vs g for all four. Drag g up with “none”: the distribution collapses to one-hot, the softmax Jacobian ‖∂p/∂z‖ goes to zero (no gradient flows) and BF16 can no longer resolve logit differences of a few units. QK-norm makes the logit independent of the weight norms (bounded by γ²√d); QK-clip rescales the head so the max logit is τ and keeps the ranking; soft-cap bounds the logit at c but squashes every large logit toward c — push g far and the top keys become indistinguishable and the entropy rises again. query 하나와 key 32개. 원래 logit에 g를 곱한다. 학습 중 ‖Wq‖·‖Wk‖가 서서히 커질 때 일어나는 일이다. 왼쪽은 고른 방법의 attention 가중치(회색 테두리는 통제 없음), 오른쪽은 네 방법의 attention 엔트로피를 g에 따라 그린 것이다. “none”에서 g를 올리면 분포가 one-hot으로 무너지고, softmax Jacobian ‖∂p/∂z‖가 0으로 가며(기울기가 흐르지 않는다), BF16은 몇 단위의 logit 차이도 구별하지 못한다. QK-norm은 logit을 가중치 norm과 무관하게 만들고(γ²√d로 유계), QK-clip은 최대 logit이 τ가 되도록 head를 재조정하며 순위를 보존하고, soft-cap은 logit을 c로 묶지만 큰 logit을 모두 c 쪽으로 찌그러뜨린다. g를 많이 올리면 상위 key들이 구별되지 않고 엔트로피가 다시 오른다.
NumPy Logit growth vs QK-norm, soft-cap and QK-clip; BF16 resolution; z-loss
import numpy as np
rng = np.random.default_rng(0)
d, nk = 64, 32
q = rng.normal(size=d)
K = rng.normal(size=(nk, d))
K[3] = 0.9 * q + np.sqrt(1 - 0.81) * K[3]          # one key the head "wants"
K[17] = 0.75 * q + np.sqrt(1 - 0.5625) * K[17]     # a runner-up

def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
def entropy(p): return -(p * np.log(p + 1e-30)).sum()
def jac_norm(p): return np.linalg.norm(np.diag(p) - np.outer(p, p))   # ‖∂p/∂z‖_F

def logits(method, g, gamma=1.0, cap=50.0, tau=100.0):
    z = g * (K @ q) / np.sqrt(d)                       # g = growth of ‖W_q‖‖W_k‖
    if method == "qk-norm":                            # RMSNorm on q and k: z = γ² q̂·k̂/√d = γ²√d·cos
        qh = q / np.sqrt((q**2).mean()); Kh = K / np.sqrt((K**2).mean(1, keepdims=True))
        return gamma**2 * (Kh @ qh) / np.sqrt(d)
    if method == "soft-cap":
        return cap * np.tanh(z / cap)
    if method == "qk-clip":                            # after the step: W_q, W_k *= sqrt(τ/S_max)
        return z * min(1.0, tau / z.max())
    return z

print(f"{'method':9s} {'g':>6} {'max z':>8} {'top-2 gap':>9} {'entropy':>8} {'|dp/dz|':>8}")
for method in ["none", "qk-norm", "soft-cap", "qk-clip"]:
    for g in [1, 10, 100, 1000]:
        z = logits(method, g); p = softmax(z); zs = np.sort(z)[::-1]
        print(f"{method:9s} {g:6d} {zs[0]:8.1f} {zs[0]-zs[1]:9.2f} {abs(entropy(p)):8.3f} {jac_norm(p):8.2e}")

# BF16 keeps 8 significant bits: spacing of representable numbers near x is 2^(floor(log2 x) - 7)
def to_bf16(x):
    b = np.asarray(x, np.float32).view(np.uint32)
    b = ((b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000).astype(np.uint32)   # round to nearest even
    return b.view(np.float32)
for x in [10.3, 100.3, 1000.3]:
    print(f"logit {x:7.1f} → bf16 {float(to_bf16(x)):7.1f}   (spacing {2.0 ** (np.floor(np.log2(x)) - 7):.3g})")

# z-loss on the OUTPUT softmax: CE is invariant to a constant shift c of all logits; log Z is not
y = rng.normal(size=1000); target = 7
for c in [0.0, 30.0]:
    z = y + c
    logZ = np.log(np.exp(z - z.max()).sum()) + z.max()
    ce = logZ - z[target]
    print(f"shift c={c:4.0f}: CE = {ce:.4f}   log Z = {logZ:7.3f}   z-loss 1e-4·log²Z = {1e-4 * logZ**2:.4f}")
# gradient of 1e-4·log²Z w.r.t. the logits is 2e-4·logZ·softmax(z): a uniform pull on the shift direction
 

Read the table row by row. Without control, at g=10g=10 the head is already one-hot and ∥∂p/∂z∥\|\partial p/\partial z\| is 10−710^{-7}: the head has stopped learning, and every further growth only adds numerical risk. QK-norm’s logits do not move with gg at all. QK-clip caps the max at τ = 100 but still allows a one-hot head — it is a guard rail against runaway growth, not a regulariser of sharpness, which is why K2 could use it with τ = 100 without changing the loss curve. Soft-cap at large gg pins both top keys at 50: the gap collapses to 0 and the head can no longer say which key it wants.

확인 문제Check yourself

A head's raw logits keep growing during training. Which remedy keeps the head able to distinguish its two best keys no matter how far the growth goes?

Soft-capping bounds the value but maps every large logit close to cc, so ctanh⁡(z1/c)−ctanh⁡(z2/c)→0c\tanh(z_1/c)-c\tanh(z_2/c)\to0 once both are ≫c\gg c: the ranking information is squashed (and the gradient sech⁡2\operatorname{sech}^2 vanishes). z-loss acts on the output softmax’s normaliser, not on attention. QK-norm removes the dependence on ∥Wq∥∥Wk∥\|W_q\|\|W_k\| entirely; only cosines (times a learned gain) remain. QK-clip would also keep the ranking, by rescaling the weights.

PyTorch PyTorch: attention with QK-norm and optional soft-cap, LM loss with z-loss (torch ≥ 2.4 for nn.RMSNorm) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

class Attention(nn.Module):
    """Causal GQA with the three logit controls of this lesson as switches."""
    def __init__(self, d, n_heads, n_kv, qk_norm=True, softcap=None):
        super().__init__()
        self.h, self.kv, self.hd = n_heads, n_kv, d // n_heads
        self.wq = nn.Linear(d, n_heads * self.hd, bias=False)
        self.wk = nn.Linear(d, n_kv * self.hd, bias=False)
        self.wv = nn.Linear(d, n_kv * self.hd, bias=False)
        self.wo = nn.Linear(n_heads * self.hd, d, bias=False)
        # QK-norm: RMSNorm over each head's dimension, with a learnable gain (the only way to sharpen)
        self.q_norm = nn.RMSNorm(self.hd) if qk_norm else nn.Identity()
        self.k_norm = nn.RMSNorm(self.hd) if qk_norm else nn.Identity()
        self.softcap = softcap

    def forward(self, x):
        B, T, _ = x.shape
        q = self.q_norm(self.wq(x).view(B, T, self.h, self.hd)).transpose(1, 2)
        k = self.k_norm(self.wk(x).view(B, T, self.kv, self.hd)).transpose(1, 2)
        v = self.wv(x).view(B, T, self.kv, self.hd).transpose(1, 2)
        k, v = (t.repeat_interleave(self.h // self.kv, dim=1) for t in (k, v))   # GQA
        if self.softcap is None:   # fused kernel path
            o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        else:                      # soft-cap needs the logits explicitly (or a kernel that supports it)
            s = (q @ k.transpose(-1, -2)) / self.hd**0.5
            s = self.softcap * torch.tanh(s / self.softcap)
            s = s.masked_fill(torch.ones(T, T, dtype=torch.bool, device=x.device).triu(1), float("-inf"))
            o = s.softmax(-1) @ v
        return self.wo(o.transpose(1, 2).reshape(B, T, -1))

def lm_loss(logits, targets, z_coef=1e-4):
    """Cross-entropy plus z-loss: z_coef · (log Z)² keeps the output softmax's free shift near 0."""
    logits = logits.float()                                   # compute log Z in FP32
    log_z = torch.logsumexp(logits, dim=-1)
    ce = F.cross_entropy(logits.flatten(0, 1), targets.flatten())
    return ce + z_coef * (log_z ** 2).mean(), log_z.mean()

torch.manual_seed(0)
attn = Attention(d=256, n_heads=8, n_kv=2, qk_norm=True, softcap=50.0)
x = torch.randn(2, 16, 256)
print(attn(x).shape)                                          # torch.Size([2, 16, 256])
logits = torch.randn(2, 16, 1000) + 30.0                      # same CE as without the +30, larger log Z
loss, lz = lm_loss(logits, torch.randint(0, 1000, (2, 16)))
print(f"loss {loss.item():.3f}, mean log Z {lz.item():.1f}")  # z-loss adds 1e-4·~37² ≈ 0.14
 

A related fix lives in the attention output: Qwen’s gated attention multiplies the SDPA output by a query-dependent sigmoid gate, which removes attention sinks and massive activations and let a 1.7B model train at a learning rate where the baseline diverged (Qwen3-Next lesson). Sinks themselves and learnable sink logits are covered in attention variants.

Widening the residual stream

A standard residual keeps one stream that every layer reads and adds to with unit weight. Three recent designs change that.

Hyper-Connections (HC) widen the stream to nn copies Xl∈Rn×dX_l\in\mathbb R^{n\times d} and learn how the layer reads them, how it writes back and how the copies mix:

Xl+1=BlXl+Cl Fl(AlXl),Al∈R1×n, Bl∈Rn×n, Cl∈Rn×1.X_{l+1}=B_lX_l+C_l\,F_l(A_lX_l),\qquad A_l\in\mathbb R^{1\times n},\ B_l\in\mathbb R^{n\times n},\ C_l\in\mathbb R^{n\times1}.

With n=1n=1 and A=B=C=1A=B=C=1 this is the ordinary residual. The trouble is depth: ignoring the layer outputs, the residual path after LL layers is BL⋯B1B_L\cdots B_1, and if the BlB_l are unconstrained the product grows or shrinks exponentially. The mHC paper measured the “Amax gain magnitude” of that composite mapping — the maximum absolute row sum (forward) or column sum (backward) — peaking around 3000 in a 27B model with HC, versus about 1.6 with mHC.

mHC constrains each BlB_l to the doubly stochastic matrices: Bl=Sinkhorn⁡(exp⁡B~l)B_l=\operatorname{Sinkhorn}(\exp\tilde B_l), alternating column and row normalisation (tmax⁡=20t_{\max}=20). Three one-line facts do the work: row and column sums equal to 1 with non-negative entries give ∥B∥1=∥B∥∞=1\|B\|_1=\|B\|_\infty=1, hence ∥B∥2≤1\|B\|_2\le1 (forward and backward non-expansive); the product of doubly stochastic matrices is doubly stochastic, so this holds at any depth; and 1⊤BX=1⊤X\mathbf 1^\top BX=\mathbf 1^\top X, so the path only redistributes mass between streams. At n=4n=4 the paper reports 6.7% training-time overhead and, at 27B, BBH 43.8 → 48.9 (HC) → 51.0 (mHC). The DeepSeek-V4 lesson has the full parameterisation; V4.1 later reorganised it so the residual is read and written once per block.

Gated Residual (Qwen3.8-Next) keeps four branches but drops the mixing matrix BB altogether: each block reads x=1n∑iGi⊙RMSNorm⁡(Ri)x=\tfrac1{n}\sum_iG_i\odot\operatorname{RMSNorm}(R_i) through an elementwise sigmoid gate predicted from all branches (this read replaces the pre-norm) and writes Ri←Ri+si yR_i\leftarrow R_i+s_i\,y. Without BB there is no product to explode and one fewer full read of the residual state per block at decode; the report found that once read and write were expressive enough, HresH_{\text{res}} brought no significant gain. Attention Residuals (Kimi) go the other way: each layer reads a softmax-weighted mix of earlier layer outputs, hl=∑i<lαi→lvih_l=\sum_{i<l}\alpha_{i\to l}v_i with a learned per-layer query, which removes PreNorm dilution by construction; Block AttnRes (K3: blocks of 12 layers) keeps memory at O(Nd)O(Nd). See the K3 lesson.

NumPy logit 성장 대 QK-norm, soft-cap, QK-clip; BF16 해상도; z-loss
import numpy as np
rng = np.random.default_rng(0)
d, nk = 64, 32
q = rng.normal(size=d)
K = rng.normal(size=(nk, d))
K[3] = 0.9 * q + np.sqrt(1 - 0.81) * K[3]          # head가 "원하는" key 하나
K[17] = 0.75 * q + np.sqrt(1 - 0.5625) * K[17]     # 2등

def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
def entropy(p): return -(p * np.log(p + 1e-30)).sum()
def jac_norm(p): return np.linalg.norm(np.diag(p) - np.outer(p, p))   # ‖∂p/∂z‖_F

def logits(method, g, gamma=1.0, cap=50.0, tau=100.0):
    z = g * (K @ q) / np.sqrt(d)                       # g = ‖W_q‖‖W_k‖의 성장
    if method == "qk-norm":                            # q, k에 RMSNorm: z = γ² q̂·k̂/√d = γ²√d·cos
        qh = q / np.sqrt((q**2).mean()); Kh = K / np.sqrt((K**2).mean(1, keepdims=True))
        return gamma**2 * (Kh @ qh) / np.sqrt(d)
    if method == "soft-cap":
        return cap * np.tanh(z / cap)
    if method == "qk-clip":                            # step 뒤: W_q, W_k *= sqrt(τ/S_max)
        return z * min(1.0, tau / z.max())
    return z

print(f"{'method':9s} {'g':>6} {'max z':>8} {'top-2 gap':>9} {'entropy':>8} {'|dp/dz|':>8}")
for method in ["none", "qk-norm", "soft-cap", "qk-clip"]:
    for g in [1, 10, 100, 1000]:
        z = logits(method, g); p = softmax(z); zs = np.sort(z)[::-1]
        print(f"{method:9s} {g:6d} {zs[0]:8.1f} {zs[0]-zs[1]:9.2f} {abs(entropy(p)):8.3f} {jac_norm(p):8.2e}")

# BF16은 유효 비트 8개: x 근처의 표현 가능한 수 간격은 2^(floor(log2 x) - 7)
def to_bf16(x):
    b = np.asarray(x, np.float32).view(np.uint32)
    b = ((b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000).astype(np.uint32)   # 가장 가까운 짝수로 반올림
    return b.view(np.float32)
for x in [10.3, 100.3, 1000.3]:
    print(f"logit {x:7.1f} → bf16 {float(to_bf16(x)):7.1f}   (spacing {2.0 ** (np.floor(np.log2(x)) - 7):.3g})")

# *출력* softmax의 z-loss: CE는 모든 logit에 상수 c를 더해도 불변이지만 log Z는 아니다
y = rng.normal(size=1000); target = 7
for c in [0.0, 30.0]:
    z = y + c
    logZ = np.log(np.exp(z - z.max()).sum()) + z.max()
    ce = logZ - z[target]
    print(f"shift c={c:4.0f}: CE = {ce:.4f}   log Z = {logZ:7.3f}   z-loss 1e-4·log²Z = {1e-4 * logZ**2:.4f}")
# 1e-4·log²Z의 logit에 대한 기울기는 2e-4·logZ·softmax(z): shift 방향을 균일하게 당긴다
 

표를 행별로 읽자. 통제가 없으면 g=10g=10에서 이미 head가 one-hot이고 ∥∂p/∂z∥\|\partial p/\partial z\|는 10−710^{-7}이다. head는 배우기를 멈췄고, 그 뒤의 성장은 수치 위험만 더한다. QK-norm의 logit은 gg와 무관하게 움직이지 않는다. QK-clip은 최대값을 τ = 100으로 묶지만 one-hot head는 여전히 허용한다. 날카로움을 정규화하는 것이 아니라 폭주를 막는 가드레일이고, 그래서 K2는 τ = 100으로 손실 곡선을 바꾸지 않고 쓸 수 있었다. soft-cap은 gg가 크면 상위 key 둘 다를 50에 고정한다. 간격이 0으로 무너져 head가 어느 key를 원하는지 말할 수 없다.

확인 문제Check yourself

학습 중 어떤 head의 원래 logit이 계속 커진다. 성장이 아무리 계속돼도 head가 가장 좋은 두 key를 구별할 수 있게 지켜 주는 처방은?

soft-capping은 값을 묶지만 큰 logit을 모두 cc 근처로 보내므로, 둘 다 ≫c\gg c가 되면 ctanh⁡(z1/c)−ctanh⁡(z2/c)→0c\tanh(z_1/c)-c\tanh(z_2/c)\to0이다. 순위 정보가 찌그러지고 기울기 sech⁡2\operatorname{sech}^2도 사라진다. z-loss는 attention이 아니라 출력 softmax의 정규화 상수에 작용한다. QK-norm은 ∥Wq∥∥Wk∥\|W_q\|\|W_k\| 의존성을 완전히 없애고 cosine(곱하기 학습되는 gain)만 남긴다. QK-clip도 가중치를 재조정해 순위를 지킨다.

PyTorch PyTorch: QK-norm과 선택적 soft-cap이 있는 attention, z-loss를 더한 LM 손실 (nn.RMSNorm은 torch ≥ 2.4) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

class Attention(nn.Module):
    """이 레슨의 세 가지 logit 통제를 스위치로 단 causal GQA."""
    def __init__(self, d, n_heads, n_kv, qk_norm=True, softcap=None):
        super().__init__()
        self.h, self.kv, self.hd = n_heads, n_kv, d // n_heads
        self.wq = nn.Linear(d, n_heads * self.hd, bias=False)
        self.wk = nn.Linear(d, n_kv * self.hd, bias=False)
        self.wv = nn.Linear(d, n_kv * self.hd, bias=False)
        self.wo = nn.Linear(n_heads * self.hd, d, bias=False)
        # QK-norm: head 차원마다 RMSNorm, 학습되는 gain (날카롭게 만드는 유일한 길)
        self.q_norm = nn.RMSNorm(self.hd) if qk_norm else nn.Identity()
        self.k_norm = nn.RMSNorm(self.hd) if qk_norm else nn.Identity()
        self.softcap = softcap

    def forward(self, x):
        B, T, _ = x.shape
        q = self.q_norm(self.wq(x).view(B, T, self.h, self.hd)).transpose(1, 2)
        k = self.k_norm(self.wk(x).view(B, T, self.kv, self.hd)).transpose(1, 2)
        v = self.wv(x).view(B, T, self.kv, self.hd).transpose(1, 2)
        k, v = (t.repeat_interleave(self.h // self.kv, dim=1) for t in (k, v))   # GQA
        if self.softcap is None:   # fused kernel 경로
            o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        else:                      # soft-cap은 logit이 명시적으로 필요 (또는 지원하는 커널)
            s = (q @ k.transpose(-1, -2)) / self.hd**0.5
            s = self.softcap * torch.tanh(s / self.softcap)
            s = s.masked_fill(torch.ones(T, T, dtype=torch.bool, device=x.device).triu(1), float("-inf"))
            o = s.softmax(-1) @ v
        return self.wo(o.transpose(1, 2).reshape(B, T, -1))

def lm_loss(logits, targets, z_coef=1e-4):
    """cross-entropy + z-loss: z_coef · (log Z)²가 출력 softmax의 자유 shift를 0 근처에 묶는다."""
    logits = logits.float()                                   # log Z는 FP32로
    log_z = torch.logsumexp(logits, dim=-1)
    ce = F.cross_entropy(logits.flatten(0, 1), targets.flatten())
    return ce + z_coef * (log_z ** 2).mean(), log_z.mean()

torch.manual_seed(0)
attn = Attention(d=256, n_heads=8, n_kv=2, qk_norm=True, softcap=50.0)
x = torch.randn(2, 16, 256)
print(attn(x).shape)                                          # torch.Size([2, 16, 256])
logits = torch.randn(2, 16, 1000) + 30.0                      # +30이 없을 때와 CE는 같고 log Z만 크다
loss, lz = lm_loss(logits, torch.randint(0, 1000, (2, 16)))
print(f"loss {loss.item():.3f}, mean log Z {lz.item():.1f}")  # z-loss가 1e-4·~37² ≈ 0.14를 더한다
 

관련된 처방 하나가 attention 출력에 있다. Qwen의 gated attention은 SDPA 출력에 query 의존 sigmoid gate를 곱해 attention sink와 massive activation을 없앴고, baseline이 발산하는 학습률에서 1.7B 모델을 학습시켰다(Qwen3-Next 레슨). sink 자체와 학습되는 sink logit은 attention 변형에서 다룬다.

residual stream 넓히기

표준 residual은 모든 층이 읽고 가중치 1로 더하는 stream을 하나 유지한다. 최근 설계 셋이 이것을 바꾼다.

Hyper-Connections(HC) 는 stream을 nn벌 Xl∈Rn×dX_l\in\mathbb R^{n\times d}로 넓히고, 층이 어떻게 읽고 어떻게 다시 쓰며 사본끼리 어떻게 섞이는지를 배운다.

Xl+1=BlXl+Cl Fl(AlXl),Al∈R1×n, Bl∈Rn×n, Cl∈Rn×1.X_{l+1}=B_lX_l+C_l\,F_l(A_lX_l),\qquad A_l\in\mathbb R^{1\times n},\ B_l\in\mathbb R^{n\times n},\ C_l\in\mathbb R^{n\times1}.

n=1n=1, A=B=C=1A=B=C=1이면 보통의 residual이다. 문제는 깊이다. 층 출력을 빼고 보면 LL층 뒤의 residual 경로는 BL⋯B1B_L\cdots B_1이고, BlB_l에 제약이 없으면 곱이 지수적으로 커지거나 줄어든다. mHC 논문은 그 합성 사상의 “Amax gain magnitude”, 즉 행 절댓값 합의 최대(순방향) 또는 열 절댓값 합의 최대(역방향)를 쟀고, 27B 모델에서 HC는 최고 약 3000, mHC는 약 1.6이었다.

mHC는 각 BlB_l을 doubly stochastic 행렬로 제한한다. 열과 행 정규화를 번갈아 하는 Bl=Sinkhorn⁡(exp⁡B~l)B_l=\operatorname{Sinkhorn}(\exp\tilde B_l)(tmax⁡=20t_{\max}=20)이다. 한 줄짜리 사실 셋이 일을 한다. 음이 아닌 원소에 행 합·열 합이 1이면 ∥B∥1=∥B∥∞=1\|B\|_1=\|B\|_\infty=1이므로 ∥B∥2≤1\|B\|_2\le1이다(순방향과 역방향 모두 비확장). doubly stochastic 행렬의 곱은 doubly stochastic이므로 이것이 어느 깊이에서나 성립한다. 그리고 1⊤BX=1⊤X\mathbf 1^\top BX=\mathbf 1^\top X라서 경로는 stream 사이에 질량을 재분배할 뿐이다. n=4n=4에서 논문은 학습 시간 6.7% 증가, 27B에서 BBH 43.8 → 48.9(HC) → 51.0(mHC)를 보고한다. 전체 파라미터화는 DeepSeek-V4 레슨에 있고, V4.1은 나중에 block마다 residual을 한 번만 읽고 쓰도록 재구성했다.

Gated Residual(Qwen3.8-Next)은 branch 넷을 유지하되 혼합 행렬 BB를 아예 없앤다. 각 block은 모든 branch에서 예측한 원소별 sigmoid gate로 x=1n∑iGi⊙RMSNorm⁡(Ri)x=\tfrac1{n}\sum_iG_i\odot\operatorname{RMSNorm}(R_i)를 읽고(이 읽기가 pre-norm을 대체한다) Ri←Ri+si yR_i\leftarrow R_i+s_i\,y로 쓴다. BB가 없으니 폭발할 곱이 없고, decode에서 block마다 residual 상태 전체를 한 번 덜 읽는다. 보고서는 읽기·쓰기가 충분히 표현력이 있으면 HresH_{\text{res}}가 의미 있는 이득을 주지 않는다고 본다. Attention Residuals(Kimi)는 반대 방향이다. 각 층이 이전 층 출력들의 softmax 가중 혼합 hl=∑i<lαi→lvih_l=\sum_{i<l}\alpha_{i\to l}v_i를 층별 학습 query로 읽어, 구조적으로 PreNorm 희석을 없앤다. Block AttnRes(K3: 12층 block)는 메모리를 O(Nd)O(Nd)로 유지한다. K3 레슨을 보라.

128층 뒤after 128 layers HC fwd – HC bwd – mHC fwd – mHC bwd – stream 합 보존 오차stream-sum drift –
Ignoring the layer outputs, the residual path through l hyper-connection layers is the matrix product Bl⋯B1 of the n×n stream-mixing matrices. The curves show its forward gain (max absolute row sum) and backward gain (max absolute column sum — the backward pass multiplies by the transposes). Raise σ: unconstrained HC (B = I + σG) compounds into exponential growth, the failure the mHC paper measured at up to ~3000 in a 27B model. mHC projects exp(·) onto doubly stochastic matrices with Sinkhorn–Knopp. Set t = 1: one column-then-row normalisation makes every row sum 1, so the forward gain is exactly 1 — but columns are not yet normalised and the backward gain still drifts. Raise t (DeepSeek uses 20) and both gains stay at 1 for any depth, because doubly stochastic matrices are closed under multiplication. 층 출력을 빼고 보면 hyper-connection 층 l개를 지나는 residual 경로는 n×n stream 혼합 행렬들의 곱 Bl⋯B1이다. 곡선은 그 곱의 순방향 이득(행 절댓값 합의 최대)과 역방향 이득(열 절댓값 합의 최대. 역전파는 전치를 곱한다)이다. σ를 올리면 제약 없는 HC(B = I + σG)가 지수적으로 커진다. mHC 논문이 27B 모델에서 최대 약 3000까지 잰 실패다. mHC는 exp(·)를 Sinkhorn–Knopp로 doubly stochastic 행렬에 사영한다. t = 1로 두면 열 정규화 다음 행 정규화 한 번으로 모든 행 합이 1이 되어 순방향 이득은 정확히 1이지만, 열은 아직 정규화되지 않아 역방향 이득이 여전히 움직인다. t를 올리면(DeepSeek은 20) 두 이득이 깊이와 상관없이 1에 머문다. doubly stochastic 행렬은 곱에 대해 닫혀 있기 때문이다.
NumPy HC vs mHC: composite gains, the three doubly-stochastic properties, and pre-norm dilution
import numpy as np
rng = np.random.default_rng(0)
n, L = 4, 64

def sinkhorn(M, iters):
    for _ in range(iters):
        M = M / M.sum(0, keepdims=True)              # columns sum to 1
        M = M / M.sum(1, keepdims=True)              # rows sum to 1
    return M
fwd = lambda P: np.abs(P).sum(1).max()               # max row sum: how much the forward pass can amplify
bwd = lambda P: np.abs(P).sum(0).max()               # max column sum: the backward pass multiplies by Pᵀ

for sigma in [0.1, 0.3]:
    P_hc, P_m1, P_m20 = np.eye(n), np.eye(n), np.eye(n)
    for _ in range(L):
        G = rng.normal(size=(n, n))
        P_hc = (np.eye(n) + sigma * G) @ P_hc                        # unconstrained hyper-connection
        E = np.exp(2 * np.eye(n) + 3 * sigma * G)                    # positive, diagonal-heavy
        P_m1 = sinkhorn(E, 1) @ P_m1
        P_m20 = sinkhorn(E, 20) @ P_m20                              # mHC (t_max = 20)
    print(f"σ={sigma}: after {L} layers  HC fwd/bwd = {fwd(P_hc):9.3g}/{bwd(P_hc):9.3g} | "
          f"Sinkhorn t=1 {fwd(P_m1):.3f}/{bwd(P_m1):.3f} | t=20 {fwd(P_m20):.4f}/{bwd(P_m20):.4f}")

# the three properties behind mHC, checked numerically
B1, B2 = sinkhorn(np.exp(rng.normal(size=(n, n))), 50), sinkhorn(np.exp(rng.normal(size=(n, n))), 50)
X = rng.normal(size=(n, 8))                                          # n streams of width 8
print("spectral norm ≤ 1:", np.linalg.norm(B1, 2).round(6),
      "| product doubly stochastic:", np.allclose((B1 @ B2).sum(0), 1) and np.allclose((B1 @ B2).sum(1), 1),
      "| stream sum preserved:", np.allclose((B1 @ X).sum(0), X.sum(0)))

# pre-norm dilution: with h_{l+1} = h_l + f_l, layer l's share of the final stream shrinks like 1/L
h = rng.normal(size=256); outs = []
for l in range(48):
    f = rng.normal(size=256)                        # each branch writes an RMS-1 update
    outs.append(f); h = h + f
print("pre-norm stream RMS after 48 layers:", np.sqrt((h**2).mean()).round(2), "(≈ √49 = 7)",
      "| one layer's share of the final stream ≈", (np.linalg.norm(outs[10]) / np.linalg.norm(h)).round(3))
 

Positions at long context

RoPE rotates each pair ii of query/key coordinates by angle mθim\theta_i, θi=b−2i/d\theta_i=b^{-2i/d}, so scores depend only on m−nm-n. Each pair has a wavelength λi=2π/θi=2πb2i/d\lambda_i=2\pi/\theta_i=2\pi b^{2i/d} tokens. Pairs with λi\lambda_i shorter than the training length LL have completed many turns during training — any angle is familiar. Pairs with λi>L\lambda_i>L have only ever seen angles in [0,Lθi)[0,L\theta_i). Run the model at L′>LL'>L and those pairs produce angles it has never seen: that is why perplexity explodes just past the training length. With d=128d=128 and b=500,000b=500{,}000 (Llama 3), 29 of the 64 pairs have λ>8192\lambda>8192.

There are three levers.

  • Raise the base. A larger bb stretches all wavelengths, so more of the context sits inside the first turn of the slow pairs and attention to distant tokens decays less with distance. Bases have grown from 10,000 (DeepSeek-V3’s decoupled key) to 500K (Llama 3), 1M (Qwen3, Gemma 3 global layers), 5M (MiniMax-M2) and 10710^7 (MiniMax-M1, Qwen3-Next). Changing the base needs training at that base.
  • Rescale the frequencies at extension time. With s=L′/Ls=L'/L:
    • Position Interpolation: θi′=θi/s\theta_i'=\theta_i/s — no pair extrapolates, but the fastest pairs slow down too, so neighbouring tokens become ss times harder to tell apart.
    • NTK-aware: b′=b sd/(d−2)b'=b\,s^{d/(d-2)} — the slowest pair is divided by exactly ss, the fastest is untouched, but middle pairs still overshoot.
    • NTK-by-parts (YaRN): with ri=L/λir_i=L/\lambda_i (turns completed in training), θi′=(1−γ(ri)) θi/s+γ(ri) θi\theta_i'=(1-\gamma(r_i))\,\theta_i/s+\gamma(r_i)\,\theta_i, γ\gamma a ramp from 0 at r<αr<\alpha to 1 at r>βr>\beta (α=1,β=32\alpha=1,\beta=32 for Llama). Pairs that never finished a turn are interpolated, pairs that turned ≥32\ge32 times keep their frequency. YaRN also scales attention by 1/t=0.1ln⁡s+1\sqrt{1/t}=0.1\ln s+1 to compensate for the flatter softmax at long range. Llama 3.1’s rope_type: llama3 is the same idea in wavelength terms (factor 8, low_freq_factor 1, high_freq_factor 4, original 8192) — i.e. α=1,β=4\alpha=1,\beta=4. DeepSeek-V3 uses YaRN with s=40s=40, α=1,β=32\alpha=1,\beta=32 from 4K; gpt-oss s=32s=32 from 4K; Kimi K2’s config sets beta_fast = beta_slow = 1, a hard switch at one turn.
  • Rotate fewer dimensions, or none. Partial RoPE rotates only a slice of each head (Qwen3-Next: 64 of 256 dims; MiniMax: 64 of 128; DeepSeek MLA: a separate 64-dim key, because RoPE between WUKW^{UK} and the query would break weight absorption — see attention variants). The rest of the head is a position-free content channel. NoPE drops positional encoding in some layers entirely: Llama 4 Scout in every 4th layer (no_rope_layers), SmolLM3 likewise, Kimi Linear/K3 in all MLA layers (the KDA layers’ decay carries position), Nemotron 3 in all attention layers (Mamba carries position). The appeal is that a NoPE layer has nothing to extrapolate. The risk showed up in Qwen3.8-Next: NoPE in the full-attention layers looked identical in pre-training, but showed a substantially higher rate of endless generation after post-training, so RoPE was kept.
NumPy HC 대 mHC: 합성 이득, doubly stochastic의 세 성질, 그리고 pre-norm 희석
import numpy as np
rng = np.random.default_rng(0)
n, L = 4, 64

def sinkhorn(M, iters):
    for _ in range(iters):
        M = M / M.sum(0, keepdims=True)              # 열 합을 1로
        M = M / M.sum(1, keepdims=True)              # 행 합을 1로
    return M
fwd = lambda P: np.abs(P).sum(1).max()               # 행 합 최대: 순방향이 증폭할 수 있는 양
bwd = lambda P: np.abs(P).sum(0).max()               # 열 합 최대: 역방향은 Pᵀ를 곱한다

for sigma in [0.1, 0.3]:
    P_hc, P_m1, P_m20 = np.eye(n), np.eye(n), np.eye(n)
    for _ in range(L):
        G = rng.normal(size=(n, n))
        P_hc = (np.eye(n) + sigma * G) @ P_hc                        # 제약 없는 hyper-connection
        E = np.exp(2 * np.eye(n) + 3 * sigma * G)                    # 양수, 대각 위주
        P_m1 = sinkhorn(E, 1) @ P_m1
        P_m20 = sinkhorn(E, 20) @ P_m20                              # mHC (t_max = 20)
    print(f"σ={sigma}: after {L} layers  HC fwd/bwd = {fwd(P_hc):9.3g}/{bwd(P_hc):9.3g} | "
          f"Sinkhorn t=1 {fwd(P_m1):.3f}/{bwd(P_m1):.3f} | t=20 {fwd(P_m20):.4f}/{bwd(P_m20):.4f}")

# mHC를 받치는 세 성질을 수치로 확인
B1, B2 = sinkhorn(np.exp(rng.normal(size=(n, n))), 50), sinkhorn(np.exp(rng.normal(size=(n, n))), 50)
X = rng.normal(size=(n, 8))                                          # 폭 8짜리 stream n개
print("spectral norm ≤ 1:", np.linalg.norm(B1, 2).round(6),
      "| product doubly stochastic:", np.allclose((B1 @ B2).sum(0), 1) and np.allclose((B1 @ B2).sum(1), 1),
      "| stream sum preserved:", np.allclose((B1 @ X).sum(0), X.sum(0)))

# pre-norm 희석: h_{l+1} = h_l + f_l이면 한 층의 몫은 1/L처럼 줄어든다
h = rng.normal(size=256); outs = []
for l in range(48):
    f = rng.normal(size=256)                        # 각 branch가 RMS 1의 갱신을 쓴다
    outs.append(f); h = h + f
print("pre-norm stream RMS after 48 layers:", np.sqrt((h**2).mean()).round(2), "(≈ √49 = 7)",
      "| one layer's share of the final stream ≈", (np.linalg.norm(outs[10]) / np.linalg.norm(h)).round(3))
 

긴 문맥에서의 위치

RoPE는 query/key 좌표의 쌍 ii를 각도 mθim\theta_i, θi=b−2i/d\theta_i=b^{-2i/d}만큼 돌려 점수가 m−nm-n에만 의존하게 한다. 쌍마다 파장 λi=2π/θi=2πb2i/d\lambda_i=2\pi/\theta_i=2\pi b^{2i/d} 토큰이 있다. λi\lambda_i가 학습 길이 LL보다 짧은 쌍은 학습 중 여러 바퀴를 돌았으므로 어느 각도든 익숙하다. λi>L\lambda_i>L인 쌍은 [0,Lθi)[0,L\theta_i)의 각도만 보았다. 모델을 L′>LL'>L에서 돌리면 이 쌍들이 본 적 없는 각도를 만든다. 학습 길이를 조금만 넘어도 perplexity가 폭발하는 이유다. d=128d=128, b=500,000b=500{,}000(Llama 3)이면 64쌍 중 29쌍이 λ>8192\lambda>8192다.

손잡이는 셋이다.

  • base를 키운다. bb가 크면 모든 파장이 늘어나, 문맥의 더 많은 부분이 느린 쌍의 첫 바퀴 안에 들어가고 먼 토큰에 대한 attention이 거리에 따라 덜 감쇠한다. base는 10,000(DeepSeek-V3의 decoupled key)에서 500K(Llama 3), 1M(Qwen3, Gemma 3 global 층), 5M(MiniMax-M2), 10710^7(MiniMax-M1, Qwen3-Next)까지 커졌다. base를 바꾸려면 그 base로 학습해야 한다.
  • 확장할 때 주파수를 다시 맞춘다. s=L′/Ls=L'/L로 두면
    • Position Interpolation: θi′=θi/s\theta_i'=\theta_i/s. 외삽되는 쌍은 없지만 가장 빠른 쌍도 느려져서 이웃 토큰을 ss배 구별하기 어려워진다.
    • NTK-aware: b′=b sd/(d−2)b'=b\,s^{d/(d-2)}. 가장 느린 쌍은 정확히 ss로 나뉘고 가장 빠른 쌍은 그대로지만, 중간 쌍은 여전히 범위를 넘어선다.
    • NTK-by-parts (YaRN): ri=L/λir_i=L/\lambda_i(학습 중 돈 바퀴 수)로 θi′=(1−γ(ri)) θi/s+γ(ri) θi\theta_i'=(1-\gamma(r_i))\,\theta_i/s+\gamma(r_i)\,\theta_i, γ\gamma는 r<αr<\alpha에서 0, r>βr>\beta에서 1인 ramp다(Llama에서 α=1,β=32\alpha=1,\beta=32). 한 바퀴도 못 돈 쌍은 보간하고, 32바퀴 이상 돈 쌍은 주파수를 유지한다. YaRN은 긴 거리에서 softmax가 평평해지는 것을 보정하려고 attention을 1/t=0.1ln⁡s+1\sqrt{1/t}=0.1\ln s+1배 한다. Llama 3.1의 rope_type: llama3은 같은 생각을 파장으로 쓴 것이다(factor 8, low_freq_factor 1, high_freq_factor 4, original 8192). 즉 α=1,β=4\alpha=1,\beta=4다. DeepSeek-V3는 4K에서 s=40s=40, α=1,β=32\alpha=1,\beta=32의 YaRN, gpt-oss는 4K에서 s=32s=32, Kimi K2의 config는 beta_fast = beta_slow = 1로 한 바퀴에서 딱 끊는다.
  • 회전하는 차원을 줄이거나 없앤다. partial RoPE는 head의 일부만 돌린다(Qwen3-Next: 256차원 중 64; MiniMax: 128 중 64; DeepSeek MLA: 별도의 64차원 key. WUKW^{UK}와 query 사이에 RoPE가 끼면 가중치 흡수가 깨지기 때문이다 — attention 변형 참고). head의 나머지는 위치 없는 내용 채널이다. NoPE는 일부 층에서 위치 인코딩을 아예 없앤다. Llama 4 Scout는 4층마다(no_rope_layers), SmolLM3도 그렇고, Kimi Linear/K3는 모든 MLA 층(KDA 층의 감쇠가 위치를 싣는다), Nemotron 3는 모든 attention 층(Mamba가 위치를 싣는다)이다. 매력은 NoPE 층에는 외삽할 것이 없다는 점이다. 위험은 Qwen3.8-Next에서 드러났다. full attention 층의 NoPE는 사전학습에서는 똑같아 보였지만 사후학습 뒤 끝없는 생성 비율이 상당히 높았고, 그래서 RoPE를 유지했다.
외삽(OOD) 쌍extrapolated pairs – 보간된 쌍interpolated – 그대로untouched – 가장 빠른 쌍: 토큰당fastest pair: per token – YaRN √(1/t) – NoPE dims –
Left: wavelength of each rotary pair in tokens (log scale), grey = original, coloured = after the method: green untouched, amber interpolated (slowed down), red extrapolated — a pair that never completed a turn during training and now sweeps angles more than 10% beyond any it has seen. Dashed lines: training length L and target L′. Right: how much each pair is slowed, θ′/θ. Pick “none” and raise L′: every pair with λ > L turns red. PI fixes that by dividing all frequencies by s — including the fastest pairs, so neighbouring tokens become s× harder to tell apart. NTK-aware changes the base so the slowest pair is divided by s and fast pairs are almost untouched, but the middle pairs still overshoot their training range by up to about √s. YaRN / Llama 3 interpolate only pairs whose wavelength exceeds the training length, keep pairs that rotated ≥ 32 (YaRN) or ≥ 4 (Llama 3) times, and blend in between. Lower the rotary fraction to see partial RoPE: fewer pairs, and the remaining dims carry no position at all. 왼쪽은 회전 쌍마다의 파장(토큰, log)이다. 회색은 원래 값, 색은 방법 적용 후: 초록 그대로, 주황 보간(느려짐), 빨강 외삽. 학습 중 한 바퀴도 돌지 못한 쌍이 이제 본 적 있는 최대 각도를 10% 넘게 지나간다는 뜻이다. 점선은 학습 길이 L과 목표 L′. 오른쪽은 각 쌍이 얼마나 느려졌는지, θ′/θ다. “none”을 고르고 L′을 올리면 λ > L인 쌍이 모두 빨개진다. PI는 모든 주파수를 s로 나눠 이를 고치지만 가장 빠른 쌍까지 느려져 이웃 토큰을 s배 구별하기 어려워진다. NTK-aware는 base를 바꿔 가장 느린 쌍만 s로 나누고 빠른 쌍은 거의 그대로 두지만, 중간 쌍은 여전히 학습 범위를 최대 약 √s배 넘어선다. YaRN / Llama 3은 파장이 학습 길이를 넘는 쌍만 보간하고, 32번(YaRN) 또는 4번(Llama 3) 이상 돈 쌍은 그대로 두며, 그 사이는 섞는다. 회전 비율을 낮추면 partial RoPE다. 쌍이 줄고, 나머지 차원은 위치 정보를 전혀 싣지 않는다.
NumPy RoPE scaling: which pairs extrapolate under PI, NTK-aware, YaRN and Llama-3 scaling
import numpy as np

def inv_freq(d_rot, base):                         # θ_i = base^(−2i/d_rot), i = 0 .. d_rot/2 − 1
    return base ** (-np.arange(0, d_rot, 2) / d_rot)

def scaled(theta, method, L, s, d_rot, base, alpha=1.0, beta=32.0):
    lam = 2 * np.pi / theta                        # wavelength in tokens
    r = L / lam                                    # full turns completed within the training length
    if method == "PI":
        return theta / s
    if method == "NTK-aware":
        return inv_freq(d_rot, base * s ** (d_rot / (d_rot - 2)))
    if method in ("YaRN", "Llama3"):
        a, b = (alpha, beta) if method == "YaRN" else (1.0, 4.0)    # Llama 3: low/high_freq_factor 1, 4
        g = np.clip((r - a) / (b - a), 0, 1)       # 0 → interpolate (θ/s), 1 → keep θ
        return (1 - g) * theta / s + g * theta
    return theta

def report(name, d_rot, base, L, Lp, **kw):
    th = inv_freq(d_rot, base); s = Lp / L
    print(f"{name}: d_rot={d_rot}, base={base:.0e}, L={L}, L'={Lp} (s={s:g})")
    for m in ["none", "PI", "NTK-aware", "YaRN", "Llama3"]:
        tp = scaled(th, m, L, s, d_rot, base, **kw)
        ood = (L * th < 2 * np.pi) & (Lp * tp > 1.1 * L * th)   # never completed a turn, now sweeps >10% further
        interp = (tp < th * (1 - 1e-9)) & ~ood
        print(f"  {m:9s} extrapolated {ood.sum():2d}  interpolated {interp.sum():2d}  untouched {len(th) - ood.sum() - interp.sum():2d}"
              f"   fastest pair {tp[0]:.3f} rad/token")
    print(f"  YaRN attention scale sqrt(1/t) = 0.1 ln s + 1 = {0.1 * np.log(s) + 1:.3f}")

report("Llama 3.1-like", 128, 5e5, 8192, 65536)
report("DeepSeek-V3 decoupled key", 64, 1e4, 4096, 163840)

# RoPE keeps the score a function of m − n only — and so does every rescaled frequency set
def rope(x, pos, theta):
    x1, x2 = x[0::2], x[1::2]
    c, s_ = np.cos(pos * theta), np.sin(pos * theta)
    return np.stack([x1 * c - x2 * s_, x1 * s_ + x2 * c], -1).ravel()
rng = np.random.default_rng(0)
q, k = rng.normal(size=64), rng.normal(size=64)
th = scaled(inv_freq(64, 1e4), "YaRN", 4096, 40.0, 64, 1e4)
a = rope(q, 1000, th) @ rope(k, 900, th); b = rope(q, 151000, th) @ rope(k, 150900, th)
print(f"score at (1000, 900) = {a:.6f}, at (151000, 150900) = {b:.6f}  → depends only on m − n")
 

Every method leaves RoPE’s relative-position property intact — it only changes which angles the model sees. PI is the only method with zero extrapolation and the only one that slows the fastest pair (to 1/s1/s rad per token); YaRN and Llama-3 scaling get zero extrapolation while keeping the fast pairs exactly. NTK-aware, which needs no fine-tuning, leaves 26 of 64 pairs overshooting.

확인 문제Check yourself

You extend a model from 8K to 64K with Position Interpolation (s = 8) and see worse accuracy on tasks that need exact local order (copying code, counting characters). What is the most likely cause, and the standard fix?

PI maps positions m↦m/sm\mapsto m/s, i.e. θi↦θi/s\theta_i\mapsto\theta_i/s for every pair. Slow pairs no longer extrapolate, but the fast pairs that encode “one token apart” are slowed 8×8\times, a loss of local resolution. NTK-by-parts interpolates only pairs whose wavelength exceeds the training length (r=L/λ<αr=L/\lambda<\alpha), keeps pairs with r>βr>\beta, and blends in between. The relative-position property holds for any fixed set of frequencies.

Summary

  • Pre-norm keeps a clean identity path for gradients but lets the stream grow like L\sqrt L and dilutes late layers; post-norm keeps the stream bounded but routes gradients through LL normalisations. Sandwich (Gemma), reordered (OLMo 2) and DeepNorm-style scaling (MiniMax-M1’s α\alpha) are compromises between the two.
  • Attention logits are bounded only by ∥Wq∥∥Wk∥\|W_q\|\|W_k\|. QK-norm removes that dependence; QK-clip rescales weights between steps when MLA rules out QK-norm; soft-capping bounds values but erases differences among large logits; z-loss pins the free shift log⁡Z\log Z of the output softmax.
  • Widening the residual stream (HC) adds a new axis but makes the residual path a matrix product that explodes unless constrained; mHC’s doubly stochastic projection makes it non-expansive at any depth; Gated Residual drops the mixing matrix; Attention Residuals replace the fixed sum by attention over depth.
  • RoPE pairs with wavelength longer than the training length are what extrapolate. Larger bases, interpolation (PI, NTK, YaRN, Llama 3), partial RoPE and NoPE layers are four ways to deal with them; YaRN-style by-parts scaling keeps local resolution, and NoPE must be validated after post-training.
NumPy RoPE 스케일링: PI, NTK-aware, YaRN, Llama-3 스케일링에서 어떤 쌍이 외삽되나
import numpy as np

def inv_freq(d_rot, base):                         # θ_i = base^(−2i/d_rot), i = 0 .. d_rot/2 − 1
    return base ** (-np.arange(0, d_rot, 2) / d_rot)

def scaled(theta, method, L, s, d_rot, base, alpha=1.0, beta=32.0):
    lam = 2 * np.pi / theta                        # 파장 (토큰)
    r = L / lam                                    # 학습 길이 안에서 돈 바퀴 수
    if method == "PI":
        return theta / s
    if method == "NTK-aware":
        return inv_freq(d_rot, base * s ** (d_rot / (d_rot - 2)))
    if method in ("YaRN", "Llama3"):
        a, b = (alpha, beta) if method == "YaRN" else (1.0, 4.0)    # Llama 3: low/high_freq_factor 1, 4
        g = np.clip((r - a) / (b - a), 0, 1)       # 0 → 보간 (θ/s), 1 → θ 유지
        return (1 - g) * theta / s + g * theta
    return theta

def report(name, d_rot, base, L, Lp, **kw):
    th = inv_freq(d_rot, base); s = Lp / L
    print(f"{name}: d_rot={d_rot}, base={base:.0e}, L={L}, L'={Lp} (s={s:g})")
    for m in ["none", "PI", "NTK-aware", "YaRN", "Llama3"]:
        tp = scaled(th, m, L, s, d_rot, base, **kw)
        ood = (L * th < 2 * np.pi) & (Lp * tp > 1.1 * L * th)   # 한 바퀴도 못 돌았는데 이제 10% 넘게 더 간다
        interp = (tp < th * (1 - 1e-9)) & ~ood
        print(f"  {m:9s} extrapolated {ood.sum():2d}  interpolated {interp.sum():2d}  untouched {len(th) - ood.sum() - interp.sum():2d}"
              f"   fastest pair {tp[0]:.3f} rad/token")
    print(f"  YaRN attention scale sqrt(1/t) = 0.1 ln s + 1 = {0.1 * np.log(s) + 1:.3f}")

report("Llama 3.1-like", 128, 5e5, 8192, 65536)
report("DeepSeek-V3 decoupled key", 64, 1e4, 4096, 163840)

# RoPE는 점수를 m − n만의 함수로 유지한다 — 다시 맞춘 어떤 주파수 집합에서도
def rope(x, pos, theta):
    x1, x2 = x[0::2], x[1::2]
    c, s_ = np.cos(pos * theta), np.sin(pos * theta)
    return np.stack([x1 * c - x2 * s_, x1 * s_ + x2 * c], -1).ravel()
rng = np.random.default_rng(0)
q, k = rng.normal(size=64), rng.normal(size=64)
th = scaled(inv_freq(64, 1e4), "YaRN", 4096, 40.0, 64, 1e4)
a = rope(q, 1000, th) @ rope(k, 900, th); b = rope(q, 151000, th) @ rope(k, 150900, th)
print(f"score at (1000, 900) = {a:.6f}, at (151000, 150900) = {b:.6f}  → depends only on m − n")
 

어떤 방법도 RoPE의 상대 위치 성질을 깨지 않는다. 모델이 보게 되는 각도만 바꾼다. PI는 외삽이 0인 유일한 방법이자 가장 빠른 쌍을 느리게 하는(토큰당 1/s1/s rad) 유일한 방법이다. YaRN과 Llama-3 스케일링은 빠른 쌍을 정확히 유지하면서 외삽 0을 얻는다. 미세조정이 필요 없는 NTK-aware는 64쌍 중 26쌍이 범위를 넘어선다.

확인 문제Check yourself

모델을 Position Interpolation(s = 8)으로 8K에서 64K로 늘렸더니 정확한 국소 순서가 필요한 과제(코드 복사, 글자 세기)가 나빠졌다. 가장 그럴듯한 원인과 표준 처방은?

PI는 위치를 m↦m/sm\mapsto m/s로, 즉 모든 쌍에서 θi↦θi/s\theta_i\mapsto\theta_i/s로 보낸다. 느린 쌍은 더 외삽되지 않지만 “한 토큰 차이”를 부호화하는 빠른 쌍이 88배 느려져 국소 해상도를 잃는다. NTK-by-parts는 파장이 학습 길이를 넘는 쌍(r=L/λ<αr=L/\lambda<\alpha)만 보간하고 r>βr>\beta인 쌍은 유지하며 그 사이를 섞는다. 상대 위치 성질은 고정된 어떤 주파수 집합에서도 성립한다.

정리

  • pre-norm은 기울기의 항등 경로를 깨끗하게 지키지만 stream이 L\sqrt L처럼 자라 뒤쪽 층이 희석된다. post-norm은 stream을 묶지만 기울기를 정규화 LL개에 통과시킨다. sandwich(Gemma), reordered(OLMo 2), DeepNorm식 배율(MiniMax-M1의 α\alpha)은 그 사이의 타협이다.
  • attention logit은 ∥Wq∥∥Wk∥\|W_q\|\|W_k\|로만 묶인다. QK-norm은 그 의존성을 없애고, QK-clip은 MLA 때문에 QK-norm을 못 쓸 때 step 사이에 가중치를 재조정하고, soft-cap은 값을 묶지만 큰 logit 사이의 차이를 지우고, z-loss는 출력 softmax의 자유 shift log⁡Z\log Z를 고정한다.
  • residual stream을 넓히면(HC) 새 축이 생기지만 residual 경로가 제약 없이는 폭발하는 행렬 곱이 된다. mHC의 doubly stochastic 사영은 어느 깊이에서도 비확장으로 만들고, Gated Residual은 혼합 행렬을 없애고, Attention Residuals는 고정된 합을 깊이 방향 attention으로 바꾼다.
  • 외삽되는 것은 파장이 학습 길이보다 긴 RoPE 쌍이다. 큰 base, 보간(PI, NTK, YaRN, Llama 3), partial RoPE, NoPE 층이 이를 다루는 네 방법이고, YaRN식 by-parts 스케일링은 국소 해상도를 지키며, NoPE는 사후학습 뒤에 검증해야 한다.

더 읽을거리Further reading