In the first lesson we saw that depth helps expressiveness, and in the last one we built a way to compute gradients. Yet until around 2010, training a network deeper than 10 layers from scratch was close to impossible. The cause is simple. Both the forward and the backward pass are chains that multiply by a matrix once per layer, and a multiplicative chain vanishes or explodes exponentially if each link’s factor strays even slightly from 1. The tools in this lesson — initialisation, normalisation, residual connections — are all “ways to pin that factor near 1”.
The signal is multiplied at every layer
Write a layer as , . If the entries of are independent with mean 0 and variance , and independent of , then one component of is a sum of terms, so
Now write in terms of and the layer-to-layer factor appears.
- tanh (linear near 0): , so . The factor is , and setting it to 1 needs .
- ReLU: if is symmetric about 0, half of it is cut off, so . The factor is , and setting it to 1 needs . This is He initialisation.
After layers the signal’s variance is the factor to the -th power. A factor of 0.9 gives after 30 layers; 1.1 gives . In standard deviations, take the square root.
Backprop is exactly the same. , so the gradient’s variance is multiplied by (times the mean square of ) per layer. Preserving the forward pass needs ; preserving the backward pass needs . Glorot & Bengio (2010) proposed the compromise
(Xavier/Glorot initialisation). For a square layer it equals . He et al. (2015) did the same calculation for ReLU and got , one of the keys to training ReLU networks of 30+ layers from scratch.
The figure below runs this chain for real. It takes an MLP of width 64 and depth 30 right after initialisation, feeds 64 random inputs to plot the per-layer signal size (RMS), and feeds a random gradient at the output to plot the size of the backpropagated gradient. Each layer is (with residual, ).
첫 레슨에서 깊이가 표현력에 유리하다는 것을 봤고, 지난 레슨에서 기울기를 구하는 법을 만들었다. 그런데 2010년 무렵까지 10층 넘는 망을 처음부터 학습시키는 것은 거의 불가능에 가까웠다. 원인은 단순하다. 순전파도 역전파도 층마다 행렬을 한 번씩 곱하는 사슬이고, 곱셈 사슬은 매 고리의 배율이 1에서 조금만 벗어나도 지수적으로 사라지거나 터진다. 이 레슨의 도구들 — 초기화, 정규화, residual — 은 모두 “그 배율을 1 근처로 붙잡는 방법”이다.
신호는 층마다 곱해진다
한 층을 , 라고 하자. 의 원소가 평균 0, 분산 로 독립이고 와도 독립이면, 의 한 성분은 개 항의 합이므로
이다. 이제 를 로 쓰면 층 사이의 배율이 나온다.
- tanh (0 근처에서 선형): 이므로 . 배율은 이고, 1로 맞추려면 .
- ReLU: 가 0 대칭이면 절반이 잘리므로 . 배율은 이고, 1로 맞추려면 . 이것이 He 초기화다.
층을 지나면 신호의 분산은 배율의 제곱이 된다. 배율이 0.9면 30층 뒤 , 1.1이면 이다. 표준편차로 보면 그 제곱근이다.
역전파도 똑같다. 이므로 기울기의 분산은 층마다 (곱하기 의 제곱 평균)배가 된다. 순전파를 보존하려면 , 역전파를 보존하려면 이 필요하다. Glorot & Bengio(2010)는 둘의 절충으로
를 제안했다(Xavier/Glorot 초기화). 정사각 층에서는 과 같다. He et al.(2015)은 ReLU에 대해 같은 계산을 해서 을 얻었고, 이것이 30층 이상의 ReLU 망을 처음부터 학습시킨 열쇠 중 하나였다.
아래 그림은 이 사슬을 직접 돌린다. 폭 64, 깊이 30의 MLP를 초기화 직후 상태로 두고, 무작위 입력 64개를 넣어 층별 신호 크기(RMS)를, 출력 쪽에 무작위 기울기를 넣어 역전파된 기울기 크기를 그린다. 각 층은 (residual이면 )다.
Try the controls in this order.
- tanh + Xavier, scale 0.5×: blue and red both fall along straight lines (a straight line on a log axis = exponential decay). After 30 layers the signal is around .
- Scale 2×: the signal survives, but the distribution on the right piles up at ±1. tanh saturates and many units have . A large signal does not mean the network will train.
- ReLU + Xavier: the variance halves each layer, ending times smaller after 30 layers. Switch to He and it flattens out. Not perfectly, though: it wobbles up and down. With finite width the per-layer factor is not exactly 1 but fluctuates randomly, and its logarithm accumulates (press new seed to see).
- ReLU + He + residual: the variance doubles each layer, , and explodes. A residual connection does not by itself preserve the signal.
- Now turn on RMSNorm (pre-norm): the input of each branch is normalised to size 1, so what each branch adds is constant. The variance grows only linearly in the number of layers, and the RMS only as . The gradient (red) is nearly flat.
import numpy as np
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
ACT = {"tanh": np.tanh, "relu": lambda x: np.maximum(x, 0), "gelu": gelu}
def rmsnorm(h, eps=1e-5):
return h / np.sqrt((h**2).mean(axis=-1, keepdims=True) + eps)
def deep_forward(act="tanh", var=1.0, gain=1.0, residual=False, norm=False,
L=30, n=128, B=128, seed=0):
"""Feed standard-normal inputs to a width-n, depth-L MLP and return the per-layer activation RMS."""
rng = np.random.default_rng(seed)
h = rng.normal(size=(B, n))
rms = lambda v: np.sqrt((v**2).mean())
stds = [rms(h)]
for _ in range(L):
W = rng.normal(size=(n, n)) * gain * np.sqrt(var / n) # Var(W) = var/n
u = rmsnorm(h) if norm else h
z = ACT[act](u) @ W # activation → linear (branch ends in a linear layer, so mean 0)
h = h + z if residual else z
stds.append(rms(h))
return np.array(stds), h
show = [0, 1, 2, 5, 10, 20, 30]
print("layer " + "".join(f"{l:>9d}" for l in show))
configs = [
("tanh Xavier ×0.5", dict(act="tanh", var=1, gain=0.5)),
("tanh Xavier ×1 ", dict(act="tanh", var=1)),
("tanh Xavier ×2 ", dict(act="tanh", var=1, gain=2)),
("ReLU Xavier ", dict(act="relu", var=1)),
("ReLU He ", dict(act="relu", var=2)),
("ReLU He +res ", dict(act="relu", var=2, residual=True)),
("ReLU He +res+RMS", dict(act="relu", var=2, residual=True, norm=True)),
]
for name, cfg in configs:
s, h = deep_forward(**cfg)
print(f"{name}" + "".join(f"{s[l]:9.2e}" for l in show))
_, h = deep_forward(act="tanh", var=1, gain=2)
print(f"\ntanh ×2, last layer: fraction of units with |tanh(h)| > 0.9 = {np.mean(np.abs(np.tanh(h)) > 0.9):.0%} (saturated → tanh' ≈ 0)")Note also that tanh + Xavier ×1 slowly shrinks to 0.12 by layer 30. Away from 0, , so the factor is slightly below 1, and the gap accumulates. This is the phenomenon Glorot & Bengio actually observed.
You use He initialisation on a ReLU layer with fan-in 4096. Drawing weights from a normal distribution, what is the standard deviation?
He initialisation sets the variance to . The standard deviation is its square root, . PyTorch’s kaiming_normal_(w, nonlinearity="relu") uses this value. Confusing variance with standard deviation is a classic initialisation bug.
Normalisation layers: resetting the factor to 1 at every layer
Initialisation only fixes the factors at the start of training. As training proceeds the weights change and the factors drift. A normalisation layer measures the activations on every forward pass and sets their size directly. The difference between them is what they average over.
Let the activation tensor have shape (batch , features ).
| Axis for mean/variance | Formula (for a sample ) | Used in | |
|---|---|---|---|
| BatchNorm | batch axis (per feature) | CNNs | |
| LayerNorm | feature axis (per sample) | original Transformer, BERT, GPT-2 | |
| RMSNorm | feature axis, no mean subtraction | T5, the LLaMA family and most recent LLMs |
are a learned per-feature scale and shift. They let the network undo the normalisation if needed, so normalising takes no expressive power away.
BatchNorm uses minibatch statistics, so one sample’s output depends on the other samples in the same batch. Training (batch statistics) and inference (running-average statistics) therefore behave differently, and it is awkward to use with small batches, variable sequence lengths, or autoregressive models that generate one token at a time. LayerNorm normalises along the feature axis within a single sample, so it has none of these problems: training and inference are identical and independent of batch size.
RMSNorm removes the mean subtraction (re-centering) and from LayerNorm. Zhang & Sennrich (2019) argue that most of LayerNorm’s effect comes from re-scaling invariance: without mean subtraction, performance is nearly the same and computation drops — one pass for the mean square instead of two passes for mean and variance. At large scale this small saving and simplicity add up, and most recent LLMs, LLaMA included, use RMSNorm.
import numpy as np
rng = np.random.default_rng(0)
def layer_norm(x, gamma, beta, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True) # mean over the feature axis
var = ((x - mu) ** 2).mean(axis=-1, keepdims=True) # variance over the feature axis
return gamma * (x - mu) / np.sqrt(var + eps) + beta
def rms_norm(x, gamma, eps=1e-5):
rms = np.sqrt((x ** 2).mean(axis=-1, keepdims=True) + eps) # no mean subtraction
return gamma * x / rms
def batch_norm_train(x, gamma, beta, eps=1e-5):
mu = x.mean(axis=0, keepdims=True) # mean over the batch axis!
var = x.var(axis=0, keepdims=True)
return gamma * (x - mu) / np.sqrt(var + eps) + beta
B, d = 4, 8
x = rng.normal(loc=3.0, scale=2.0, size=(B, d))
g, b = np.ones(d), np.zeros(d)
y = layer_norm(x, g, b)
print("LN output: per-row mean", np.round(y.mean(-1), 6), " per-row std", np.round(y.std(-1), 4))
z = rms_norm(x, g)
print("RMS output: per-row RMS", np.round(np.sqrt((z**2).mean(-1)), 4), " per-row mean", np.round(z.mean(-1), 3))
# invariances: scale the whole input by a, or shift it by c
a, c = 5.0, 10.0
same = lambda u, v: np.allclose(u, v, atol=1e-4)
print("\ninvariant to scale x·a shift x+c")
print(f"LayerNorm {same(layer_norm(a*x, g, b), y)!s:10s} {same(layer_norm(x+c, g, b), y)}")
print(f"RMSNorm {same(rms_norm(a*x, g), z)!s:10s} {same(rms_norm(x+c, g), z)}")
# batch dependence: does changing other samples change sample 0's output?
x2 = x.copy(); x2[1:] = rng.normal(size=(B - 1, d))
print("\nDoes sample 0's output change when samples 1–3 change?")
print(" BatchNorm:", not np.allclose(batch_norm_train(x, g, b)[0], batch_norm_train(x2, g, b)[0]))
print(" LayerNorm:", not np.allclose(layer_norm(x, g, b)[0], layer_norm(x2, g, b)[0]))Scale invariance also leaves a mark on training dynamics. Replacing the weight right before a normalisation with leaves the output unchanged, so the gradient with respect to that is orthogonal to and shrinks by . In other words, the larger the weight norm, the smaller the effective learning rate. This is why weight decay, used together with normalisation layers, plays the role of “shrinking the norm to keep the effective learning rate up”.
Residual connections: a gradient highway
Even with each layer’s factor fixed by normalisation, a plain 56-layer network was worse than a 20-layer one already in training error (He et al., 2016, on CIFAR-10 — an optimisation problem, not overfitting). The fix was to have each layer add only a correction instead of rewriting its output wholesale.
Backpropagating,
The first term of the expanded product is the identity matrix. However small each branch’s Jacobian, the gradient of the output reaches every layer intact through . The multiplicative chain has gained an additive bypass. The remaining terms of the expansion correspond to “paths that go through some subset of branches”, and there are such paths. This is where the interpretation of a residual network as an ensemble of shallow networks comes from.
As step 4 of the figure showed, residual connections alone make the forward variance explode, because every branch adds variance. In practice there are two remedies.
- Normalise the branch input (pre-norm): . What each branch adds has a constant size, so the variance grows only linearly in .
- Shrink the branch output: initialise the branch’s last linear layer small. GPT-2 initialised the weights feeding into the residual path scaled by ( = number of residual layers). Taken to the extreme of zero, the whole network starts out as the identity function.
Pre-norm vs post-norm
The original Transformer (Vaswani et al., 2017) put normalisation after the residual addition (post-norm).
In post-norm the identity path goes through an LN at every layer, so it is not a “clean highway”. Xiong et al. (2020) showed that at initialisation post-LN has large gradients for the parameters near the output layer, so it tends to diverge without learning-rate warmup. Pre-LN had even gradients across layers and trained without warmup. In exchange, the residual stream in pre-norm keeps growing along the layers, so a final normalisation (final norm) is placed before the output head. Since GPT-2 most LLMs are pre-norm, and recent models use pre-norm RMSNorm as standard (we assemble the whole block two lessons from now).
→ Go deeper: Stability components follows where frontier models put the norm today (sandwich, reordered and DeepNorm placements, QK-norm, logit control, widened residual streams such as mHC).
Dropout
Finally, one tool from the regularisation side. Dropout zeroes each unit with probability during training and scales the survivors by (inverted dropout). The expectation is unchanged, so at inference nothing needs to be done. It stops units from depending on each other (co-adaptation), and since each step trains a different subnetwork, one interpretation is that it approximates an ensemble of exponentially many subnetworks.
Dropout helps most when data is scarce relative to the model. In large-scale LLM pre-training, where the data is seen roughly once, underfitting is the problem rather than overfitting, so dropout is often turned off. It matters again when fine-tuning on small data (LoRA’s dropout option is an example).
import torch
import torch.nn as nn
lin = nn.Linear(4096, 4096, bias=False)
nn.init.kaiming_normal_(lin.weight, mode="fan_in", nonlinearity="relu") # std = √(2/4096)
print(lin.weight.std().item()) # ≈ 0.0221
nn.init.xavier_normal_(lin.weight, gain=nn.init.calculate_gain("tanh")) # gain(tanh) = 5/3
class RMSNorm(nn.Module): # torch>=2.4 has nn.RMSNorm
def __init__(self, d, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d))
def forward(self, x):
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
return self.weight * (x * rms)
class PreNormBlock(nn.Module):
"""h ← h + W2 · relu(W1 · RMSNorm(h)), W2 initialised scaled down by 1/√(2L)"""
def __init__(self, d, n_layers):
super().__init__()
self.norm = RMSNorm(d)
self.fc1 = nn.Linear(d, 4 * d, bias=False)
self.fc2 = nn.Linear(4 * d, d, bias=False)
nn.init.kaiming_normal_(self.fc1.weight, nonlinearity="relu")
nn.init.normal_(self.fc2.weight, std=(1 / (4 * d)) ** 0.5 / (2 * n_layers) ** 0.5)
def forward(self, h):
return h + self.fc2(torch.relu(self.fc1(self.norm(h))))
L, d = 48, 256
net = nn.Sequential(*[PreNormBlock(d, L) for _ in range(L)])
x = torch.randn(64, d, requires_grad=True)
y = net(x)
y.pow(2).mean().backward()
print(f"input RMS {x.pow(2).mean().sqrt():.2f} → output RMS {y.pow(2).mean().sqrt():.2f}")
print(f"input gradient RMS {x.grad.pow(2).mean().sqrt():.2e}")At inference an autoregressive LLM generates tokens one at a time (batch size 1). Which normalisation behaves exactly as it did during training?
LayerNorm and RMSNorm look only at the feature axis of each token vector, so whatever else is in the batch, training and inference compute the same thing. BatchNorm uses batch statistics in training and stored running averages at inference, so the two differ, and at batch size 1 batch statistics are meaningless anyway.
Summary
- In both the forward and the backward pass a factor is multiplied in at every layer. If the factor is not 1, the signal vanishes or explodes exponentially with depth.
- Variance-preserving initialisation: for tanh/linear (Xavier: ), for ReLU (He).
- BatchNorm normalises over the batch axis, LayerNorm over the feature axis (mean and variance), RMSNorm over the feature axis (RMS only). LLMs use RMSNorm: batch-independent and cheap.
- Residual connections add an identity path to the product of Jacobians and preserve the gradient. Pre-norm and scaled-down branch outputs prevent the forward variance from exploding.
- Post-LN has unbalanced gradients at initialisation and needs warmup; Pre-LN is stable (but needs a final norm).
다음 순서로 조작해 보자.
- tanh + Xavier, 배율 0.5×: 파랑과 빨강이 모두 직선으로 떨어진다(로그 축에서 직선 = 지수 감소). 30층 뒤 신호가 수준이다.
- 배율 2×: 신호는 유지되지만 오른쪽 분포가 ±1에 몰린다. tanh가 포화되어 이 되는 유닛이 많아진다. 신호가 크다고 학습이 되는 것이 아니다.
- ReLU + Xavier: 층마다 분산이 절반이 되어 30층 뒤 배. He 로 바꾸면 평평해진다. 단, 완전히 평평하지는 않고 위아래로 흔들린다. 폭이 유한하면 층마다 배율이 정확히 1이 아니라 무작위로 흔들리고, 그 로그가 누적되기 때문이다(다른 난수를 눌러 보자).
- ReLU + He + residual: 분산이 층마다 로 두 배가 되어 폭발한다. residual은 그 자체로 신호를 보존하지 않는다.
- 여기에 RMSNorm을 켜면(pre-norm) 각 가지(branch)의 입력이 크기 1로 정규화되므로 가지가 더하는 양이 일정하다. 분산이 층 수에 선형으로, RMS는 로만 자란다. 기울기(빨강)는 거의 평평하다.
import numpy as np
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
ACT = {"tanh": np.tanh, "relu": lambda x: np.maximum(x, 0), "gelu": gelu}
def rmsnorm(h, eps=1e-5):
return h / np.sqrt((h**2).mean(axis=-1, keepdims=True) + eps)
def deep_forward(act="tanh", var=1.0, gain=1.0, residual=False, norm=False,
L=30, n=128, B=128, seed=0):
"""폭 n, 깊이 L MLP에 표준정규 입력을 넣고 층별 활성화 RMS를 반환."""
rng = np.random.default_rng(seed)
h = rng.normal(size=(B, n))
rms = lambda v: np.sqrt((v**2).mean())
stds = [rms(h)]
for _ in range(L):
W = rng.normal(size=(n, n)) * gain * np.sqrt(var / n) # Var(W) = var/n
u = rmsnorm(h) if norm else h
z = ACT[act](u) @ W # 활성화 → 선형 (가지의 끝이 선형이라 평균 0)
h = h + z if residual else z
stds.append(rms(h))
return np.array(stds), h
show = [0, 1, 2, 5, 10, 20, 30]
print("층 " + "".join(f"{l:>9d}" for l in show))
configs = [
("tanh Xavier ×0.5", dict(act="tanh", var=1, gain=0.5)),
("tanh Xavier ×1 ", dict(act="tanh", var=1)),
("tanh Xavier ×2 ", dict(act="tanh", var=1, gain=2)),
("ReLU Xavier ", dict(act="relu", var=1)),
("ReLU He ", dict(act="relu", var=2)),
("ReLU He +res ", dict(act="relu", var=2, residual=True)),
("ReLU He +res+RMS", dict(act="relu", var=2, residual=True, norm=True)),
]
for name, cfg in configs:
s, h = deep_forward(**cfg)
print(f"{name}" + "".join(f"{s[l]:9.2e}" for l in show))
_, h = deep_forward(act="tanh", var=1, gain=2)
print(f"\ntanh ×2 마지막 층: |tanh(h)| > 0.9 인 유닛 비율 = {np.mean(np.abs(np.tanh(h)) > 0.9):.0%} (포화 → tanh' ≈ 0)")tanh + Xavier ×1이 30층에서 0.12까지 느리게 줄어드는 것도 눈여겨보자. 는 0에서 멀어질수록 라서 배율이 1보다 약간 작고, 그 차이가 누적된다. Glorot & Bengio가 실제로 관찰한 현상이다.
fan-in이 4096인 ReLU 층에 He 초기화를 쓴다. 가중치를 정규분포에서 뽑을 때 표준편차는?
He 초기화는 분산이 이다. 표준편차는 그 제곱근 . PyTorch의 kaiming_normal_(w, nonlinearity="relu")가 이 값을 쓴다. 분산과 표준편차를 헷갈리는 것은 초기화 버그의 단골이다.
정규화 층: 배율을 매 층 다시 1로
초기화는 학습 시작 시점의 배율만 맞춘다. 학습이 진행되면 가중치가 바뀌고 배율도 흐트러진다. 정규화(normalization) 층은 매 순전파마다 활성화를 측정해 직접 크기를 맞춘다. 차이는 무엇에 대해 평균을 내는가 다.
활성화 텐서가 (배치 , 특징 ) 모양이라고 하자.
| 평균·분산을 내는 축 | 식 (샘플 기준) | 쓰이는 곳 | |
|---|---|---|---|
| BatchNorm | 배치 축 (특징별로) | CNN | |
| LayerNorm | 특징 축 (샘플별로) | 원조 Transformer, BERT, GPT-2 | |
| RMSNorm | 특징 축, 평균 빼지 않음 | T5, LLaMA 계열 대부분의 최신 LLM |
는 학습되는 특징별 배율과 이동이다. 정규화가 표현력을 빼앗지 않도록 필요하면 원래 크기로 되돌릴 수 있게 한다.
BatchNorm 은 미니배치의 통계를 쓰므로 한 샘플의 출력이 같은 배치의 다른 샘플에 의존한다. 그래서 학습(배치 통계)과 추론(이동평균 통계)이 다르게 동작하고, 배치가 작거나 시퀀스 길이가 제각각이거나 토큰을 하나씩 생성하는 자기회귀 모델에서는 쓰기 곤란하다. LayerNorm 은 샘플 하나 안에서 특징 축으로 정규화하므로 이 문제가 없다. 학습과 추론이 같고 배치 크기와 무관하다.
RMSNorm 은 LayerNorm에서 평균 빼기(re-centering)와 를 없앴다. Zhang & Sennrich(2019)의 주장은 LayerNorm의 효과는 대부분 크기 재조정 불변성(re-scaling invariance) 에서 오며, 평균 빼기는 없어도 성능이 거의 같고 계산이 줄어든다는 것이다. 평균과 분산을 두 번 훑는 대신 제곱 평균 한 번이면 된다. 대규모 모델에서는 이 작은 절약과 단순함이 쌓여, LLaMA를 비롯한 최신 LLM 대부분이 RMSNorm을 쓴다.
import numpy as np
rng = np.random.default_rng(0)
def layer_norm(x, gamma, beta, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True) # 특징 축 평균
var = ((x - mu) ** 2).mean(axis=-1, keepdims=True) # 특징 축 분산
return gamma * (x - mu) / np.sqrt(var + eps) + beta
def rms_norm(x, gamma, eps=1e-5):
rms = np.sqrt((x ** 2).mean(axis=-1, keepdims=True) + eps) # 평균을 빼지 않는다
return gamma * x / rms
def batch_norm_train(x, gamma, beta, eps=1e-5):
mu = x.mean(axis=0, keepdims=True) # 배치 축 평균!
var = x.var(axis=0, keepdims=True)
return gamma * (x - mu) / np.sqrt(var + eps) + beta
B, d = 4, 8
x = rng.normal(loc=3.0, scale=2.0, size=(B, d))
g, b = np.ones(d), np.zeros(d)
y = layer_norm(x, g, b)
print("LN 출력: 행별 평균", np.round(y.mean(-1), 6), " 행별 std", np.round(y.std(-1), 4))
z = rms_norm(x, g)
print("RMS 출력: 행별 RMS", np.round(np.sqrt((z**2).mean(-1)), 4), " 행별 평균", np.round(z.mean(-1), 3))
# 불변성: 입력 전체를 a배, 혹은 c만큼 이동
a, c = 5.0, 10.0
same = lambda u, v: np.allclose(u, v, atol=1e-4)
print("\n불변성 스케일 x·a 이동 x+c")
print(f"LayerNorm {same(layer_norm(a*x, g, b), y)!s:10s} {same(layer_norm(x+c, g, b), y)}")
print(f"RMSNorm {same(rms_norm(a*x, g), z)!s:10s} {same(rms_norm(x+c, g), z)}")
# 배치 의존성: 다른 샘플을 바꾸면 샘플 0의 출력이 바뀌는가?
x2 = x.copy(); x2[1:] = rng.normal(size=(B - 1, d))
print("\n샘플 1~3을 바꿨을 때 샘플 0 출력이 변하나?")
print(" BatchNorm:", not np.allclose(batch_norm_train(x, g, b)[0], batch_norm_train(x2, g, b)[0]))
print(" LayerNorm:", not np.allclose(layer_norm(x, g, b)[0], layer_norm(x2, g, b)[0]))크기 불변성은 학습 동역학에도 흔적을 남긴다. 정규화 바로 앞의 가중치 를 로 바꿔도 출력이 같으므로, 그 에 대한 기울기는 와 직교하고 크기는 로 준다. 즉 가중치 노름이 커질수록 실효 학습률이 작아진다. weight decay가 정규화 층과 함께 쓰일 때 “노름을 줄여 실효 학습률을 유지하는” 역할을 하는 이유다.
Residual: 기울기의 고속도로
정규화로 각 층의 배율을 맞춰도, 평범한(plain) 56층 망은 20층 망보다 학습 오차부터 더 나빴다(He et al., 2016의 CIFAR-10 관찰. 과적합이 아니라 최적화 문제다). 해법은 각 층이 출력을 통째로 다시 쓰는 대신 수정분만 더하게 하는 것이었다.
역전파하면
곱을 전개한 첫 항이 항등행렬 이다. 각 가지의 야코비안이 아무리 작아도, 출력의 기울기가 를 통해 모든 층에 그대로 전달된다. 곱셈 사슬에 덧셈 우회로가 생긴 것이다. 전개의 나머지 항들은 “몇 개의 가지를 거치는 경로”에 해당하고, 경로 수는 개다. residual 망을 얕은 망들의 앙상블처럼 볼 수 있다는 해석이 여기서 나온다.
그림의 4번에서 봤듯이 residual만으로는 순전파 분산이 폭발한다. 가지마다 분산을 더하기 때문이다. 실전의 처방은 두 가지다.
- 가지 입력 정규화 (pre-norm): . 가지가 더하는 크기가 일정해져 분산이 에 선형으로만 자란다.
- 가지 출력 축소: 가지의 마지막 선형층을 작게 초기화한다. GPT-2는 residual 경로로 들어가는 가중치를 배( = residual 층 수)로 초기화했다. 극단적으로 0으로 두면 초기에는 망 전체가 항등함수에서 출발한다.
Pre-norm vs Post-norm
원조 Transformer(Vaswani et al., 2017)는 정규화를 residual 덧셈 뒤 에 뒀다(post-norm).
post-norm에서는 항등 경로가 매 층 LN을 통과하므로 “깨끗한 고속도로”가 아니다. Xiong et al.(2020)은 초기화 시점에 post-LN의 출력층 근처 매개변수 기울기가 크다는 것을 보였고, 그래서 학습률 warmup 없이는 발산하기 쉽다. pre-LN은 기울기가 층에 걸쳐 고르고 warmup 없이도 학습되었다. 대신 pre-norm에서는 residual stream의 크기가 층을 따라 계속 자라므로, 출력 헤드 앞에 마지막 정규화(final norm)를 하나 둔다. GPT-2 이후 대부분의 LLM이 pre-norm이고, 최근 모델은 pre-norm RMSNorm이 표준이다(다음다음 레슨에서 블록 전체를 조립한다).
→ 더 깊이: 안정화 부품에서 오늘날 프론티어 모델이 norm을 어디에 두는지(sandwich·reordered·DeepNorm 배치, QK-norm, logit 통제, mHC 같은 residual stream 넓히기)를 따라간다.
Dropout
마지막으로 정규화(regularization) 쪽 도구 하나. Dropout 은 학습 중 각 유닛을 확률 로 0으로 만들고, 살아남은 유닛을 배 한다(inverted dropout). 기댓값이 그대로이므로 추론 때는 아무것도 하지 않으면 된다. 유닛들이 서로에게 의존해 공모(co-adaptation)하는 것을 막고, 매 step 다른 부분망을 학습하므로 지수적으로 많은 부분망의 앙상블을 근사한다는 해석이 있다.
dropout은 데이터가 모델에 비해 적을 때 효과가 크다. 데이터를 거의 한 번만 보는 대규모 LLM 사전학습에서는 과적합보다 과소적합이 문제여서 dropout을 끄는 경우가 많다. 작은 데이터로 미세조정할 때는 다시 의미가 생긴다(LoRA의 dropout 옵션이 그 예다).
import torch
import torch.nn as nn
lin = nn.Linear(4096, 4096, bias=False)
nn.init.kaiming_normal_(lin.weight, mode="fan_in", nonlinearity="relu") # std = √(2/4096)
print(lin.weight.std().item()) # ≈ 0.0221
nn.init.xavier_normal_(lin.weight, gain=nn.init.calculate_gain("tanh")) # gain(tanh) = 5/3
class RMSNorm(nn.Module): # torch>=2.4 에는 nn.RMSNorm 이 있다
def __init__(self, d, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d))
def forward(self, x):
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
return self.weight * (x * rms)
class PreNormBlock(nn.Module):
"""h ← h + W2 · relu(W1 · RMSNorm(h)), W2는 1/√(2L)로 축소 초기화"""
def __init__(self, d, n_layers):
super().__init__()
self.norm = RMSNorm(d)
self.fc1 = nn.Linear(d, 4 * d, bias=False)
self.fc2 = nn.Linear(4 * d, d, bias=False)
nn.init.kaiming_normal_(self.fc1.weight, nonlinearity="relu")
nn.init.normal_(self.fc2.weight, std=(1 / (4 * d)) ** 0.5 / (2 * n_layers) ** 0.5)
def forward(self, h):
return h + self.fc2(torch.relu(self.fc1(self.norm(h))))
L, d = 48, 256
net = nn.Sequential(*[PreNormBlock(d, L) for _ in range(L)])
x = torch.randn(64, d, requires_grad=True)
y = net(x)
y.pow(2).mean().backward()
print(f"입력 RMS {x.pow(2).mean().sqrt():.2f} → 출력 RMS {y.pow(2).mean().sqrt():.2f}")
print(f"입력 기울기 RMS {x.grad.pow(2).mean().sqrt():.2e}")자기회귀 LLM 추론에서 토큰을 하나씩 생성한다(배치 크기 1). 학습 때와 똑같이 동작하는 정규화는?
LayerNorm과 RMSNorm은 각 토큰 벡터의 특징 축만 보므로, 배치에 누가 있든 학습과 추론의 계산이 같다. BatchNorm은 학습 때 배치 통계를, 추론 때 저장된 이동평균을 쓰므로 둘이 다르고, 배치 크기 1에서는 배치 통계 자체가 의미가 없다.
정리
- 순전파·역전파 모두 층마다 배율이 곱해진다. 배율이 1이 아니면 깊이에 지수적으로 소실·폭발한다.
- 분산 보존 초기화: tanh/선형은 (Xavier: ), ReLU는 (He).
- BatchNorm은 배치 축, LayerNorm은 특징 축(평균·분산), RMSNorm은 특징 축(RMS만). LLM은 배치 독립적이고 싼 RMSNorm을 쓴다.
- Residual은 야코비안 곱에 항등 경로를 더해 기울기를 보존한다. 순전파 분산 폭발은 pre-norm과 가지 출력 축소로 막는다.
- Post-LN은 초기 기울기가 불균형해 warmup이 필요하고, Pre-LN은 안정적이다(대신 final norm 필요).
더 읽을거리Further reading
- Glorot & Bengio, Understanding the Difficulty of Training Deep Feedforward Neural Networks (AISTATS, 2010) — 층별 활성화·기울기 분산을 측정하고 Xavier 초기화를 유도한 논문Measures per-layer activation and gradient variances and derives Xavier initialisation
- He, Zhang, Ren, Sun, Delving Deep into Rectifiers (ICCV, 2015) — ReLU에 맞춘 분산 보존 초기화(He/Kaiming init) 유도Derives the variance-preserving initialisation for ReLU (He/Kaiming init)
- Ioffe & Szegedy, Batch Normalization (ICML, 2015) — 배치 통계로 정규화하는 BatchNormBatchNorm, which normalises with batch statistics
- Ba, Kiros, Hinton, Layer Normalization (2016) — 샘플 하나의 특징 축으로 정규화. RNN·Transformer의 표준이 됨Normalises along the feature axis of a single sample; became the standard for RNNs and Transformers
- Zhang & Sennrich, Root Mean Square Layer Normalization (NeurIPS, 2019) — 평균 빼기를 없앤 RMSNorm. 재척도 불변성만으로 충분하다는 주장RMSNorm, which drops the mean subtraction; argues that re-scaling invariance alone is enough
- He, Zhang, Ren, Sun, Deep Residual Learning for Image Recognition (CVPR, 2016) — residual 연결로 100층 이상을 학습한 ResNetResNet, which trained more than 100 layers with residual connections
- Xiong et al., On Layer Normalization in the Transformer Architecture (ICML, 2020) — post-LN과 pre-LN의 초기 기울기 분석, pre-LN은 warmup 없이도 학습됨Analyses gradients at initialisation for post-LN vs pre-LN; pre-LN trains even without warmup
- Srivastava et al., Dropout: A Simple Way to Prevent Neural Networks from Overfitting (JMLR, 2014) — dropout의 원 논문The original dropout paper