[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,89 +1,310 @@
|
||||
---
|
||||
id: wiki-2026-0508-catastrophic-forgetting
|
||||
title: Catastrophic Forgetting
|
||||
title: Catastrophic Forgetting & Continual Learning
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [CATAST-FORGET-001]
|
||||
aliases: [파괴적 망각, continual learning, lifelong learning, EWC, replay buffer, LoRA, mixture of experts]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, neural-networks, lifelong-learning, catastrophic-forgetting, Stability-plasticity]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [continual-learning, catastrophic-forgetting, ewc, replay, transfer-learning, lifelong-learning, lora, llm-finetune]
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: PyTorch / Avalanche / continual-learning libs
|
||||
---
|
||||
|
||||
# Catastrophic Forgetting (파괴적 망각)
|
||||
# Catastrophic Forgetting
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "새로운 지식을 배우려다 소중한 과거의 기억을 덮어쓰지 마라" — 인공 신경망이 새로운 태스크를 학습할 때, 이전에 학습했던 태스크에 필요한 가중치들이 급격히 수정되어 과거의 성능이 파괴적으로 저하되는 현상.
|
||||
## 📌 한 줄 통찰
|
||||
> **"매 new task 의 학습 의 매 old 의 destroy"**. 매 NN 의 weight 의 overwrite. 매 lifelong learning 의 fundamental challenge. 매 modern LLM era 의 highly relevant — 매 fine-tune 의 base capability 의 lose.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 학습 과정에서 가중치들이 현재의 데이터에만 최적화되면서, 과거의 데이터 분포 정보를 잃어버리는 정보 오버라이딩 패턴.
|
||||
- **주요 해결 기법 (Continual Learning):**
|
||||
- **[[Regularization|Regularization]]-based:** 과거 태스크에 중요했던 가중치가 변하지 않도록 페널티 부여 (예: EWC).
|
||||
- **Replay-based:** 과거의 데이터 일부를 저장해두었다가 새로운 학습 시 함께 사용.
|
||||
- **[[Architecture|Architecture]]-based:** 새로운 지식을 위해 신경망의 일부를 동적으로 확장하거나 분리.
|
||||
- **의의:** 인간처럼 평생에 걸쳐 지식을 축적하는 '지속 가능한 학습(Lifelong Learning)' 구현을 위한 가장 큰 난제 중 하나.
|
||||
## 📖 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 초기에는 데이터를 합쳐서 다시 학습시키는 것이 유일한 해결책이었으나, 현재는 가중치 동역학을 제어하여 지식을 보존하는 정교한 기법들이 연구됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 로컬 브레인 업데이트 시, 핵심 지식 노드의 가중치를 보호하는 규제화 기법을 적용하여 파괴적 망각을 최소화함.
|
||||
### 매 mechanism
|
||||
- 매 SGD 의 모든 weight 의 update.
|
||||
- 매 same weight 가 매 multiple task 의 store.
|
||||
- 매 new task 의 gradient 의 old 의 wipe.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Neural-Networks-Foundations, Transfer-Learning-Foundations, [[Regularization-Techniques|Regularization-Techniques]], [[Representation-Learning|Representation-Learning]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Catastrophic-Forgetting.md
|
||||
### 매 3 approach (Continual Learning)
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
#### 1. Regularization-based
|
||||
- **EWC** (Elastic Weight Consolidation): 매 past 의 important weight 의 protect.
|
||||
- **SI** (Synaptic Intelligence).
|
||||
- **LwF** (Learning without Forgetting): 매 distillation.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
#### 2. Replay-based
|
||||
- **Experience replay**: 매 old data 의 sample.
|
||||
- **Generative replay** (DGR): 매 generative model 의 old 의 reconstruct.
|
||||
- **Reservoir sampling**.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
#### 3. Architecture-based
|
||||
- **Progressive Networks**: 매 column 의 add.
|
||||
- **PackNet**: 매 weight 의 mask.
|
||||
- **Dynamic expansion**.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
#### 4. Modern (LLM)
|
||||
- **LoRA**: 매 base 의 frozen + 매 adapter 의 train.
|
||||
- **Adapter modules**.
|
||||
- **Mixture of Experts** (MoE).
|
||||
- **Soft prompt tuning**.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### 매 evaluation metric
|
||||
- **Average accuracy**: 매 모든 past task.
|
||||
- **Backward transfer (BWT)**: 매 old task 의 degradation.
|
||||
- **Forward transfer (FWT)**: 매 new task 의 boost.
|
||||
- **Forgetting rate**.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### 매 setting
|
||||
- **Class-incremental**: 매 new class.
|
||||
- **Task-incremental**: 매 distinct task.
|
||||
- **Domain-incremental**: 매 same task, 매 new domain.
|
||||
- **Online**: 매 stream.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### 매 modern LLM 의 응용
|
||||
1. **Fine-tune drift**: 매 helpful 의 acquire 가, 매 reasoning 의 lose.
|
||||
2. **Domain adapt**: 매 medical fine-tune 가, 매 general 의 weak.
|
||||
3. **RLHF**: 매 alignment tax.
|
||||
4. **Continual pretraining**: 매 new knowledge.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
→ 매 LoRA 의 popular reason: 매 base 의 keep.
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### 매 lib
|
||||
- **Avalanche** (PyTorch): 매 best.
|
||||
- **Continual-AI**: 매 community.
|
||||
- **Mammoth**.
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
### 매 biological 의 inspiration
|
||||
- 매 brain 의 hippocampus 의 fast learning + 매 neocortex 의 consolidation.
|
||||
- 매 sleep 의 replay 의 role (Bayesian brain).
|
||||
- 매 modular brain.
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
## 💻 패턴
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### EWC (Elastic Weight Consolidation)
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class EWC:
|
||||
def __init__(self, model, dataset, lambda_=1000):
|
||||
self.model = model
|
||||
self.lambda_ = lambda_
|
||||
self.params = {n: p for n, p in model.named_parameters() if p.requires_grad}
|
||||
self.fisher = self._compute_fisher(dataset)
|
||||
self.opt_params = {n: p.data.clone() for n, p in self.params.items()}
|
||||
|
||||
def _compute_fisher(self, dataset):
|
||||
fisher = {n: torch.zeros_like(p) for n, p in self.params.items()}
|
||||
self.model.eval()
|
||||
for x, y in dataset:
|
||||
self.model.zero_grad()
|
||||
output = self.model(x)
|
||||
loss = F.cross_entropy(output, y)
|
||||
loss.backward()
|
||||
for n, p in self.params.items():
|
||||
fisher[n] += p.grad.data.pow(2) / len(dataset)
|
||||
return fisher
|
||||
|
||||
def penalty(self):
|
||||
loss = 0
|
||||
for n, p in self.params.items():
|
||||
loss += (self.fisher[n] * (p - self.opt_params[n]).pow(2)).sum()
|
||||
return self.lambda_ * loss
|
||||
|
||||
# 매 train new task with EWC
|
||||
ewc = EWC(model, old_task_loader)
|
||||
for x, y in new_task_loader:
|
||||
loss = F.cross_entropy(model(x), y) + ewc.penalty()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Experience Replay
|
||||
```python
|
||||
class ReplayBuffer:
|
||||
def __init__(self, capacity=10000):
|
||||
self.buffer = []
|
||||
self.capacity = capacity
|
||||
|
||||
def add(self, data):
|
||||
if len(self.buffer) >= self.capacity:
|
||||
# 매 reservoir sampling
|
||||
idx = random.randint(0, len(self.buffer))
|
||||
if idx < self.capacity:
|
||||
self.buffer[idx] = data
|
||||
else:
|
||||
self.buffer.append(data)
|
||||
|
||||
def sample(self, n):
|
||||
return random.sample(self.buffer, min(n, len(self.buffer)))
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
replay = ReplayBuffer()
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# 매 train new task + 매 mix replay
|
||||
for x, y in new_task_loader:
|
||||
new_loss = F.cross_entropy(model(x), y)
|
||||
|
||||
if replay.buffer:
|
||||
replay_batch = replay.sample(BATCH_SIZE // 2)
|
||||
rx, ry = collate(replay_batch)
|
||||
replay_loss = F.cross_entropy(model(rx), ry)
|
||||
loss = new_loss + replay_loss
|
||||
else:
|
||||
loss = new_loss
|
||||
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
# 매 store new for future
|
||||
for x_i, y_i in zip(x, y):
|
||||
replay.add((x_i, y_i))
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### LoRA (modern, LLM-friendly)
|
||||
```python
|
||||
from peft import LoraConfig, get_peft_model
|
||||
from transformers import AutoModelForCausalLM
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
base = AutoModelForCausalLM.from_pretrained('meta-llama/Llama-3-8B')
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
# 매 task 1 의 LoRA
|
||||
lora_t1 = LoraConfig(r=16, lora_alpha=32, target_modules=['q_proj', 'v_proj'])
|
||||
model_t1 = get_peft_model(base, lora_t1)
|
||||
train(model_t1, task1_data)
|
||||
model_t1.save_pretrained('./lora-task1')
|
||||
|
||||
# 매 task 2 — 매 base 의 fresh + 매 다른 LoRA
|
||||
model_t2 = get_peft_model(base, LoraConfig(r=16, lora_alpha=32, target_modules=['q_proj', 'v_proj']))
|
||||
train(model_t2, task2_data)
|
||||
model_t2.save_pretrained('./lora-task2')
|
||||
|
||||
# 매 inference 시 의 swap
|
||||
def serve(prompt, task):
|
||||
base.load_adapter(f'./lora-{task}')
|
||||
return base.generate(prompt)
|
||||
```
|
||||
|
||||
→ 매 base 의 untouched — 매 forgetting X.
|
||||
|
||||
### Generative Replay
|
||||
```python
|
||||
def generative_replay(generator, classifier, new_task_loader):
|
||||
for x, y in new_task_loader:
|
||||
# 매 new task loss
|
||||
new_loss = F.cross_entropy(classifier(x), y)
|
||||
|
||||
# 매 old replay (generated)
|
||||
n_replay = x.size(0)
|
||||
replay_x = generator.sample(n_replay)
|
||||
replay_y = classifier_old(replay_x).argmax(-1) # 매 old 의 prediction 의 supervise
|
||||
replay_loss = F.cross_entropy(classifier(replay_x), replay_y)
|
||||
|
||||
loss = new_loss + 0.5 * replay_loss
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
### PackNet (architecture-based)
|
||||
```python
|
||||
class PackNet:
|
||||
"""매 weight 의 task 별 mask."""
|
||||
def __init__(self, model, prune_ratio=0.5):
|
||||
self.model = model
|
||||
self.task_masks = {} # 매 task → 매 mask
|
||||
|
||||
def train_task(self, task_id, loader):
|
||||
# 매 train normally
|
||||
train(self.model, loader)
|
||||
|
||||
# 매 prune low-magnitude weights
|
||||
for name, p in self.model.named_parameters():
|
||||
threshold = p.abs().quantile(self.prune_ratio)
|
||||
mask = p.abs() > threshold
|
||||
self.task_masks[(task_id, name)] = mask
|
||||
p.data *= mask # 매 freeze unmasked
|
||||
|
||||
def forward_task(self, task_id, x):
|
||||
# 매 use only task's mask
|
||||
with torch.no_grad():
|
||||
for name, p in self.model.named_parameters():
|
||||
p.data *= self.task_masks[(task_id, name)]
|
||||
return self.model(x)
|
||||
```
|
||||
|
||||
### Continual eval (Avalanche)
|
||||
```python
|
||||
from avalanche.benchmarks.classic import SplitMNIST
|
||||
from avalanche.training import EWC
|
||||
from avalanche.evaluation.metrics import accuracy_metrics, forgetting_metrics
|
||||
|
||||
scenario = SplitMNIST(n_experiences=5)
|
||||
model = MyModel()
|
||||
strategy = EWC(model, optimizer, criterion=F.cross_entropy, ewc_lambda=400)
|
||||
|
||||
for experience in scenario.train_stream:
|
||||
strategy.train(experience)
|
||||
results = strategy.eval(scenario.test_stream)
|
||||
print(f'Avg accuracy: {results["Top1_Acc_Stream/eval_phase/test_stream/Task000"]}')
|
||||
```
|
||||
|
||||
### LLM fine-tune drift detection
|
||||
```python
|
||||
def detect_drift(base_model, finetuned_model, eval_set):
|
||||
"""매 base capability 의 forgetting 의 measure."""
|
||||
base_scores = []
|
||||
ft_scores = []
|
||||
for example in eval_set:
|
||||
base_scores.append(score(base_model, example))
|
||||
ft_scores.append(score(finetuned_model, example))
|
||||
|
||||
drift = np.mean(base_scores) - np.mean(ft_scores)
|
||||
if drift > 0.05:
|
||||
log(f'Significant capability loss: {drift:.3f}')
|
||||
return drift
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| LLM fine-tune | LoRA / Adapter |
|
||||
| Class-incremental | EWC + Replay |
|
||||
| Streaming | Reservoir + Online EWC |
|
||||
| Few-shot | Prompt tuning |
|
||||
| Domain shift | Domain-adversarial |
|
||||
| Strong constraint | Architecture-based (PackNet) |
|
||||
| General | Replay (best) |
|
||||
|
||||
**기본값**: LoRA / Adapter for LLM. Replay + EWC for vision.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Continual-Learning]] · [[Transfer-Learning]]
|
||||
- 변형: [[EWC]] · [[Replay-Buffer]] · [[Generative-Replay]] · [[Progressive-Networks]] · [[PackNet]]
|
||||
- 응용: [[LoRA]] · [[Adapter]] · [[Mixture-of-Experts]] · [[Soft-Prompt-Tuning]]
|
||||
- Adjacent: [[Bayesian-Brain-Hypothesis]] · [[Biological-Intelligence]] · [[Bias-vs-Variance]] · [[Auto-Encoding]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 sequential task. 매 LLM domain adapt. 매 streaming data. 매 lifelong agent.
|
||||
**언제 X**: 매 single static dataset. 매 IID assumption.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Naive fine-tune**: 매 catastrophic forgetting.
|
||||
- **No EWC / replay**: 매 old task 의 lose.
|
||||
- **Replay buffer 의 unbounded**: 매 storage 폭발.
|
||||
- **No drift measurement**: 매 silent capability loss.
|
||||
- **Same LR for all task**: 매 some 의 dominate.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Kirkpatrick EWC 2017, Lopez-Paz GEM, Rebuffi iCaRL).
|
||||
- 신뢰도 A.
|
||||
- Related: [[LoRA]] · [[Mixture-of-Experts]] · [[Continual-Learning]] · [[Bayesian-Brain-Hypothesis]] · [[Biological-Intelligence]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — 3 approach + 매 EWC / replay / LoRA / PackNet code + LLM drift |
|
||||
|
||||
Reference in New Issue
Block a user