[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,186 @@
|
||||
id: wiki-2026-0508-reward-shaping-in-rl
|
||||
title: Reward Shaping in RL
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [RL-REWARD-SHAPE-001]
|
||||
aliases: [Reward Shaping, Shaped Reward, Dense Reward Design]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, Reinforcement-Learning, reward-shaping, reward-design, sparse-rewards, Behavior-steering]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [reinforcement-learning, reward-design, RLHF, GRPO, sparse-reward]
|
||||
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/Gymnasium/TRL
|
||||
---
|
||||
|
||||
# Reward Shaping in RL (강화학습에서의 보상 설계)
|
||||
# Reward Shaping in RL
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "최종 목표라는 커다란 보상을 향해 가기 위해, 에이전트의 발걸음마다 '올바른 방향'을 가리키는 작은 이정표(Sub-rewards)를 설계하라" — 보상이 희소한(Sparse Reward) 환경에서 학습 속도를 높이기 위해 보상 함수에 추가적인 지침을 더하는 기법.
|
||||
## 매 한 줄
|
||||
> **"매 sparse reward → dense intermediate signal — without changing optimal policy."**. Ng, Harada, Russell 1999 ("Policy Invariance Under Reward Transformations") 의 prove 의 매 potential-based shaping F(s,s') = γΦ(s') − Φ(s) 가 optimal policy 의 preserve, 매 modern RLHF/GRPO/RLVR 의 reward design 의 foundation 의.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Intermediate Incentivization and [[Alignment|Alignment]] Steering" — 최종 성공 시에만 보상을 주는 대신, 목표에 가까워지는 상태 전이마다 보상을 부여하여 에이전트가 '무엇이 좋은 행동인지'를 빠르게 파악하게 만드는 패턴.
|
||||
- **주요 고려 사항:**
|
||||
- **Potential-based Reward Shaping:** 정책의 최적성을 해치지 않으면서 보상을 추가하는 수학적 기법.
|
||||
- **Reward Hacking Risk:** 에이전트가 개발자의 의도와 달리 꼼수를 써서 보상만 극대화하는 부작용 주의.
|
||||
- **Dense vs Sparse:** 너무 촘촘한 보상은 국소 최적해(Local Optimum)에 빠뜨릴 수 있고, 너무 희소한 보상은 학습 자체를 불가능하게 함.
|
||||
- **의의:** 복잡한 로봇 제어나 전략 게임처럼 성공까지의 과정이 긴 문제에서 AI의 학습 효율을 결정짓는 가장 결정적인 '교육학적 설계' 과정.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 보상을 많이 줄수록 똑똑해진다는 단순한 믿음에서 벗어나, 이제는 보상을 최소화하되 에이전트의 '호기심(Curiosity)'이나 '자기 주도적 탐색'을 장려하는 내적 동기(Intrinsic Motivation) 연구로 트렌드가 변화함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 작업 완수도 평가 시, 최종 결과뿐만 아니라 효율적인 도구 사용 및 불필요한 연산 방지 등 각 단계별 '좋은 습관'에 가중치를 주는 보상 체계를 적용함.
|
||||
### 매 핵심 theorem (Ng et al. 1999)
|
||||
- Shaped reward: r'(s, a, s') = r(s, a, s') + F(s, s').
|
||||
- F(s, s') = γ·Φ(s') − Φ(s) (potential-based) → policy invariance guaranteed.
|
||||
- 의 X 가 well-defined Φ — 매 arbitrary bonus 의 optimal policy 의 distort 의 가능.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Reinforcement-Learning|Reinforcement-Learning]], [[Positive-Reinforcement|Positive-Reinforcement]], [[Markov-Decision-Process-MDP|Markov-Decision-Process-MDP]], [[Exploration-vs-Exploitation|Exploration-vs-Exploitation]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Reward-Shaping-in-RL.md
|
||||
### 매 shaping types
|
||||
- **Potential-based** (theory-safe): heuristic value Φ(s).
|
||||
- **Curiosity / intrinsic motivation**: ICM, RND — exploration bonus.
|
||||
- **Demonstrations (LfD)**: shaped reward from expert similarity.
|
||||
- **Curriculum**: progressively harder targets.
|
||||
- **RLHF reward model**: human-trained dense reward.
|
||||
- **RLVR (verifiable)**: rule-based pass/fail (math, code) — sparse but exact.
|
||||
- **GRPO advantages** (DeepSeek 2024-25): group-relative normalization replaces critic.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Sparse-reward locomotion / manipulation.
|
||||
2. Game RL (StarCraft II, Atari hard-exploration).
|
||||
3. RLHF for LLM alignment.
|
||||
4. RLVR/GRPO for math/code (DeepSeek-R1, o1).
|
||||
5. Robotics imitation + RL hybrid.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Potential-Based Shaping (Ng 1999)
|
||||
```python
|
||||
def potential(state) -> float:
|
||||
"""매 heuristic 의 — e.g. 의 distance-to-goal."""
|
||||
return -goal_distance(state)
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def shaped_reward(r, s, s_next, gamma=0.99):
|
||||
return r + gamma * potential(s_next) - potential(s)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Curiosity-Driven (RND)
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class RND(nn.Module):
|
||||
def __init__(self, obs_dim, feat_dim=128):
|
||||
super().__init__()
|
||||
self.target = nn.Sequential(nn.Linear(obs_dim, 256), nn.ReLU(),
|
||||
nn.Linear(256, feat_dim))
|
||||
for p in self.target.parameters(): p.requires_grad_(False)
|
||||
self.predictor = nn.Sequential(nn.Linear(obs_dim, 256), nn.ReLU(),
|
||||
nn.Linear(256, feat_dim))
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
def intrinsic(self, obs):
|
||||
return ((self.predictor(obs) - self.target(obs)) ** 2).mean(-1)
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Curriculum Reward
|
||||
```python
|
||||
def curriculum_target(episode_idx, easy_target, hard_target, ramp_episodes=10000):
|
||||
t = min(episode_idx / ramp_episodes, 1.0)
|
||||
return easy_target + t * (hard_target - easy_target)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### RLHF Reward Model
|
||||
```python
|
||||
import torch.nn as nn
|
||||
from transformers import AutoModel
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
class RewardModel(nn.Module):
|
||||
def __init__(self, base="meta-llama/Llama-3-8b"):
|
||||
super().__init__()
|
||||
self.backbone = AutoModel.from_pretrained(base)
|
||||
self.head = nn.Linear(self.backbone.config.hidden_size, 1)
|
||||
|
||||
def forward(self, input_ids, attn):
|
||||
out = self.backbone(input_ids, attn).last_hidden_state
|
||||
last = out[:, -1]
|
||||
return self.head(last).squeeze(-1)
|
||||
|
||||
# Bradley-Terry pairwise loss
|
||||
def bt_loss(r_chosen, r_rejected):
|
||||
return -torch.nn.functional.logsigmoid(r_chosen - r_rejected).mean()
|
||||
```
|
||||
|
||||
### RLVR — Verifiable Rule Reward
|
||||
```python
|
||||
def rlvr_reward(generated: str, gold: str, task: str) -> float:
|
||||
if task == "math":
|
||||
return 1.0 if extract_answer(generated) == gold else 0.0
|
||||
elif task == "code":
|
||||
return float(run_unit_tests(generated))
|
||||
elif task == "format":
|
||||
return 1.0 if has_required_tags(generated) else 0.0
|
||||
```
|
||||
|
||||
### GRPO Advantage (DeepSeek 2024)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
def grpo_advantages(group_rewards: np.ndarray) -> np.ndarray:
|
||||
"""매 group-relative normalization — critic 의 X."""
|
||||
mean = group_rewards.mean()
|
||||
std = group_rewards.std() + 1e-8
|
||||
return (group_rewards - mean) / std
|
||||
|
||||
# Usage: sample G=8 outputs per prompt, compute rewards, normalize within group
|
||||
```
|
||||
|
||||
### Combined Shaping
|
||||
```python
|
||||
def combined_reward(r_env, s, s_next, model, obs, gamma=0.99,
|
||||
pot_w=1.0, cur_w=0.1):
|
||||
pot = gamma * potential(s_next) - potential(s)
|
||||
cur = model.intrinsic(obs).item()
|
||||
return r_env + pot_w * pot + cur_w * cur
|
||||
```
|
||||
|
||||
### Reward Hacking Detector
|
||||
```python
|
||||
def detect_hacking(rewards, true_returns, window=100):
|
||||
"""매 reward 의 up 의 X 의 true return 의 stagnant → hacking."""
|
||||
if len(rewards) < window: return False
|
||||
rew_trend = np.polyfit(range(window), rewards[-window:], 1)[0]
|
||||
ret_trend = np.polyfit(range(window), true_returns[-window:], 1)[0]
|
||||
return rew_trend > 0.01 and ret_trend < 0
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Sparse reward, known heuristic | Potential-based shaping |
|
||||
| Hard exploration | RND / ICM curiosity |
|
||||
| Have expert demos | LfD-shaped reward + BC pretrain |
|
||||
| LLM alignment, subjective | RLHF reward model |
|
||||
| LLM math/code | RLVR (rule-based) + GRPO |
|
||||
| Robotic manipulation | Combined: potential + curiosity + demo |
|
||||
|
||||
**기본값**: Potential-based primary; RLVR + GRPO 의 LLM verifiable tasks 의; RLHF 의 subjective tasks 의.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Reinforcement Learning]] · [[Reward Design]]
|
||||
- 변형: [[Potential-Based Shaping]] · [[Curiosity-Driven]] · [[GRPO]] · [[RLHF]] · [[RLVR]]
|
||||
- 응용: [[Sparse Reward]] · [[Hard Exploration]] · [[LLM Post-Training]]
|
||||
- Adjacent: [[Reward Prediction Error]] · [[Inverse RL]] · [[Imitation Learning]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: reward model training (RLHF), reward function code generation, reward hacking analysis from logs.
|
||||
**언제 X**: LLM 의 reward function 의 propose 의 hacking 의 prone 의 — verify 의 with controlled rollouts.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Non-potential bonus**: arbitrary +10 의 sub-goal 의 reach → optimal policy 의 distort.
|
||||
- **Reward hacking ignored**: cumulative reward up 의 task fail 의 monitor 의 X.
|
||||
- **Over-shaping**: dense bonus 의 overwhelm sparse signal → agent 의 task 의 ignore.
|
||||
- **Static curriculum**: agent 의 surpass 의 still serving easy targets.
|
||||
- **No baseline check**: shaping with vs without 의 ablation 의 X — actual gain unknown.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Ng/Harada/Russell 1999 ICML; DeepSeek-R1 paper 2025; Sutton & Barto Ch 17).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — potential-based + RND + RLHF + GRPO + RLVR |
|
||||
|
||||
Reference in New Issue
Block a user