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:
| Model | Norm and logit control | Residual stream | Positions |
|---|---|---|---|
| Gemma 2 | RMSNorm before and after each sublayer; soft-cap 50 (attention), 30 (final logits) | standard | RoPE |
| Gemma 3 | same norms; QK-norm replaces soft-capping | standard | RoPE base 10K local / 1M global, 5 local : 1 global, ×8 interpolation for 128K |
| OLMo 2 | reordered norm , QK-norm, z-loss | standard | RoPE |
| Qwen3-Next | zero-centred RMSNorm with weight decay on the gains; sigmoid output gate on attention | standard | partial RoPE (25% of 256 dims), base |
| Qwen3.8-Flash-Next | Gated Residual read replaces the pre-norm; Muon without QK-clip | Gated Residual, 4 branches | partial RoPE 25%; NoPE tried and rejected |
| Kimi K2 | pre-norm; QK-Clip τ = 100 (MLA cannot use QK-norm) | standard | decoupled RoPE, YaRN ×32 from 4K |
| Kimi K3 | gated MLA with channel-wise output gate | Block Attention Residuals (12-layer blocks) | NoPE in MLA; KDA carries position |
| DeepSeek-V3 | pre-norm RMSNorm | standard | decoupled RoPE on 64 dims, YaRN from 4K |
| DeepSeek-V4 | RMSNorm on queries and KV entries (no QK-Clip needed under Muon) | mHC, , Sinkhorn | RoPE on the last 64 dims + output counter-rotation |
| MiniMax-M1 | post-norm with residual scale (config) | standard | RoPE on 64 of 128 dims, base |
| MiniMax-M2 | QK-norm (use_qk_norm) | standard | RoPE on 64 of 128 dims, base |
| Llama 4 Scout | QK-norm (use_qk_norm) | standard | NoPE every 4th layer, attention temperature tuning; Llama-3 scaling ×16 |
| Nemotron 3 Ultra | — | standard | no positional encoding in attention; Mamba carries position |
Where the norm goes
Four placements are in use, plus one scaling trick:
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 grows like and the -th layer’s update is a fraction 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 term of ); post-norm’s identity path goes through normalisations, each multiplying by a Jacobian , 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 and shrinks the branches at init.
MiniMax-M1’s config, for what it is worth, sets postnorm: true with every residual scale — exactly 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, with initialised at 0 and weight decay on , 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 2 | reordered norm , QK-norm, z-loss | 표준 | RoPE |
| Qwen3-Next | gain에 weight decay를 건 zero-centered RMSNorm; attention 출력 sigmoid gate | 표준 | partial RoPE(256차원 중 25%), base |
| Qwen3.8-Flash-Next | Gated Residual 읽기가 pre-norm을 대체; QK-clip 없는 Muon | Gated Residual, branch 4개 | partial RoPE 25%; NoPE를 시험하고 기각 |
| Kimi K2 | pre-norm; QK-Clip τ = 100 (MLA는 QK-norm을 못 씀) | 표준 | decoupled RoPE, 4K에서 YaRN ×32 |
| Kimi K3 | 채널별 출력 gate가 있는 gated MLA | Block Attention Residuals (12층 block) | MLA는 NoPE; 위치는 KDA가 맡음 |
| DeepSeek-V3 | pre-norm RMSNorm | 표준 | 64차원 decoupled RoPE, 4K에서 YaRN |
| DeepSeek-V4 | query와 KV 항목에 RMSNorm (Muon에서도 QK-Clip 불필요) | mHC, , Sinkhorn | 마지막 64차원에 RoPE + 출력 역회전 |
| MiniMax-M1 | residual 배율 의 post-norm (config) | 표준 | 128차원 중 64차원 RoPE, base |
| MiniMax-M2 | QK-norm (use_qk_norm) | 표준 | 128차원 중 64차원 RoPE, base |
| Llama 4 Scout | QK-norm (use_qk_norm) | 표준 | 4층마다 NoPE, attention temperature tuning; Llama-3 스케일링 ×16 |
| Nemotron 3 Ultra | — | 표준 | attention에 위치 인코딩 없음; 위치는 Mamba가 맡음 |
norm을 어디에 두나
쓰이는 배치는 넷, 그리고 배율 요령 하나다.
각각이 사 주는 것은 깊이 방향의 두 곱에 대한 진술이다. 순방향: pre-norm에서는 모든 branch가 정규화되지 않은 stream에 대략 일정한 크기의 갱신을 더하므로 이 처럼 자라고, 번째 층의 갱신은 stream의 약 비율이다. 뒤쪽 층은 stream을 거의 움직이지 못한다. Attention Residuals 논문은 이것을 PreNorm 희석(dilution) 이라 부른다. post-norm은 층마다 stream을 RMS 1로 되돌리므로 희석이 없다. 역방향: pre-norm의 항등 경로는 기울기를 모든 층에 그대로 나른다(의 항). post-norm의 항등 경로는 정규화 개를 지나며 매번 Jacobian 를 곱하므로, 앞쪽 층에 닿는 기울기가 깊이와 branch 이득에 따라 달라진다. post-norm Transformer에 warm-up이 필요했던 이유다(Xiong et al. 2020). sandwich와 reordered norm은 pre-norm의 깨끗한 항등 경로를 지키면서 각 branch가 더할 수 있는 크기를 묶고, DeepNorm은 post-norm을 유지하되 항등 경로를 로 키우고 branch를 초기화 때 줄인다.
참고로 MiniMax-M1의 config는 postnorm: true와 모든 residual 배율 을 쓴다. 80층에 대한 DeepNet의 decoder-only 공식 과 정확히 같다(우리의 관찰이며 보고서는 이를 논하지 않는다). Qwen3-Next는 더 작은 것을 바꿨다. zero-centered RMSNorm 에서 를 0으로 초기화하고 에 weight decay를 걸어, decay가 gain을 0이 아니라 1 쪽으로 당기게 했다. Qwen3에서 QK-norm gain이 비정상적으로 커지는 것을 본 뒤의 변경이다.
Attention-logit growth, and four ways to bound it
With RMSNorm’d inputs, an attention logit is bounded only by the weights:
Nothing in the loss stops 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 diverged, with the attention weights collapsing to one-hot vectors. Two mechanisms make large logits dangerous. The softmax Jacobian vanishes as 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 faster.
The remedies act at different points of the computation:
| Remedy | Where it acts | Guarantee | Cost / caveat | Used by |
|---|---|---|---|---|
| QK-norm | normalise per head (RMSNorm with gain ) before the dot product | , independent of | needs materialised per head — incompatible with MLA’s absorbed keys | Gemma 3, OLMo 2, Qwen3, MiniMax-M2, Llama 4 |
| QK-clip | after the optimiser step, if head ‘s max logit , scale by | max logit ≤ τ from the next step on, ranking preserved | needs the max logit per head from the forward pass; a guard rail, not an entropy control | Kimi K2 (τ = 100) |
| Soft-cap | on the logits | compresses differences among large logits; gradient ; needs kernel support | Gemma 2 (50 / 30) | |
| z-loss | auxiliary on the output softmax | keeps | one hyper-parameter, | PaLM, OLMo 2 |
QK-norm is the most direct: the logit becomes , so the model can sharpen a head only by growing a -dimensional gain, not two 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, , so nothing pins the overall level . Wortsman et al. observed output logit divergence: logits drift very negative and training becomes unstable. Adding (PaLM’s coefficient) gives the free direction a weak restoring force; its gradient shifts all logits together and leaves their differences — the prediction — alone.
attention logit 성장, 그리고 그것을 묶는 네 방법
RMSNorm한 입력에서 attention logit은 가중치로만 묶인다.
손실에는 가 커지는 것을 막는 항이 없다. head가 확신을 가지면 logit을 키울수록 softmax가 날카로워지고 비용은 거의 없다. Dehghani et al.은 ViT-22B에서 이것을 보았고(“attention logit growth”), Wortsman et al.은 작은 모델에서 재현해 attention logit이 을 넘은 run은 모두 발산했다는 것과 attention 가중치가 one-hot으로 무너진다는 것을 보였다. 큰 logit이 위험한 메커니즘은 둘이다. 가 one-hot이 되면 softmax Jacobian 이 사라져 head가 더 배우지 못한다. 그리고 BF16은 유효 비트가 8개라 logit 1000 근처에서 표현 가능한 수의 간격이 4다. 어느 key가 이기는지를 담은 logit 차이가 반올림으로 사라진다. K2 레슨은 Muon이 이것을 악화시킨다는 것을 보여 준다. full-rank 갱신이 의 spectral norm을 더 빨리 키운다.
처방들은 계산의 서로 다른 지점에 작용한다.
| 처방 | 작용 지점 | 보장 | 비용 / 단서 | 쓰는 곳 |
|---|---|---|---|---|
| QK-norm | 내적 전에 head별로 정규화(gain 가 있는 RMSNorm) | , 와 무관 | head별 가 실체화되어야 한다. MLA의 흡수된 key와 맞지 않는다 | Gemma 3, OLMo 2, Qwen3, MiniMax-M2, Llama 4 |
| QK-clip | optimizer step 뒤, head 의 최대 logit 이면 를 배 | 다음 step부터 최대 logit ≤ τ, 순위 보존 | forward에서 head별 최대 logit이 필요; 엔트로피 조절이 아니라 가드레일 | Kimi K2 (τ = 100) |
| soft-cap | logit에 | 큰 logit 사이의 차이를 압축; 기울기 ; 커널 지원 필요 | Gemma 2 (50 / 30) | |
| z-loss | 출력 softmax에 보조항 | 유지 | 하이퍼파라미터 하나, | PaLM, OLMo 2 |
QK-norm이 가장 직접적이다. logit이 가 되므로, 모델은 행렬 둘이 아니라 차원 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에 상수를 더해도 변하지 않으므로() 전체 수준 을 붙잡는 것이 없다. Wortsman et al.은 출력 logit 발산을 관찰했다. logit이 크게 음수로 흘러가며 학습이 불안정해진다. (PaLM의 계수)를 더하면 이 자유 방향에 약한 복원력이 생긴다. 기울기 는 모든 logit을 함께 옮기고, 예측을 담은 logit 사이의 차이는 건드리지 않는다.
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 directionRead the table row by row. Without control, at the head is already one-hot and is : the head has stopped learning, and every further growth only adds numerical risk. QK-norm’s logits do not move with 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 pins both top keys at 50: the gap collapses to 0 and the head can no longer say which key it wants.
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 , so once both are : the ranking information is squashed (and the gradient vanishes). z-loss acts on the output softmax’s normaliser, not on attention. QK-norm removes the dependence on entirely; only cosines (times a learned gain) remain. QK-clip would also keep the ranking, by rescaling the weights.
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.14A 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 copies and learn how the layer reads them, how it writes back and how the copies mix:
With and this is the ordinary residual. The trouble is depth: ignoring the layer outputs, the residual path after layers is , and if the 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 to the doubly stochastic matrices: , alternating column and row normalisation (). Three one-line facts do the work: row and column sums equal to 1 with non-negative entries give , hence (forward and backward non-expansive); the product of doubly stochastic matrices is doubly stochastic, so this holds at any depth; and , so the path only redistributes mass between streams. At 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 altogether: each block reads through an elementwise sigmoid gate predicted from all branches (this read replaces the pre-norm) and writes . Without 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, brought no significant gain. Attention Residuals (Kimi) go the other way: each layer reads a softmax-weighted mix of earlier layer outputs, with a learned per-layer query, which removes PreNorm dilution by construction; Block AttnRes (K3: blocks of 12 layers) keeps memory at . See the K3 lesson.
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 방향을 균일하게 당긴다표를 행별로 읽자. 통제가 없으면 에서 이미 head가 one-hot이고 는 이다. head는 배우기를 멈췄고, 그 뒤의 성장은 수치 위험만 더한다. QK-norm의 logit은 와 무관하게 움직이지 않는다. QK-clip은 최대값을 τ = 100으로 묶지만 one-hot head는 여전히 허용한다. 날카로움을 정규화하는 것이 아니라 폭주를 막는 가드레일이고, 그래서 K2는 τ = 100으로 손실 곡선을 바꾸지 않고 쓸 수 있었다. soft-cap은 가 크면 상위 key 둘 다를 50에 고정한다. 간격이 0으로 무너져 head가 어느 key를 원하는지 말할 수 없다.
학습 중 어떤 head의 원래 logit이 계속 커진다. 성장이 아무리 계속돼도 head가 가장 좋은 두 key를 구별할 수 있게 지켜 주는 처방은?
soft-capping은 값을 묶지만 큰 logit을 모두 근처로 보내므로, 둘 다 가 되면 이다. 순위 정보가 찌그러지고 기울기 도 사라진다. z-loss는 attention이 아니라 출력 softmax의 정규화 상수에 작용한다. QK-norm은 의존성을 완전히 없애고 cosine(곱하기 학습되는 gain)만 남긴다. QK-clip도 가중치를 재조정해 순위를 지킨다.
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을 벌 로 넓히고, 층이 어떻게 읽고 어떻게 다시 쓰며 사본끼리 어떻게 섞이는지를 배운다.
, 이면 보통의 residual이다. 문제는 깊이다. 층 출력을 빼고 보면 층 뒤의 residual 경로는 이고, 에 제약이 없으면 곱이 지수적으로 커지거나 줄어든다. mHC 논문은 그 합성 사상의 “Amax gain magnitude”, 즉 행 절댓값 합의 최대(순방향) 또는 열 절댓값 합의 최대(역방향)를 쟀고, 27B 모델에서 HC는 최고 약 3000, mHC는 약 1.6이었다.
mHC는 각 을 doubly stochastic 행렬로 제한한다. 열과 행 정규화를 번갈아 하는 ()이다. 한 줄짜리 사실 셋이 일을 한다. 음이 아닌 원소에 행 합·열 합이 1이면 이므로 이다(순방향과 역방향 모두 비확장). doubly stochastic 행렬의 곱은 doubly stochastic이므로 이것이 어느 깊이에서나 성립한다. 그리고 라서 경로는 stream 사이에 질량을 재분배할 뿐이다. 에서 논문은 학습 시간 6.7% 증가, 27B에서 BBH 43.8 → 48.9(HC) → 51.0(mHC)를 보고한다. 전체 파라미터화는 DeepSeek-V4 레슨에 있고, V4.1은 나중에 block마다 residual을 한 번만 읽고 쓰도록 재구성했다.
Gated Residual(Qwen3.8-Next)은 branch 넷을 유지하되 혼합 행렬 를 아예 없앤다. 각 block은 모든 branch에서 예측한 원소별 sigmoid gate로 를 읽고(이 읽기가 pre-norm을 대체한다) 로 쓴다. 가 없으니 폭발할 곱이 없고, decode에서 block마다 residual 상태 전체를 한 번 덜 읽는다. 보고서는 읽기·쓰기가 충분히 표현력이 있으면 가 의미 있는 이득을 주지 않는다고 본다. Attention Residuals(Kimi)는 반대 방향이다. 각 층이 이전 층 출력들의 softmax 가중 혼합 를 층별 학습 query로 읽어, 구조적으로 PreNorm 희석을 없앤다. Block AttnRes(K3: 12층 block)는 메모리를 로 유지한다. K3 레슨을 보라.
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 of query/key coordinates by angle , , so scores depend only on . Each pair has a wavelength tokens. Pairs with shorter than the training length have completed many turns during training — any angle is familiar. Pairs with have only ever seen angles in . Run the model at and those pairs produce angles it has never seen: that is why perplexity explodes just past the training length. With and (Llama 3), 29 of the 64 pairs have .
There are three levers.
- Raise the base. A larger 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 (MiniMax-M1, Qwen3-Next). Changing the base needs training at that base.
- Rescale the frequencies at extension time. With :
- Position Interpolation: — no pair extrapolates, but the fastest pairs slow down too, so neighbouring tokens become times harder to tell apart.
- NTK-aware: — the slowest pair is divided by exactly , the fastest is untouched, but middle pairs still overshoot.
- NTK-by-parts (YaRN): with (turns completed in training), , a ramp from 0 at to 1 at ( for Llama). Pairs that never finished a turn are interpolated, pairs that turned times keep their frequency. YaRN also scales attention by to compensate for the flatter softmax at long range. Llama 3.1’s
rope_type: llama3is the same idea in wavelength terms (factor 8,low_freq_factor1,high_freq_factor4, original 8192) — i.e. . DeepSeek-V3 uses YaRN with , from 4K; gpt-oss from 4K; Kimi K2’s config setsbeta_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 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.
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 좌표의 쌍 를 각도 , 만큼 돌려 점수가 에만 의존하게 한다. 쌍마다 파장 토큰이 있다. 가 학습 길이 보다 짧은 쌍은 학습 중 여러 바퀴를 돌았으므로 어느 각도든 익숙하다. 인 쌍은 의 각도만 보았다. 모델을 에서 돌리면 이 쌍들이 본 적 없는 각도를 만든다. 학습 길이를 조금만 넘어도 perplexity가 폭발하는 이유다. , (Llama 3)이면 64쌍 중 29쌍이 다.
손잡이는 셋이다.
- base를 키운다. 가 크면 모든 파장이 늘어나, 문맥의 더 많은 부분이 느린 쌍의 첫 바퀴 안에 들어가고 먼 토큰에 대한 attention이 거리에 따라 덜 감쇠한다. base는 10,000(DeepSeek-V3의 decoupled key)에서 500K(Llama 3), 1M(Qwen3, Gemma 3 global 층), 5M(MiniMax-M2), (MiniMax-M1, Qwen3-Next)까지 커졌다. base를 바꾸려면 그 base로 학습해야 한다.
- 확장할 때 주파수를 다시 맞춘다. 로 두면
- Position Interpolation: . 외삽되는 쌍은 없지만 가장 빠른 쌍도 느려져서 이웃 토큰을 배 구별하기 어려워진다.
- NTK-aware: . 가장 느린 쌍은 정확히 로 나뉘고 가장 빠른 쌍은 그대로지만, 중간 쌍은 여전히 범위를 넘어선다.
- NTK-by-parts (YaRN): (학습 중 돈 바퀴 수)로 , 는 에서 0, 에서 1인 ramp다(Llama에서 ). 한 바퀴도 못 돈 쌍은 보간하고, 32바퀴 이상 돈 쌍은 주파수를 유지한다. YaRN은 긴 거리에서 softmax가 평평해지는 것을 보정하려고 attention을 배 한다. Llama 3.1의
rope_type: llama3은 같은 생각을 파장으로 쓴 것이다(factor 8,low_freq_factor1,high_freq_factor4, original 8192). 즉 다. DeepSeek-V3는 4K에서 , 의 YaRN, gpt-oss는 4K에서 , Kimi K2의 config는beta_fast = beta_slow = 1로 한 바퀴에서 딱 끊는다.
- 회전하는 차원을 줄이거나 없앤다. partial RoPE는 head의 일부만 돌린다(Qwen3-Next: 256차원 중 64; MiniMax: 128 중 64; DeepSeek MLA: 별도의 64차원 key. 와 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를 유지했다.
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 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.
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 , i.e. for every pair. Slow pairs no longer extrapolate, but the fast pairs that encode “one token apart” are slowed , a loss of local resolution. NTK-by-parts interpolates only pairs whose wavelength exceeds the training length (), keeps pairs with , 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 and dilutes late layers; post-norm keeps the stream bounded but routes gradients through normalisations. Sandwich (Gemma), reordered (OLMo 2) and DeepNorm-style scaling (MiniMax-M1’s ) are compromises between the two.
- Attention logits are bounded only by . 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 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.
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인 유일한 방법이자 가장 빠른 쌍을 느리게 하는(토큰당 rad) 유일한 방법이다. YaRN과 Llama-3 스케일링은 빠른 쌍을 정확히 유지하면서 외삽 0을 얻는다. 미세조정이 필요 없는 NTK-aware는 64쌍 중 26쌍이 범위를 넘어선다.
모델을 Position Interpolation(s = 8)으로 8K에서 64K로 늘렸더니 정확한 국소 순서가 필요한 과제(코드 복사, 글자 세기)가 나빠졌다. 가장 그럴듯한 원인과 표준 처방은?
PI는 위치를 로, 즉 모든 쌍에서 로 보낸다. 느린 쌍은 더 외삽되지 않지만 “한 토큰 차이”를 부호화하는 빠른 쌍이 배 느려져 국소 해상도를 잃는다. NTK-by-parts는 파장이 학습 길이를 넘는 쌍()만 보간하고 인 쌍은 유지하며 그 사이를 섞는다. 상대 위치 성질은 고정된 어떤 주파수 집합에서도 성립한다.
정리
- pre-norm은 기울기의 항등 경로를 깨끗하게 지키지만 stream이 처럼 자라 뒤쪽 층이 희석된다. post-norm은 stream을 묶지만 기울기를 정규화 개에 통과시킨다. sandwich(Gemma), reordered(OLMo 2), DeepNorm식 배율(MiniMax-M1의 )은 그 사이의 타협이다.
- attention logit은 로만 묶인다. QK-norm은 그 의존성을 없애고, QK-clip은 MLA 때문에 QK-norm을 못 쓸 때 step 사이에 가중치를 재조정하고, soft-cap은 값을 묶지만 큰 logit 사이의 차이를 지우고, z-loss는 출력 softmax의 자유 shift 를 고정한다.
- 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
- Wortsman et al., Small-scale proxies for large-scale Transformer training instabilities (ICLR 2024) — attention logit 성장과 출력 logit 발산을 작은 모델에서 재현하고 qk-layernorm·z-loss로 고친다. 이 레슨의 출발점.Reproduces attention-logit growth and output-logit divergence in small models and fixes them with qk-layernorm and z-loss; this lesson's starting point.
- Gemma Team, Gemma 2 (2024) and Gemma 3 (2025) technical reports — Gemma 2의 logit soft-cap(attention 50, 최종 30)과, Gemma 3가 이를 QK-norm으로 바꾼 것.Gemma 2's logit soft-capping (attention 50, final 30), and Gemma 3 replacing it with QK-norm.
- OLMo Team, 2 OLMo 2 Furious (2025) — reordered norm + QK-norm + z-loss, 임베딩 weight decay 제거. 안정화 ablation이 자세하다.Reordered norm, QK-norm, z-loss and no weight decay on embeddings, with detailed stability ablations.
- Xie et al., mHC: Manifold-Constrained Hyper-Connections (2025); Zhu et al., Hyper-Connections (2024) — residual stream을 n배로 넓히는 HC와, 잔차 행렬을 Sinkhorn으로 doubly stochastic하게 만든 mHC.HC widens the residual stream n-fold; mHC makes the residual matrix doubly stochastic with Sinkhorn.
- Kimi Team, Attention Residuals (2026) — 깊이 방향 softmax attention으로 이전 층 출력을 골라 읽는 residual. PreNorm 희석 문제.A residual that reads earlier layer outputs with depth-wise softmax attention; the PreNorm dilution problem.
- Peng et al., YaRN: Efficient Context Window Extension of Large Language Models (ICLR 2024) — PI, NTK-aware, NTK-by-parts, attention temperature를 한 틀로 정리. 수식은 이 레슨이 그대로 쓴다.Puts PI, NTK-aware, NTK-by-parts and the attention temperature into one frame; this lesson uses its formulas.
- Kimi Team, Kimi K2: Open Agentic Intelligence (2025) — Muon에서 attention logit이 폭주하는 이유와 QK-Clip(τ = 100).Why attention logits explode under Muon, and QK-Clip (τ = 100).
- Qwen Team, On the Design of Qwen3.8-Next Architecture (2026) — Gated Residual, 그리고 NoPE가 사전학습에서는 같아 보이다 사후학습 뒤 끝없는 생성을 늘린 사례.The Gated Residual, and NoPE looking equal in pre-training but causing endless generation after post-training.