Layer Normalization
Layer Normalization
Normalizes layer outputs. Used instead of Batch Norm in Transformers.
Layer Normalization
Normalizes layer outputs. Used instead of Batch Norm in Transformers.
Layer Normalization (LayerNorm) is a technique that normalizes along the feature dimension of each sample. Proposed by Ba et al. in 2016, it is a core component of the Transformer and is used in all modern language models, including GPT, BERT, and LLaMA.
Difference from Batch Normalization: BatchNorm normalizes along the batch dimension, so it depends on the batch size and requires running statistics at inference time. LayerNorm normalizes each sample independently, so it is independent of batch size and is well suited to NLP, where sequence length is variable.
Formula: y = (x - mean(x)) / sqrt(var(x) + eps) * gamma + beta. mean and var are computed along the hidden dimension. gamma (scale) and beta (shift) are learnable parameters, through which the model adjusts the degree of normalization.
Variants: Pre-LN (normalization before the layer, GPT-2+), Post-LN (normalization after the layer, the original Transformer), RMSNorm (faster because it removes the mean, LLaMA). Pre-LN has higher training stability and is the current standard.
import torch
import torch.nn as nn
# 1. PyTorch LayerNorm 사용
layer_norm = nn.LayerNorm(
normalized_shape=768, # hidden dimension
eps=1e-5, # 수치 안정성
elementwise_affine=True # gamma, beta 학습
)
x = torch.randn(32, 100, 768) # (batch, seq_len, hidden)
output = layer_norm(x) # 각 (batch, seq) 위치에서 768차원 정규화
# 2. LayerNorm 직접 구현 (이해용)
class ManualLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-5):
super().__init__()
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
self.eps = eps
def forward(self, x):
# x: (batch, seq, hidden)
mean = x.mean(dim=-1, keepdim=True) # hidden dim 평균
var = x.var(dim=-1, keepdim=True, unbiased=False)
x_norm = (x - mean) / torch.sqrt(var + self.eps)
return self.gamma * x_norm + self.beta
# 3. RMSNorm (LLaMA 스타일, 더 빠름)
class RMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.eps = eps
def forward(self, x):
# mean 계산 생략 -> 더 빠름
rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return x / rms * self.weight
# 4. Pre-LN vs Post-LN Transformer Block
class PreLNBlock(nn.Module):
"""GPT-2+ 스타일: 더 안정적인 학습"""
def __init__(self, hidden_size):
super().__init__()
self.ln1 = nn.LayerNorm(hidden_size)
self.attn = nn.MultiheadAttention(hidden_size, num_heads=8)
self.ln2 = nn.LayerNorm(hidden_size)
self.ffn = nn.Sequential(
nn.Linear(hidden_size, hidden_size * 4),
nn.GELU(),
nn.Linear(hidden_size * 4, hidden_size)
)
def forward(self, x):
# Pre-LN: LayerNorm을 먼저 적용
x = x + self.attn(self.ln1(x), self.ln1(x), self.ln1(x))[0]
x = x + self.ffn(self.ln2(x))
return x
"Training is unstable and we're analyzing the cause. It looks like the gradients are exploding in the deeper layers because of the Post-LN structure. Switching to Pre-LN and adding learning rate warmup should fix it."
"The difference between LayerNorm and BatchNorm is the normalization axis. BatchNorm normalizes along the batch dimension, and LayerNorm normalizes along the feature dimension. In NLP, sequence length is variable and batch size is small, so LayerNorm is the standard."
"The reason LLaMA uses RMSNorm is speed. Skipping the mean computation makes it about 15% faster, and there's almost no difference in performance. In large-scale models, this kind of optimization has a big impact on training cost."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
For images, statistics across channels are important, so BatchNorm is more effective. LayerNorm is optimized for NLP/Transformers.
When training in float16, eps=1e-12 causes numerical instability. Recommended: 1e-5 for float16 and 1e-6 for bfloat16.
Pre-LN structure is recommended for Transformers. For large models, optimize speed with RMSNorm. Make normalized_shape match the last dimension(s).