C.W.K.
Stream
Lesson 07 of 08 · published

Normalization (BatchNorm, LayerNorm, GroupNorm) 과 Pooling

~12 min · batchnorm, layernorm, groupnorm, pool

Level 0Tensor 호기심
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

Normalization 이 deep network 를 trainable 하게 만든 것

Normalization layer 가 activation 을 re-center 와 re-scale 해서 training 안정화. 세 흔한 variant — 그리고 교환 가능 X; 작업 shape 으로 골라:

  • BatchNorm2d — 각 channel 에 대해 batch 전체에 걸쳐 normalize. CNN 에 표준. stats 잘 estimate 위해 합리적으로 큰 batch (보통 16+) 필요. train() vs eval() 행동 switch: training 은 batch stats, eval 은 running mean / running var (buffer) 사용.
  • LayerNorm — feature dim 에 걸쳐 sample 별 normalize. Transformer 에 표준 — batch size 무관하고 inference 행동 안정.
  • GroupNorm — channel 을 group 으로 split 해서 각 group 안에서 normalize. batch size 어느 거나 (1 도) 작동. object detection (COCO, GPU 당 batch=2 흔함) 와 일부 vision Transformer 에 사용.

왜 BatchNorm 어디나 X?

BatchNorm 이 batch 안 sample 사이 정보 leak (각 sample 의 normalization 이 다른 것에 의존), 일부 setup (RNN step, multi-task, batch coupling 원치 않는 contrastive learning) 에 나쁨. 작은 batch 와 single sample 의 inference time 에도 fragile. LayerNorm 이 이 모든 거 회피 — Transformer 가 그걸로 settle 한 이유.

Pooling

MaxPool2d 가 각 window 의 max, AvgPool2d 가 평균. AdaptiveAvgPool2d(out_size) 가 modern hero — 요청된 output 생산하는 옳은 window size 알아냄. CNN backbone 끝에 AdaptiveAvgPool2d(1) 둬서 input image size 무관하게 single feature vector.

Code

BatchNorm2d — CNN 용·python
import torch
import torch.nn as nn

bn = nn.BatchNorm2d(64)             # normalizes per-channel across batch
x = torch.randn(32, 64, 16, 16)     # batch=32

bn.train()
out_train = bn(x)                    # uses batch stats
print(bn.running_mean.shape)         # torch.Size([64]) — buffer

bn.eval()
out_eval = bn(x)                     # uses running stats
LayerNorm — Transformer 용·python
import torch
import torch.nn as nn

# Normalize the LAST dim (features), per-sample
ln = nn.LayerNorm(512)
x = torch.randn(32, 16, 512)         # batch=32, seq=16, features=512
out = ln(x)
print(out.mean(dim=-1).abs().max())  # ~0  (zero mean per-sample-per-position)
print(out.std(dim=-1).mean())        # ~1
GroupNorm — 작은 batch, batch coupling 없음·python
import torch
import torch.nn as nn

# 64 channels split into 8 groups of 8 channels each
gn = nn.GroupNorm(num_groups=8, num_channels=64)
x = torch.randn(2, 64, 16, 16)       # batch=2 — too small for BatchNorm
out = gn(x)
print(out.shape)                      # torch.Size([2, 64, 16, 16])
Pooling — 그리고 AdaptiveAvgPool trick·python
import torch
import torch.nn as nn

x = torch.randn(8, 64, 32, 32)

mp = nn.MaxPool2d(2)                  # halves spatial
print(mp(x).shape)                     # torch.Size([8, 64, 16, 16])

ap = nn.AvgPool2d(4)
print(ap(x).shape)                     # torch.Size([8, 64, 8, 8])

# AdaptiveAvgPool — outputs a fixed spatial size regardless of input
gap = nn.AdaptiveAvgPool2d(1)
print(gap(x).shape)                    # torch.Size([8, 64, 1, 1])

# Same module on a different input size still produces 1x1
y = torch.randn(8, 64, 224, 224)
print(gap(y).shape)                    # torch.Size([8, 64, 1, 1])

External links

Exercise

같은 2-layer MLP 두 번 짓기: 하나는 layer 사이 LayerNorm, 하나는 없이. random data 에 100 step 둘 다 train. loss curve plot. LayerNorm 버전이 더 빠르고 부드럽게 수렴해야 — 모든 Transformer block 에 적어도 LayerNorm 하나 있는 이유.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.