[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+137 -39
View File
@@ -2,62 +2,160 @@
id: wiki-2026-0508-parameter-sharing
title: Parameter Sharing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DL-PARAM-SHARE-001]
aliases: [Weight Sharing, Tied Weights]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, Deep-Learning, Parameter-sharing, cnn, rnn, weight-tying, Efficiency]
confidence_score: 0.9
verification_status: applied
tags: [parameter-sharing, weight-tying, cnn, rnn, model-compression]
raw_sources: []
last_reinforced: 2026-04-26
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
---
# Parameter Sharing (파라미터 공유)
# Parameter Sharing
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 위치나 시점에 상관없이 동일한 '특징 추출기'를 반복 사용하여, 모델의 덩치는 줄이고 지능의 보편성은 높여라" — 신경망의 서로 다른 부분에서 동일한 가중치(Weight)를 공유함으로써 학습해야 할 파라미터 수를 획기적으로 줄이고 일반화 성능을 높이는 기법.
## 한 줄
> **"매 same weights, different positions"**. 매 single parameter set 가 multiple computations 에 reuse — translation invariance (CNN), temporal invariance (RNN), parameter efficiency (transformer FFN tied embeddings). 매 modern DL 의 fundamental design pattern.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Structural Symmetry and Translation Invariance" — 이미지는 어느 위치에서든 같은 필터로 특징을 뽑을 수 있고(CNN), 문장은 어느 시점에서든 같은 논리로 다음을 예측할 수 있다(RNN)는 구조적 가정을 바탕으로 가중치를 묶어버리는(Weight Tying) 패턴.
- **주요 적용 사례:**
- **CNN (Convolutional Neural Networks):** 하나의 필터(커널)가 이미지 전체를 훑으며 동일한 가중치로 연산. 공간적 불변성 확보.
- **RNN (Recurrent Neural Networks):** 매 시간 단계(Time step)마다 동일한 전이 행렬을 사용하여 시퀀스 데이터 처리.
- **Siamese Networks:** 두 개의 입력을 정확히 동일한 가중치를 가진 네트워크에 통과시켜 비교.
- **의의:** 과적합([[Overfitting|Overfitting]])을 방지하고 메모리 사용량을 절감하며, 데이터의 대칭성이나 반복되는 패턴을 포착하는 데 최적화된 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 모든 파라미터가 자유로워야 더 똑똑할 것이라는 초기 직관을 깨고, 오히려 파라미터를 강제적으로 공유했을 때 모델이 데이터의 핵심적인 불변 특징(Invariant features)을 더 잘 배운다는 사실이 딥러닝의 폭발적 성장을 이끌었음.
- **정책 변화:** Antigravity 프로젝트는 멀티모달 에이전트 설계 시, 서로 다른 입력(이미지, 텍스트)에서 공통된 의미 공간을 추출하기 위해 공유된 가중치 층을 활용하는 임베딩 아키텍처를 적용함.
### 매 motivation
- Parameter explosion: 매 fully connected layer on image → billions of params.
- Inductive bias: 매 weight sharing encodes prior (translation/time invariance).
- Generalization: 매 fewer params → better generalization (less overfit).
- Compute: 매 shared weights enable convolution / matmul optimization.
## 🔗 지식 연결 (Graph)
- [[Convolutional-Neural-Networks|Convolutional-Neural-Networks]]-CNN, [[Recurrent-Neural-Networks|Recurrent-Neural-Networks]]-RNN, [[Overfitting-and-Underfitting|Overfitting-and-Underfitting]], [[One-Shot-Learning|One-Shot-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/Parameter-Sharing.md
### 매 forms
- **Spatial sharing (CNN)**: 매 same conv kernel slid across image.
- **Temporal sharing (RNN/LSTM/GRU)**: 매 same recurrent weights at every timestep.
- **Cross-layer sharing**: 매 ALBERT, Universal Transformer — 매 same layer params reused L times.
- **Tied embeddings**: 매 input embedding == output projection (LM head).
- **Multi-head**: 매 NOT shared (each head has own W_q, W_k, W_v).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern usage
- ALBERT (2019): cross-layer sharing for BERT compression (12× param reduction).
- ViT: spatial sharing via patch embedding.
- Mamba/SSM: temporal sharing via state-space recurrence.
- LoRA: 매 single low-rank delta shared across positions.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. CNN image classification (ResNet, ConvNeXt).
2. Sequence modeling (RNN, Transformer position embeddings).
3. Model compression (ALBERT, distillation).
4. Multi-task learning (shared encoder).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### CNN spatial sharing
```python
import torch.nn as nn
# Single 3x3 kernel applied to every spatial position
conv = nn.Conv2d(3, 64, kernel_size=3, padding=1)
# Params: 3*64*3*3 + 64 = 1792 (independent of image size)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Tied input/output embeddings
```python
class LanguageModel(nn.Module):
def __init__(self, vocab_size, dim):
super().__init__()
self.embed = nn.Embedding(vocab_size, dim)
# tie: lm_head.weight = embed.weight
self.lm_head = nn.Linear(dim, vocab_size, bias=False)
self.lm_head.weight = self.embed.weight # share!
## 🧬 중복 검사 (Duplicate Check)
def forward(self, x):
h = self.embed(x)
return self.lm_head(h) # no extra params
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Cross-layer sharing (ALBERT-style)
```python
class SharedTransformer(nn.Module):
def __init__(self, num_layers, dim):
super().__init__()
self.shared_layer = TransformerBlock(dim) # ONE block
self.num_layers = num_layers
## 🕓 변경 이력 (Changelog)
def forward(self, x):
for _ in range(self.num_layers):
x = self.shared_layer(x) # reuse same params
return x
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### RNN temporal sharing (built-in)
```python
rnn = nn.GRU(input_size=128, hidden_size=256, num_layers=2)
# At every timestep t, same W_ih, W_hh applied
# Params independent of sequence length
```
### Detect shared params
```python
# Count unique parameter tensors
seen = set()
unique = 0
for p in model.parameters():
if id(p) not in seen:
seen.add(id(p))
unique += p.numel()
print(f"Unique params: {unique}")
```
### Multi-task shared encoder
```python
class MultiTaskModel(nn.Module):
def __init__(self):
super().__init__()
self.encoder = ResNet50() # SHARED
self.classifier = nn.Linear(2048, 1000)
self.detector = DetectionHead(2048)
def forward(self, x, task):
features = self.encoder(x)
return self.classifier(features) if task == "cls" else self.detector(features)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Image input | CNN spatial sharing |
| Sequence input | RNN or Transformer (positional sharing) |
| Memory constrained, many layers | Cross-layer sharing (ALBERT) |
| LM with large vocab | Tied embeddings (saves vocab*dim params) |
| Multi-task related | Shared encoder |
| Tasks unrelated | Don't force sharing — degrades quality |
**기본값**: tied embeddings + CNN spatial / Transformer positional sharing.
## 🔗 Graph
- 부모: [[Inductive-Bias]] · [[Model-Compression]]
- 변형: [[Weight-Tying]] · [[Cross-Layer-Sharing]] · [[Tied-Embeddings]]
- 응용: [[CNN]] · [[RNN]] · [[ALBERT]] · [[Transformer]]
- Adjacent: [[Convolution]] · [[Recurrence]] · [[Multi-Task-Learning]]
## 🤖 LLM 활용
**언제**: 매 designing efficient architecture, debugging param count, applying inductive bias.
**언제 X**: 매 tasks/positions truly independent (forcing sharing hurts quality).
## ❌ 안티패턴
- **Over-sharing**: 매 ALL layers shared → severe quality drop on complex tasks.
- **No tied embeddings on small LM**: 매 vocab=50k, dim=512 → 25M wasted params.
- **Sharing across modalities**: 매 vision encoder ≠ text encoder weights (use CLIP-style separate).
- **Forgetting LayerNorm not shared**: 매 cross-layer share W matrices but keep LN per-layer.
## 🧪 검증 / 중복
- Verified (LeCun 1989 CNN, ALBERT paper, Press & Wolf 2017 tied embeddings).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — sharing forms, modern usage, patterns |