- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
92 lines
3.1 KiB
Python
92 lines
3.1 KiB
Python
"""UCB 액션 선택 정책 — 에피소드 내 카드 중복 방지 포함."""
|
|
|
|
import logging
|
|
from typing import Optional
|
|
|
|
import numpy as np
|
|
|
|
from services.policy.visit_table import VisitTable
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class UCBPolicy:
|
|
"""Upper Confidence Bound policy with per-episode action masking.
|
|
|
|
UCB = Q(s,a) + c * sqrt(ln(N(s)) / N(s,a))
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
visit_table: VisitTable,
|
|
exploration_constant: float = float(np.sqrt(2.0)),
|
|
epsilon: float = 1e-6,
|
|
rng: Optional[np.random.Generator] = None,
|
|
) -> None:
|
|
self.visit_table = visit_table
|
|
self.action_space_size = visit_table.action_space_size
|
|
self.exploration_constant = exploration_constant
|
|
self.epsilon = epsilon
|
|
self._rng = rng or np.random.default_rng()
|
|
self._episode_actions: set[int] = set()
|
|
self._last_selection_info: dict = {}
|
|
|
|
def select_action(
|
|
self,
|
|
state_index: int,
|
|
q_values: np.ndarray,
|
|
available_mask: Optional[np.ndarray] = None,
|
|
) -> Optional[int]:
|
|
mask = self._prepare_mask(available_mask)
|
|
if not mask.any():
|
|
self.reset_episode()
|
|
mask = self._prepare_mask(available_mask)
|
|
if not mask.any():
|
|
return None
|
|
|
|
counts = self.visit_table.get_state_counts(state_index)
|
|
masked_counts = np.where(mask, counts, 0)
|
|
total = max(masked_counts.sum(), 1)
|
|
|
|
# N(s,a)=0인 액션은 epsilon으로 대체 → UCB 보너스가 매우 커져 자연스럽게 우선 선택
|
|
denom = np.where(counts > 0, counts.astype(float), self.epsilon)
|
|
bonus = self.exploration_constant * np.sqrt(np.log(total + 1.0) / denom)
|
|
scores = q_values + bonus
|
|
scores[~mask] = -np.inf
|
|
action = int(np.argmax(scores))
|
|
|
|
self._last_selection_info = {
|
|
"visit_count": int(counts[action]),
|
|
"total_visits": int(total),
|
|
"ucb_score": float(scores[action]),
|
|
}
|
|
|
|
logger.info(
|
|
f"[UCB Policy - State {state_index}] "
|
|
f"q={[f'{q:.3f}' for q in q_values]} visits={counts.tolist()} "
|
|
f"mask={mask.astype(int).tolist()} => action {action}"
|
|
)
|
|
|
|
self.visit_table.increment(state_index, action)
|
|
self._episode_actions.add(action)
|
|
return action
|
|
|
|
def reset_episode(self) -> None:
|
|
"""에피소드(협상 세션) 내 사용된 액션 기록 초기화 — 세션 경계마다 호출할 것"""
|
|
self._episode_actions.clear()
|
|
|
|
def get_action_mask(self) -> np.ndarray:
|
|
mask = np.ones(self.action_space_size, dtype=int)
|
|
for action in self._episode_actions:
|
|
mask[action] = 0
|
|
return mask
|
|
|
|
def _prepare_mask(self, available_mask: Optional[np.ndarray]) -> np.ndarray:
|
|
if available_mask is None:
|
|
mask = np.ones(self.action_space_size, dtype=bool)
|
|
else:
|
|
mask = np.asarray(available_mask, dtype=bool).copy()
|
|
for action in self._episode_actions:
|
|
mask[action] = False
|
|
return mask
|