[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
+136 -39
View File
@@ -2,62 +2,159 @@
id: wiki-2026-0508-predictive-coding
title: Predictive Coding
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [PRED-CODING-001]
aliases: [Predictive Coding Networks, PCN, Hierarchical Predictive Coding]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [neuroscience, ai, predictive-Processing, bayesian-brain, cognitive-science]
confidence_score: 0.9
verification_status: applied
tags: [neuroscience, computational-neuroscience, free-energy, brain-models]
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 / JAX
---
# Predictive Coding (예측 부호화)
# Predictive Coding
## 📌 한 줄 통찰 (The Karpathy Summary)
> "뇌는 감각을 수동적으로 받아들이지 않고, 끊임없이 세상을 예측하고 수정한다" — 하위 계층에서 올라오는 감각 신호와 상위 계층의 예측 신호 간의 '오차(Error)'만을 전달하여 에너지 효율을 극대화하고 인지 정합성을 유지하는 뇌의 정보 처리 메커니즘.
## 한 줄
> **"매 brain = prediction machine — top-down predictions vs bottom-up errors 의 hierarchical loop"**. Rao & Ballard (1999) 의 visual cortex model 에서 시작, Friston 의 free-energy principle 로 generalized, 2020s 부터 backprop alternative 로 deep learning 에서 재조명. Each layer predicts activity below; only prediction errors propagate up.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 상위 모델이 생성한 예측과 실제 입력 사이의 잔차(Residual)를 최소화하는 방향으로 내부 모델을 업데이트하는 베이지안 뇌(Bayesian Brain) 가설 기반의 인지 패턴.
- **세부 내용:**
- **Top-down Predictions:** 뇌는 과거 경험을 바탕으로 다음에 들어올 감각 데이터(시각, 청각 등)를 미리 예측함.
- **Prediction Error:** 실제 입력이 예측과 다를 때만 해당 '오차 신호'가 상위 계층으로 전달되어 모델을 수정함.
- **[[Efficiency|Efficiency]]:** 예측이 정확할수록 처리해야 할 정보량이 줄어들어 뇌의 에너지 소모를 최소화함.
- **Perception as Inference:** 우리가 보고 느끼는 현실은 감각 데이터 자체라기보다, 뇌가 구성한 최선의 '예측 가설'에 가까움.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 뇌를 단순한 자극-반응 시스템으로 보던 관점에서, 능동적인 추론 엔진(Inference Engine)으로 바라보는 관점으로의 대전환.
- **정책 변화:** Antigravity 에이전트의 상황 인지 로직은 예측 부호화 원리를 차용하여, 예상된 정상 범위를 벗어나는 데이터(Anomalies)에 우선적으로 주의를 기울이도록 설계됨.
### 매 Rao-Ballard (1999)
- Hierarchical generative model: layer L predicts layer L-1 activity.
- Prediction error e_L = r_{L-1} - W_L * r_L.
- Errors drive higher representations; representations drive top-down predictions.
- Endstop neurons, surround suppression 매 emergent properties.
## 🔗 지식 연결 (Graph)
- Bayesian-Inference, Neuroscience, Active-Inference, [[Anomaly-Detection|Anomaly-Detection]]
- **Raw Source:** 10_Wiki/Topics/AI/Predictive-Coding.md
### 매 free-energy principle (Friston)
- Brain minimizes variational free energy = surprise upper bound.
- Active inference: action selection also minimizes expected free energy.
- Unifies perception, action, learning under one objective.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern PC neural networks
- **PCN as backprop alternative**: local Hebbian-like updates only.
- **Equilibrium propagation** (Scellier-Bengio): related fixed-point training.
- **Z-IL (Zero-divergence Inference Learning)**: PC equivalent to BP at convergence (Song 2020).
- 2024-2026 work: scaling PC to ImageNet, transformer-PC hybrids.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 advantages over backprop
1. Local plasticity (biologically plausible).
2. No need to store activations for backward pass.
3. Natural for online / continual learning.
4. Robust to weight transport problem.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Minimal PC layer (PyTorch)
```python
import torch, torch.nn as nn
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
class PCLayer(nn.Module):
def __init__(self, dim_below, dim_above):
super().__init__()
self.W = nn.Parameter(torch.randn(dim_above, dim_below) * 0.1)
self.r = None # state, set per batch
## 🧬 중복 검사 (Duplicate Check)
def init_state(self, batch_size, device):
self.r = torch.zeros(batch_size, self.W.shape[0], device=device, requires_grad=True)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def predict(self):
return self.r @ self.W # top-down prediction of layer below
## 🕓 변경 이력 (Changelog)
def error(self, below):
return below - self.predict()
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Inference loop (energy minimization)
```python
def pc_inference(layers, x, n_steps=20, lr_r=0.1):
# x: input at bottom
for L in layers: L.init_state(x.size(0), x.device)
activity = [x] + [L.r for L in layers]
for _ in range(n_steps):
# compute errors at each level
errors = []
for i, L in enumerate(layers):
errors.append(activity[i] - L.predict())
# update r via gradient descent on free energy
for i, L in enumerate(layers):
grad = -errors[i] @ L.W.T
if i + 1 < len(layers):
grad = grad + errors[i + 1]
L.r = (L.r - lr_r * grad).detach().requires_grad_(True)
activity[i + 1] = L.r
return errors
```
### Weight update (local Hebbian)
```python
def pc_weight_update(layers, errors, activity, lr_w=0.01):
with torch.no_grad():
for i, L in enumerate(layers):
# dW ∝ r_above^T * error_below
dW = L.r.T @ errors[i] / errors[i].size(0)
L.W += lr_w * dW
```
### Active inference (action selection)
```python
def select_action(model, state, candidate_actions):
"""Pick action minimizing expected free energy G = epistemic + pragmatic."""
G = []
for a in candidate_actions:
next_belief = model.transition(state, a)
ambiguity = model.entropy(next_belief)
risk = model.kl_to_preferred(next_belief)
G.append(ambiguity + risk)
return candidate_actions[torch.argmin(torch.tensor(G))]
```
### Z-IL (PC ≡ BP at convergence)
```python
# Song et al 2020: at the equilibrium of PC inference,
# weight updates equal those produced by BP.
# Critical detail: feedback weights = transpose of forward weights (tied).
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Biological plausibility required | Predictive coding |
| Energy efficiency on neuromorphic HW | PC / spiking PC |
| SOTA accuracy on ImageNet | Backprop CNN/ViT (still wins) |
| Continual learning | PC w/ uncertainty-weighted errors |
| Interpretation of cortical hierarchy | PC as theory |
**기본값**: BP for engineering; PC for neuroscience modeling 또는 neuromorphic deployment.
## 🔗 Graph
- 부모: [[Computational-Neuroscience]] · [[Free-Energy-Principle]]
- 변형: [[Active-Inference]] · [[Equilibrium-Propagation]]
- 응용: [[Cortical-Hierarchy]] · [[Bayesian-Brain]] · [[Neuromorphic-Computing]]
- Adjacent: [[Backpropagation]] · [[Variational-Inference]] · [[Helmholtz-Machine]]
## 🤖 LLM 활용
**언제**: brain-inspired model design, biologically-plausible learning, continual learning, neuromorphic chips.
**언제 X**: pure engineering goals — backprop is faster and more accurate.
## ❌ 안티패턴
- **PC as drop-in BP replacement**: still slower and less accurate at scale.
- **Confusing inference vs learning**: PC has nested loops (fast inference, slow weights).
- **Ignoring weight symmetry**: untied feedback breaks BP equivalence.
- **Free-energy hand-wave**: equation must be operationalized concretely.
## 🧪 검증 / 중복
- Verified (Rao & Ballard 1999 Nat Neurosci, Friston 2010, Song et al 2020 NeurIPS).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full PC theory + modern PC NN code |