- 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
112 lines
3.9 KiB
Python
112 lines
3.9 KiB
Python
"""카드 선택기 — State → action_id → card_id 추론."""
|
|
|
|
import logging
|
|
from typing import Dict, Optional
|
|
|
|
import numpy as np
|
|
|
|
from services.cards.mapper import ActionCardMapper
|
|
from services.policy.q_table import QTable
|
|
from services.policy.state import State
|
|
from services.policy.ucb import UCBPolicy
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class CardSelector:
|
|
"""
|
|
Q_Table은 추상적인 action_id만 반환하고,
|
|
ActionCardMapper를 통해 구체적인 card_id로 변환한다.
|
|
"""
|
|
|
|
def __init__(self, q_table: QTable, policy: UCBPolicy,
|
|
action_card_mapper: ActionCardMapper):
|
|
self.q_table = q_table
|
|
self.policy = policy
|
|
self.action_card_mapper = action_card_mapper
|
|
|
|
def execute(
|
|
self,
|
|
state: State,
|
|
use_policy: bool = True,
|
|
excluded_actions: Optional[list] = None,
|
|
) -> Dict:
|
|
"""
|
|
현재 상태에서 최적의 협상 카드 선택.
|
|
|
|
Args:
|
|
use_policy: True면 UCB 정책(방문수 증가 + 에피소드 중복 방지),
|
|
False면 순수 Q-value argmax (학습 격리 — 신규견적 등)
|
|
excluded_actions: 선택에서 제외할 action_id 리스트
|
|
"""
|
|
state_index = state.to_index()
|
|
q_values = self.q_table.get_q_values_for_state(state_index)
|
|
|
|
available_mask = None
|
|
if excluded_actions is not None:
|
|
action_space_size = len(q_values)
|
|
available_mask = np.ones(action_space_size, dtype=int)
|
|
for action_id in excluded_actions:
|
|
if 0 <= action_id < action_space_size:
|
|
available_mask[action_id] = 0
|
|
logger.info(f"[CardSelector] excluded actions: {excluded_actions}")
|
|
|
|
if use_policy:
|
|
action_id = self.policy.select_action(
|
|
state_index, q_values, available_mask=available_mask
|
|
)
|
|
else:
|
|
if available_mask is not None:
|
|
masked_q = q_values.copy()
|
|
masked_q[available_mask == 0] = -np.inf
|
|
action_id = int(np.argmax(masked_q))
|
|
if masked_q[action_id] == -np.inf:
|
|
action_id = None
|
|
else:
|
|
action_id = self.q_table.get_best_action(state_index)
|
|
|
|
if action_id is None:
|
|
return {
|
|
"action_id": None,
|
|
"card_id": None,
|
|
"q_value": None,
|
|
"state_index": state_index,
|
|
"message": "No available actions (all actions used in this episode)",
|
|
}
|
|
|
|
card_id = self.action_card_mapper.get_card_id(action_id)
|
|
if card_id is None:
|
|
return {
|
|
"action_id": action_id,
|
|
"card_id": None,
|
|
"q_value": float(q_values[action_id]),
|
|
"state_index": state_index,
|
|
"visit_count": 0,
|
|
"message": f"action_id {action_id} has no card mapping",
|
|
}
|
|
|
|
q_value = self.q_table.get_q_value(state_index, action_id)
|
|
|
|
# 학습 격리 경로는 정책을 거치지 않으므로 정책 통계가 무의미 → None
|
|
if use_policy:
|
|
visit_count = self.policy.visit_table.get_action_count(state_index, action_id)
|
|
selection_info = self.policy._last_selection_info
|
|
else:
|
|
visit_count = None
|
|
selection_info = {}
|
|
|
|
return {
|
|
"action_id": action_id,
|
|
"card_id": card_id,
|
|
"q_value": float(q_value),
|
|
"state_index": state_index,
|
|
"visit_count": visit_count,
|
|
"visit_count_at_selection": selection_info.get("visit_count"),
|
|
"total_visits_at_selection": selection_info.get("total_visits"),
|
|
"ucb_score_at_selection": selection_info.get("ucb_score"),
|
|
}
|
|
|
|
def reset_episode(self):
|
|
"""협상 세션 종료/시작 시 정책 초기화"""
|
|
self.policy.reset_episode()
|