[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,66 +2,157 @@
|
||||
id: wiki-2026-0508-pooling
|
||||
title: Pooling
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-POOL-001]
|
||||
aliases: [Max Pooling, Average Pooling, Global Pooling]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [auto-reinforced, pooling, cnn, Computer-Vision, Deep-Learning, dimension-reduction]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [deep-learning, cnn, pooling, downsampling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: pytorch
|
||||
---
|
||||
|
||||
# [[Pooling|Pooling]]
|
||||
# Pooling
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "지적 요약의 힘: 이미지의 미세한 픽셀 정보를 다 가지고 있지 않아도, 핵심적인 특징(예: 코너나 엣지)만 골라내어 크기를 확 줄임으로써, 인공 신경망이 정보 과부하에 빠지지 않고 중요한 것에만 집중하게 만드는 다이어트 기법."
|
||||
## 매 한 줄
|
||||
> **"매 spatial/sequence dimension downsample — invariance + receptive field 확대."**. CNN 시대의 staple (max/avg pool), 매 modern Transformer는 거의 안 씀 (strided conv 또는 attention pooling). Global pool은 여전히 classification head 표준.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
풀링(Pooling)은 합성곱 신경망(CNN)에서 특성 지도의 해상도를 낮춰 연산량을 줄이고 중요한 특징을 강조하는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **대표적 기법**:
|
||||
* **Max Pooling**: 해당 영역에서 가장 큰 값(가장 두드러진 특징)만 남김. (가장 널리 쓰임)
|
||||
* **Average Pooling**: 영역의 평균값을 취함 (부드러운 요약).
|
||||
2. **이점**:
|
||||
* **Invariance**: 사물이 이미지 안에서 살짝 옆으로 이동해도 동일하게 인식하는 강인함 제공.
|
||||
* **Computational [[Efficiency|Efficiency]]**: 데이터 크기를 줄여 연산 속도 향상. (Efficiency와 연결)
|
||||
* **[[Overfitting|Overfitting]] Reduction**: 세세한 부분([[Noise|Noise]])을 뭉개버려 과적합 방지. (Overfitting와 연결)
|
||||
### 매 종류
|
||||
- **Max Pooling**: window 내 max — translation invariance, edge-preserve.
|
||||
- **Average Pooling**: window 평균 — smooth, all-pixel contribute.
|
||||
- **Global Average Pooling (GAP)**: 매 entire feature map → 단일 값. ResNet/EfficientNet head.
|
||||
- **Adaptive Pooling**: output size fix → input size 무관 (PyTorch `AdaptiveAvgPool2d`).
|
||||
- **Attention Pooling**: weighted sum, learned weights — ViT [CLS] 또는 perceiver.
|
||||
- **L_p Pooling, Stochastic Pooling, Mixed Pooling**: less common, occasionally robust.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 무조건 데이터 크기를 줄이는 정책이 효율적이라 믿었으나, 현대 정책은 정보 보존 정책을 중시하여 풀링 대신 보폭(Stride)을 넓린 합성곱(Strided Convolution) 정책을 사용해 정보 손실을 최소화하기도 함(RL Update).
|
||||
- **정책 변화(RL Update)**: 최근의 트랜스포머 기반 비전 모델(ViT) 정책에서는 풀링 대신 '패치 임베딩' 정책이나 'Layer Norm' 정책 등을 활용해 전역적인 맥락을 더 정교하게 파악하는 방향으로 진화 중임.
|
||||
### 매 왜 사용
|
||||
- **Downsampling**: spatial size 줄여 compute / params 감소.
|
||||
- **Invariance**: small translation에 robust.
|
||||
- **Receptive field 확대**: deeper layer가 wider context 봄.
|
||||
- **Overfitting 방지**: parameter-free regularization 효과.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Computer Vision|Computer Vision]], Deep Learning (DL), [[Efficiency|Efficiency]], [[Overfitting|Overfitting]], [[Noise|Noise]]
|
||||
- **Modern Tech/Tools**: CNN, Global Average Pooling (GAP), Pytorch (nn.MaxPool2d).
|
||||
---
|
||||
### 매 modern shift
|
||||
- 2020+ Transformer 시대 — 매 pool 자리에 strided conv (stage transition) 또는 patch merging (Swin) 또는 attention pooling.
|
||||
- ConvNeXt도 strided conv 사용.
|
||||
- GAP은 classification head에서 여전히 universal.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Max / Avg pool 기본
|
||||
```python
|
||||
import torch.nn as nn
|
||||
maxp = nn.MaxPool2d(kernel_size=2, stride=2) # H,W /2
|
||||
avgp = nn.AvgPool2d(kernel_size=2, stride=2)
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Global Average Pooling (classification head)
|
||||
```python
|
||||
import torch.nn as nn
|
||||
class Head(nn.Module):
|
||||
def __init__(self, c, n_cls):
|
||||
super().__init__()
|
||||
self.gap = nn.AdaptiveAvgPool2d(1)
|
||||
self.fc = nn.Linear(c, n_cls)
|
||||
def forward(self, x): # x: (B, C, H, W)
|
||||
x = self.gap(x).flatten(1) # (B, C)
|
||||
return self.fc(x)
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Adaptive pool (variable input size)
|
||||
```python
|
||||
import torch, torch.nn as nn
|
||||
pool = nn.AdaptiveAvgPool2d((7, 7)) # 항상 7x7 output
|
||||
x = torch.randn(2, 64, 33, 41) # 임의 spatial
|
||||
y = pool(x) # (2, 64, 7, 7)
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### Attention Pooling (ViT [CLS])
|
||||
```python
|
||||
import torch, torch.nn as nn
|
||||
class AttnPool(nn.Module):
|
||||
def __init__(self, d, heads=8):
|
||||
super().__init__()
|
||||
self.q = nn.Parameter(torch.randn(1, 1, d))
|
||||
self.attn = nn.MultiheadAttention(d, heads, batch_first=True)
|
||||
def forward(self, x): # x: (B, N, D)
|
||||
B = x.size(0)
|
||||
q = self.q.expand(B, -1, -1)
|
||||
out, _ = self.attn(q, x, x)
|
||||
return out.squeeze(1) # (B, D)
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### Patch Merging (Swin Transformer)
|
||||
```python
|
||||
import torch, torch.nn as nn
|
||||
class PatchMerging(nn.Module):
|
||||
def __init__(self, dim):
|
||||
super().__init__()
|
||||
self.norm = nn.LayerNorm(4*dim)
|
||||
self.reduction = nn.Linear(4*dim, 2*dim, bias=False)
|
||||
def forward(self, x): # x: (B, H, W, C)
|
||||
x0 = x[:, 0::2, 0::2, :]; x1 = x[:, 1::2, 0::2, :]
|
||||
x2 = x[:, 0::2, 1::2, :]; x3 = x[:, 1::2, 1::2, :]
|
||||
x = torch.cat([x0,x1,x2,x3], -1)
|
||||
return self.reduction(self.norm(x))
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### 1D pool (sequence / audio)
|
||||
```python
|
||||
import torch.nn as nn
|
||||
pool1d = nn.MaxPool1d(kernel_size=4, stride=4) # (B, C, T) -> (B, C, T/4)
|
||||
gap1d = nn.AdaptiveAvgPool1d(1)
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Set/Graph pooling (mean/max/sum)
|
||||
```python
|
||||
import torch
|
||||
def set_mean(x, mask): # x:(B,N,D), mask:(B,N)
|
||||
m = mask.unsqueeze(-1).float()
|
||||
return (x*m).sum(1) / m.sum(1).clamp(min=1)
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Classification final feature | Global Avg Pooling |
|
||||
| Variable input image | AdaptiveAvgPool2d |
|
||||
| Edge-preserve detection | Max Pool 또는 strided conv |
|
||||
| Transformer stage transition | Patch merging / strided conv |
|
||||
| Set/sequence aggregation | Attention pool |
|
||||
| Audio waveform | 1D max/avg pool 또는 strided conv |
|
||||
|
||||
**기본값**: feature map → GAP, downsample → strided conv (modern).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Convolutional_Neural_Network]] · [[Deep_Learning]]
|
||||
- 변형: [[Max_Pooling]] · [[Average_Pooling]] · [[Attention_Pooling]]
|
||||
- 응용: [[Image_Classification]] · [[ResNet]] · [[ViT]]
|
||||
- Adjacent: [[Strided_Convolution]] · [[Patch_Merging]] · [[Receptive_Field]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: CNN backbone에서 spatial reduce, classification head GAP, set/graph aggregation.
|
||||
**언제 X**: dense prediction (segmentation, detection)에서 매 정보 손실 — skip connection 결합 또는 dilated conv 고려.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Pool then upsample for segmentation without skip**: 매 detail 손실. U-Net skip 사용.
|
||||
- **MaxPool everywhere in modern arch**: 매 strided conv가 매 학습 가능 — 거의 dominant.
|
||||
- **Flatten without GAP**: classification head fully-connected로 들어가면 매 huge params + overfit.
|
||||
- **Pool over tokens with [CLS] available**: attention pool 또는 [CLS] readout 매 better.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (PyTorch docs nn.MaxPool2d, AdaptiveAvgPool, Swin Transformer paper, ConvNeXt paper).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — pooling types + modern shift to strided conv / attention pool |
|
||||
|
||||
Reference in New Issue
Block a user