[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,92 +1,283 @@
|
||||
---
|
||||
id: wiki-2026-0508-credit-assignment-problem
|
||||
id: wiki-2026-0508-credit-assignment
|
||||
title: Credit Assignment Problem
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-CRAS-001]
|
||||
aliases: [credit assignment, temporal credit, structural credit, backpropagation, GAE, PRM, attribution]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.94
|
||||
tags: [auto-reinforced, credit-assignment, Reinforcement-Learning, machine-learning, Backpropagation, reward]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [reinforcement-learning, credit-assignment, backpropagation, gae, prm, attribution, multi-agent, llm]
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: PyTorch / JAX / RL libs
|
||||
---
|
||||
|
||||
# [[Credit Assignment Problem|Credit Assignment Problem]]
|
||||
# Credit Assignment Problem
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "누가 상을 받을 자격이 있는가?: 복잡한 연속적 행동 끝에 결과가 나왔을 때, 그 성공(또는 실패)에 기여한 결정적인 '과거의 행동'이나 '신경망의 가중치'를 정확히 찾아내어 공로를 인정해 주는 학습의 핵심 난제."
|
||||
## 매 한 줄
|
||||
> **"매 누가 / 매 무엇 의 reward 의 기여?"**. 매 long sequence 의 final reward 의 매 step 별 attribution. 매 RL 의 fundamental + 매 deep learning 의 backprop 의 essence. 매 modern: GAE, PRM, RLHF, multi-agent.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
신용 할당 문제(Credit Assignment Problem)는 최종 결과에 도달하기까지의 수많은 과정 중 어떤 부분이 얼마나 기여했는지 판별하는 문제입니다.
|
||||
## 매 핵심 type
|
||||
|
||||
1. **두 가지 유형**:
|
||||
* **Temporal Credit Assignment**: 긴 시간 동안 여러 행동을 한 뒤 보상을 받았을 때, "어떤 시점의 행동" 덕분인지 알아내는 것 (예: 장기전 게임인 바둑의 수). (Reinforcement Learning과 연결)
|
||||
* **Structural Credit Assignment**: 다층 신경망에서 에러가 발생했을 때, "어떤 층의 어떤 노드"를 수정해야 하는지 찾아내는 것. (Backpropagation과 연결)
|
||||
2. **해결 방법**:
|
||||
* **Backpropagation**: 에러를 뒤로 전파하며 기여도(Gradient)를 계산.
|
||||
* **Eligibility Traces / Reward Shaping**: 강화학습에서 과거의 행동에 대한 기억을 남겨 보상을 분배.
|
||||
### Temporal Credit Assignment
|
||||
- 매 sequence of action → 매 final reward.
|
||||
- 매 어떤 action 의 결정?
|
||||
- 매 RL 의 challenge.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 보상이 주어지는 시점의 행동에만 집중하는 정책이 많았으나, 현대 정책은 미래의 기대 가치(Value Function)를 끌어다 쓰는 '벨만 방정식 정책'과 '과정 보상 모델(PRM) 정책'을 통해 정교하게 신용을 할당함(RL Update).
|
||||
- **정책 변화(RL Update)**: 복잡한 AI 에이전트 워크플로우 정책에서, 최종 결과물만 평가하는 것이 아니라 각 중간 단계 에이전트의 기여도를 공정하게 평가하고 보상하는 '에이전시 기반 신용 할당 정책'이 시스템 설계의 핵심이 됨.
|
||||
### Structural Credit Assignment
|
||||
- 매 layered NN → 매 error.
|
||||
- 매 어떤 weight / neuron 의 fix?
|
||||
- 매 backprop 의 solve.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Reinforcement Learning (RL)|Reinforcement Learning (RL)]], [[Backpropagation|Backpropagation]], [[Reward Prediction Error|Reward Prediction Error]], [[Optimization|Optimization]], [[Analysis|Analysis]]
|
||||
- **Modern Tech/Tools**: Temporal Difference (TD) Learning, Process Reward Models (PRMs), Attribution modeling.
|
||||
---
|
||||
### Multi-agent Credit
|
||||
- 매 N agent → 매 collective reward.
|
||||
- 매 individual contribution.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 매 solution
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Backpropagation (structural)
|
||||
- 매 chain rule.
|
||||
- 매 each layer 의 gradient.
|
||||
- 매 1986 Rumelhart-Hinton-Williams.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### TD Learning (temporal)
|
||||
- 매 bootstrap.
|
||||
- 매 [[Computational-Neuroscience-RL]] 참조.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Eligibility Trace
|
||||
- 매 past action 의 trace 유지.
|
||||
- 매 TD(λ).
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### GAE (Generalized Advantage Estimation)
|
||||
- Schulman 2015.
|
||||
- 매 bias-variance trade-off.
|
||||
- 매 PPO 의 standard.
|
||||
- $A_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l \delta_{t+l}$
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### Hindsight Experience Replay (HER)
|
||||
- 매 fail trajectory 의 매 different goal 의 reuse.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Reward Shaping
|
||||
- 매 dense intermediate reward.
|
||||
- 매 careful: 매 unintended optimal X.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Process Reward Model (PRM, modern)
|
||||
- 매 매 step 의 grade.
|
||||
- 매 OpenAI Math, 매 DeepSeek-Prover.
|
||||
- 매 outcome reward 보다 매 finer.
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Counterfactual (multi-agent)
|
||||
- COMA (Counterfactual Multi-Agent Policy Gradient).
|
||||
- 매 1 agent 의 fix → 매 contribution.
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
### Attention attribution (LLM)
|
||||
- 매 attention score 의 attribution.
|
||||
- 매 SHAP, integrated gradient.
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
## 매 응용
|
||||
1. **Game AI**: 매 chess / Go (long horizon).
|
||||
2. **Robotics**: 매 sparse reward.
|
||||
3. **LLM RLHF**: 매 token-level reward.
|
||||
4. **Multi-agent**: 매 cooperative.
|
||||
5. **Medical**: 매 long-term outcome.
|
||||
6. **Finance**: 매 portfolio.
|
||||
|
||||
```text
|
||||
# TODO
|
||||
## 💻 패턴
|
||||
|
||||
### Backpropagation (structural)
|
||||
```python
|
||||
import torch
|
||||
|
||||
x = torch.tensor([1.0, 2.0], requires_grad=True)
|
||||
W1 = torch.randn(2, 3, requires_grad=True)
|
||||
W2 = torch.randn(3, 1, requires_grad=True)
|
||||
|
||||
h = torch.relu(x @ W1)
|
||||
y = h @ W2
|
||||
|
||||
loss = (y - target).pow(2).mean()
|
||||
loss.backward() # 매 W1, W2 의 gradient (credit) 계산.
|
||||
|
||||
print(W1.grad) # 매 each weight 의 contribution.
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### TD(0) (temporal)
|
||||
```python
|
||||
def td_update(V, state, reward, next_state, alpha=0.1, gamma=0.95):
|
||||
td_error = reward + gamma * V[next_state] - V[state]
|
||||
V[state] += alpha * td_error
|
||||
return V
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### TD(λ) with eligibility trace
|
||||
```python
|
||||
class TDLambda:
|
||||
def __init__(self, n_states, alpha=0.1, gamma=0.95, lam=0.9):
|
||||
self.V = np.zeros(n_states)
|
||||
self.e = np.zeros(n_states)
|
||||
self.alpha, self.gamma, self.lam = alpha, gamma, lam
|
||||
|
||||
def update(self, state, reward, next_state):
|
||||
td_error = reward + self.gamma * self.V[next_state] - self.V[state]
|
||||
self.e *= self.gamma * self.lam
|
||||
self.e[state] += 1 # 매 visited state 의 trace 증가
|
||||
self.V += self.alpha * td_error * self.e # 매 trace 비례 update
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### GAE (PPO standard)
|
||||
```python
|
||||
def compute_gae(rewards, values, gamma=0.99, lam=0.95):
|
||||
"""매 매 step 의 advantage."""
|
||||
advantages = np.zeros_like(rewards)
|
||||
last_gae = 0
|
||||
for t in reversed(range(len(rewards))):
|
||||
delta = rewards[t] + gamma * values[t+1] - values[t]
|
||||
advantages[t] = last_gae = delta + gamma * lam * last_gae
|
||||
return advantages
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Hindsight Experience Replay
|
||||
```python
|
||||
def her_relabel(trajectory, goal_extractor):
|
||||
"""매 failure 의 매 goal 의 reach 의 success 로 relabel."""
|
||||
new_trajectories = [trajectory]
|
||||
|
||||
# 매 final state 의 매 goal
|
||||
final_state = trajectory[-1].state
|
||||
new_goal = goal_extractor(final_state)
|
||||
|
||||
relabeled = []
|
||||
for t in trajectory:
|
||||
new_reward = 1.0 if reached(t.next_state, new_goal) else -0.01
|
||||
relabeled.append(Transition(t.state, t.action, new_reward, t.next_state, new_goal))
|
||||
new_trajectories.append(relabeled)
|
||||
|
||||
return new_trajectories
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Reward shaping (caution)
|
||||
```python
|
||||
def shaped_reward(state, action, next_state):
|
||||
base_reward = environment_reward(state, action, next_state)
|
||||
# 매 distance-based shaping (Ng 1999 — potential-based 안전)
|
||||
phi = lambda s: -distance_to_goal(s)
|
||||
shaping = gamma * phi(next_state) - phi(state)
|
||||
return base_reward + shaping
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Process Reward Model (PRM)
|
||||
```python
|
||||
def prm_train(model, trajectories):
|
||||
"""매 각 step 의 quality 의 supervised label."""
|
||||
for traj in trajectories:
|
||||
for step in traj.steps:
|
||||
# 매 human / verifier label
|
||||
quality = label_step(step.state, step.action, step.reasoning)
|
||||
loss = model.loss(step, quality)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
# 매 inference: 매 each generation step 의 PRM score.
|
||||
def search_with_prm(prompt, prm, beam=4, depth=10):
|
||||
candidates = [prompt]
|
||||
for d in range(depth):
|
||||
all_candidates = []
|
||||
for c in candidates:
|
||||
for cont in generate_n(c, n=beam*2):
|
||||
score = prm.score(c + cont)
|
||||
all_candidates.append((c + cont, score))
|
||||
all_candidates.sort(key=lambda x: -x[1])
|
||||
candidates = [c for c, _ in all_candidates[:beam]]
|
||||
return candidates[0]
|
||||
```
|
||||
|
||||
### COMA (multi-agent counterfactual)
|
||||
```python
|
||||
def coma_advantage(joint_actions, q_function, agent_idx):
|
||||
"""매 specific agent 의 contribution = joint Q − counterfactual baseline."""
|
||||
actual_q = q_function(joint_actions)
|
||||
|
||||
# 매 agent_idx 의 매 다른 action 의 average
|
||||
counterfactual_q = 0
|
||||
for alt_action in action_space:
|
||||
alt = list(joint_actions)
|
||||
alt[agent_idx] = alt_action
|
||||
counterfactual_q += q_function(alt) * policy[agent_idx][alt_action]
|
||||
|
||||
return actual_q - counterfactual_q
|
||||
```
|
||||
|
||||
### Attention-based attribution
|
||||
```python
|
||||
import torch
|
||||
|
||||
def attention_attribution(model, input_ids, target_token_idx):
|
||||
"""매 매 input token 의 contribution to 매 specific output."""
|
||||
output = model(input_ids, output_attentions=True)
|
||||
attentions = output.attentions # 매 N layer × N head × seq × seq
|
||||
|
||||
# 매 target token 의 attention to 매 input
|
||||
avg = torch.stack(attentions).mean(dim=(0, 1, 2)) # 매 reduce
|
||||
return avg[target_token_idx] # 매 (seq,) — 매 매 input 의 contribution
|
||||
```
|
||||
|
||||
### RLHF token-level credit
|
||||
```python
|
||||
def rlhf_token_advantage(generated_tokens, reward_model):
|
||||
"""매 reward 의 token-level distribute."""
|
||||
final_reward = reward_model(generated_tokens)
|
||||
|
||||
# 매 simple: 매 final 의 모든 token 의 distribute (inefficient)
|
||||
simple = [final_reward / len(generated_tokens)] * len(generated_tokens)
|
||||
|
||||
# 매 better: 매 PRM 의 step-level
|
||||
prm_scores = process_reward_model.score_each(generated_tokens)
|
||||
return prm_scores
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Long horizon | TD + GAE |
|
||||
| Sparse reward | HER + reward shaping |
|
||||
| Math / multi-step | PRM |
|
||||
| Deep NN | Backprop |
|
||||
| Multi-agent | COMA / counterfactual |
|
||||
| LLM RLHF | PRM > outcome reward |
|
||||
| Interpretability | SHAP / attention |
|
||||
|
||||
**기본값**: 매 GAE (PPO) + 매 PRM (LLM math/code).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Reinforcement-Learning]] · [[Optimization]] · [[Deep-Learning]]
|
||||
- 변형: [[Backpropagation]] · [[TD-Learning]] · [[GAE]] · [[HER]] · [[PRM]] · [[COMA]]
|
||||
- 응용: [[PPO]] · [[RLHF]] · [[Best-of-N_Sampling]] · [[Multi-Agent-Systems]]
|
||||
- Adjacent: [[Computational-Neuroscience-RL]] · [[Bayesian-Brain-Hypothesis]] · [[Bias-Correction-Algorithm]] · [[Causal-Inference]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 RL design. 매 RLHF / PRM. 매 multi-agent system. 매 attribution.
|
||||
**언제 X**: 매 supervised IID (다른 paradigm).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Outcome reward 만 (long horizon)**: 매 sparse signal.
|
||||
- **Reward shaping 의 careless**: 매 unintended optimal.
|
||||
- **No eligibility trace** (long): 매 slow learning.
|
||||
- **PRM 의 noisy label**: 매 wrong attribution.
|
||||
- **Multi-agent 의 individual reward 의 share**: 매 lazy agent.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Schulman GAE, Andrychowicz HER, OpenAI PRM, Foerster COMA).
|
||||
- 신뢰도 A.
|
||||
- Related: [[Reinforcement-Learning]] · [[Computational-Neuroscience-RL]] · [[RLHF]] · [[Causal-Inference]] · [[Best-of-N_Sampling]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — temporal/structural/multi-agent + 매 GAE / HER / PRM / COMA code |
|
||||
|
||||
Reference in New Issue
Block a user