Merge feat/switch-model into feat/switch-model-v2 (main 1cce752 기준)
충돌 해결 원칙: main 의 협상 고도화(결정 스택 규칙층·ScriptNaturalizer 표현층·카드 전술· LPS 최저가 연동)와 switch-model 의 완전 자율 모드(DQN·봉투·ment_generator)를 모두 유지. - chat_engine: rules(config 규칙층) + autonomy_decider 공존, vars_for 는 main 전술 변수 + 자율 변수(autonomy_offer/internet_lowest_price/customer_condition) 합집합, wild_card_1pct 수락 분기는 main 의 pending_counter_price 일반화로 대체(자율 분기만 유지) - chat_service: tactics/naturalizer import + ment_generator import 병존, _play_closing_tactic(main) + _autonomy_learn(자율 로깅) 메서드 병존 - nego_context_crud: _ITEMS/_SUPPLIERS 컬럼 합집합 (name + internet_lowest_price) - docker-compose: OPENAI_API_KEY passthrough + DQN_SERVING/AUTONOMY_MODE 플래그 병존 검증: py_compile + 결함 회귀 게이트 78/78 통과 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
commit
8f4c82a282
32 files changed
+2926
-8
No files matched your search
@@ -0,0 +1,63 @@
|
||||
"""카드 스크립트 → 임베딩 캐시 생성 (action-as-feature 준비, 1회 실행).
|
||||
|
||||
card.nego_cards(11장)의 name+script 를 문장 임베딩으로 변환해 artifacts/card_embeddings.npz 에 저장.
|
||||
새 카드가 추가되면 이 스크립트를 다시 돌리면 된다(그 카드만 임베딩돼 캐시에 합류).
|
||||
|
||||
실행:
|
||||
APP_ENV=local python -m tools.build_card_embeddings
|
||||
출력:
|
||||
artifacts/card_embeddings.npz (numbers, names, strategy, tone, embeddings[N,384])
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ARTIFACTS = os.path.join(_HERE, "..", "artifacts")
|
||||
OUT_PATH = os.path.join(ARTIFACTS, "card_embeddings.npz")
|
||||
|
||||
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2" # 384차원, 한국어 지원, 로컬/무료
|
||||
|
||||
|
||||
async def load_cards():
|
||||
"""card.nego_cards 에서 (number, name, script, strategy_type, tone) 로드."""
|
||||
import asyncpg
|
||||
conn = await asyncpg.connect(
|
||||
host="127.0.0.1", port=5432, user="postgres", password="password", database="negosium_db")
|
||||
try:
|
||||
rows = await conn.fetch(
|
||||
"SELECT number, name, script, strategy_type, tone FROM card.nego_cards "
|
||||
"WHERE deleted = FALSE ORDER BY number")
|
||||
return [(r["number"], r["name"], r["script"], r["strategy_type"], r["tone"]) for r in rows]
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
def main():
|
||||
cards = asyncio.run(load_cards())
|
||||
if not cards:
|
||||
raise SystemExit("card.nego_cards 가 비어있음 — DB 시드 확인 (docker start negosium-pg)")
|
||||
print(f"카드 {len(cards)}장 로드: {[c[0] for c in cards]}")
|
||||
|
||||
from sentence_transformers import SentenceTransformer
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
texts = [f"{name}. {script}" for _, name, script, _, _ in cards]
|
||||
emb = model.encode(texts, normalize_embeddings=True) # [N, 384], 단위벡터
|
||||
print(f"임베딩 shape: {emb.shape}")
|
||||
|
||||
os.makedirs(ARTIFACTS, exist_ok=True)
|
||||
np.savez(
|
||||
OUT_PATH,
|
||||
numbers=np.array([c[0] for c in cards]),
|
||||
names=np.array([c[1] for c in cards]),
|
||||
strategy=np.array([c[3] for c in cards], dtype=np.int64),
|
||||
tone=np.array([c[4] for c in cards], dtype=np.int64),
|
||||
embeddings=emb.astype(np.float32),
|
||||
)
|
||||
print(f"저장: {OUT_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,251 @@
|
||||
"""기존 Q-Table(UCB) vs action-as-feature DQN 공정 비교 — 고객사 성향 조건화 환경 (최종).
|
||||
|
||||
같은 환경(FeatureBuyer 2축 + 협력사·고객사성향 랜덤)에서 동일 에피소드로 학습·평가.
|
||||
- Q-Table: 이산 state 162칸 + 카드=슬롯. 성향(고객사) 입력 자체가 불가능 → 평균 성향에 수렴
|
||||
- DQN : 연속 상태 + 성향 벡터 + 카드 특징(임베딩+전략/톤 one-hot)
|
||||
|
||||
평가 4종:
|
||||
① 학습 카드 9장 — 평균보상(진짜 목적함수) + top3 적중(MC 정답 기준)
|
||||
② zero-shot 11장 — 안 본 카드 2장 포함
|
||||
③ 새 카드 첫 턴 사용률 — 구조적 차이
|
||||
④ 성향 극단 테스트 — 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가
|
||||
|
||||
실행: APP_ENV=local python -m tools.compare_qtable_vs_dqn
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.buyer import Scenario
|
||||
from eval_harness.feature_buyer import FeatureBuyer, SupplierProfile, sample_supplier
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.train_feature_dqn import (
|
||||
ANCHOR, HOLDOUT, MAX_TURNS, TARGET, load_cards, make_snapshot, pref_config, sample_tenant_pref)
|
||||
|
||||
|
||||
# ---- 정책 어댑터 ------------------------------------------------------------------
|
||||
class DQNAdapter:
|
||||
name = "feature_dqn"
|
||||
|
||||
def __init__(self, policy, feat):
|
||||
self.p, self.feat = policy, feat
|
||||
|
||||
def _sf(self, snap, tf):
|
||||
return np.concatenate([build_state_features(snap), tf])
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
self.p.greedy = greedy
|
||||
i, _, _ = self.p.select(self._sf(snap, tf), np.stack([self.feat[c] for c in avail]))
|
||||
return avail[i]
|
||||
|
||||
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||
sf = self._sf(snap, tf)
|
||||
if done or next_snap is None:
|
||||
self.p.remember(sf, self.feat[card], reward, None, None, True)
|
||||
else:
|
||||
self.p.remember(sf, self.feat[card], reward, self._sf(next_snap, tf),
|
||||
np.stack([self.feat[c] for c in next_avail]), False)
|
||||
self.p.train_step()
|
||||
|
||||
|
||||
class QTableAdapter:
|
||||
"""기존 UCBQTablePolicy. 성향(tf)은 구조상 받을 수 없다 — 이산 state 162칸에 그 축이 없음."""
|
||||
|
||||
name = "qtable_ucb"
|
||||
|
||||
def __init__(self, all_numbers, state_cfg, lr=0.1, gamma=0.95):
|
||||
self.numbers = list(all_numbers)
|
||||
self.a_of = {n: i for i, n in enumerate(self.numbers)}
|
||||
self.state_cfg = state_cfg
|
||||
self.qt = QTable(162, len(self.numbers), learning_rate=lr, discount_factor=gamma)
|
||||
self.pol = UCBQTablePolicy(self.qt)
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
idx = state_index(snap, self.state_cfg)
|
||||
if greedy:
|
||||
q = self.qt.row(idx)
|
||||
return max(avail, key=lambda c: q[self.a_of[c]])
|
||||
mask = np.zeros(len(self.numbers), dtype=bool)
|
||||
for c in avail:
|
||||
mask[self.a_of[c]] = True
|
||||
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=len(self.numbers),
|
||||
episode=EpisodeState(), available_mask=mask)
|
||||
return self.numbers[self.pol.select(ctx).action_id]
|
||||
|
||||
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||
idx = state_index(snap, self.state_cfg)
|
||||
nidx = state_index(next_snap, self.state_cfg) if (next_snap is not None and not done) else None
|
||||
self.pol.update(Transition(state_index=idx, action_id=self.a_of[card], reward=reward,
|
||||
next_state_index=nidx, done=done))
|
||||
|
||||
|
||||
class RandomAdapter:
|
||||
name = "random"
|
||||
|
||||
def __init__(self, seed=0):
|
||||
self.rng = np.random.default_rng(seed)
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
return avail[self.rng.integers(len(avail))]
|
||||
|
||||
def learn(self, *a, **k):
|
||||
pass
|
||||
|
||||
|
||||
# ---- 공용 에피소드 -----------------------------------------------------------------
|
||||
def run_episode(adapter, sup, tf, pool, strat, rc, seed, learn=True, greedy=False, forced_first=None):
|
||||
buyer = FeatureBuyer(sup, strat, seed=seed, max_turns=MAX_TURNS)
|
||||
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||
price0 = TARGET * 1.15
|
||||
price, used, total_r, first_card = price0, set(), 0.0, None
|
||||
|
||||
for turn in range(1, MAX_TURNS + 1):
|
||||
acceptance = max(0.0, (price0 - price) / price0)
|
||||
snap = make_snapshot(sup, price, turn, acceptance)
|
||||
avail = [c for c in pool if c not in used] or list(pool)
|
||||
if turn == 1 and forced_first is not None:
|
||||
card = forced_first
|
||||
else:
|
||||
card = adapter.choose(snap, tf, avail, greedy)
|
||||
used.add(card)
|
||||
if first_card is None:
|
||||
first_card = card
|
||||
|
||||
resp = buyer.respond(card, scenario, turn, price)
|
||||
price = resp.new_price
|
||||
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||
success = resp.accept or price <= ANCHOR
|
||||
outcome = (NegotiationOutcome.SUCCESS if success
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
# 채점은 최종 결과 시점만 (중간 턴 0 → γ 부트스트랩으로 전파).
|
||||
# 진행 중 보상을 누적하면 '질질 끄는 전략'이 부당하게 유리해지는 인공물이 생긴다.
|
||||
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||
total_r += r
|
||||
|
||||
if learn:
|
||||
if done:
|
||||
adapter.learn(snap, tf, card, r, None, None, True)
|
||||
else:
|
||||
acc2 = max(0.0, (price0 - price) / price0)
|
||||
nsnap = make_snapshot(sup, price, turn + 1, acc2)
|
||||
navail = [c for c in pool if c not in used] or list(pool)
|
||||
adapter.learn(snap, tf, card, r, nsnap, navail, False)
|
||||
if done:
|
||||
return total_r, success, price, first_card
|
||||
return total_r, False, price, first_card
|
||||
|
||||
|
||||
# ---- MC 정답 랭킹: 이 (협력사, 성향)에서 진짜 좋은 첫 카드 top-k ---------------------
|
||||
_rand = RandomAdapter(seed=1)
|
||||
|
||||
def rank_cards_mc(sup, tf, pool, strat, rc, seed, sims=6, k=3):
|
||||
means = {}
|
||||
for c in pool:
|
||||
rs = [run_episode(_rand, sup, tf, pool, strat, rc, seed=seed + 17 * s,
|
||||
learn=False, greedy=False, forced_first=c)[0] for s in range(sims)]
|
||||
means[c] = np.mean(rs)
|
||||
return sorted(means, key=lambda c: -means[c])[:k]
|
||||
|
||||
|
||||
# ---- 학습/평가 ---------------------------------------------------------------------
|
||||
def train(adapter, pool, strat, base_reward, state_cfg, episodes, seed):
|
||||
rng = np.random.default_rng(seed)
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||
rc = RewardCalculator(rcfg, state_cfg)
|
||||
run_episode(adapter, sup, tf, pool, strat, rc, seed=seed * 100 + ep, learn=True)
|
||||
|
||||
|
||||
def evaluate(adapter, pool, strat, base_reward, state_cfg, n=300, seed0=777, label=""):
|
||||
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||
rng = np.random.default_rng(seed0)
|
||||
rewards, succ, ratios, hits, holdout_first = [], 0, [], 0, 0
|
||||
for i in range(n):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||
rc = RewardCalculator(rcfg, state_cfg)
|
||||
good = rank_cards_mc(sup, tf, pool, strat, rc, seed=seed0 * 7 + i)
|
||||
r, ok, price, first = run_episode(adapter, sup, tf, pool, strat, rc,
|
||||
seed=seed0 * 1000 + i, learn=False, greedy=True)
|
||||
rewards.append(r); succ += ok; ratios.append(price / TARGET)
|
||||
hits += (first in good); holdout_first += (first in HOLDOUT)
|
||||
m, ci = float(np.mean(rewards)), float(1.96 * np.std(rewards) / np.sqrt(n))
|
||||
print(f"{label:<14} mean_rwd={m:.4f} ±{ci:.4f} success={succ/n:.3f} "
|
||||
f"settled/tgt={np.mean(ratios):.3f} top3_hit={hits/n:.3f} 새카드첫턴={holdout_first/n:.3f}")
|
||||
|
||||
|
||||
def pref_behavior_test(adapters, pool, strat, base_reward, state_cfg):
|
||||
"""④ 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가 (greedy).
|
||||
|
||||
첫 턴은 '일단 깎기'가 공통 정답이라 성향 차이가 잘 안 드러난다.
|
||||
→ 협상 중반(가격이 이미 target 근처, 3턴째) 상태를 함께 프로브: 여기서
|
||||
성사중시는 '마무리(수락 잘 되는) 카드', 가격중시는 '더 깎는 카드'가 갈려야 한다.
|
||||
"""
|
||||
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||
sups = [SupplierProfile(5_000_000, 3, "A"), # 소형·경쟁多
|
||||
SupplierProfile(200_000_000, 1, "A")] # 대형·단독
|
||||
probes = [("첫턴", TARGET * 1.15, 1, 0.0),
|
||||
("중반(3턴,가격↓)", TARGET * 1.02, 3, 0.11)]
|
||||
for pr_name, price, turn, acc in probes:
|
||||
print(f"\n ── 프로브: {pr_name} (price={price:.0f}) ──")
|
||||
print(f" {'협력사':<13} {'성향':<9} " + " ".join(f"{a.name:<15}" for a in adapters))
|
||||
for sup in sups:
|
||||
row = {}
|
||||
for p, pname in [(0.05, "성사중시"), (0.95, "가격중시")]:
|
||||
rcfg = pref_config(base_reward, p)
|
||||
tf = build_tenant_features(rcfg)
|
||||
picks = []
|
||||
for a in adapters:
|
||||
snap = make_snapshot(sup, price, turn, acc)
|
||||
picks.append(a.choose(snap, tf, pool, True))
|
||||
seg = f"{sup.segment[0]}·{sup.segment[1]}"
|
||||
print(f" {seg:<13} {pname:<9} " + " ".join(f"{c}(전략{strat[c]})".ljust(15) for c in picks))
|
||||
|
||||
|
||||
def main(episodes=10000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
numbers, feat, strat = load_cards()
|
||||
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
card_dim = feat[numbers[0]].shape[0]
|
||||
print(f"환경: 2축 FeatureBuyer + 성향 랜덤 · 학습 {episodes}ep · 카드특징 {card_dim}차원 "
|
||||
f"(임베딩384+전략4+톤4) · 학습 {len(train_pool)}장 / 홀드아웃 {HOLDOUT}")
|
||||
|
||||
qt = QTableAdapter(numbers, tcfg.state)
|
||||
dqn = DQNAdapter(FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=card_dim, eps_decay=4000), feat)
|
||||
|
||||
print("\n[학습] qtable_ucb ...")
|
||||
train(qt, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||
print("[학습] feature_dqn ...")
|
||||
train(dqn, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||
|
||||
print("\n=== ① 학습 카드 9장 풀 ===")
|
||||
evaluate(RandomAdapter(seed), train_pool, strat, tcfg.reward, tcfg.state, label="random")
|
||||
evaluate(qt, train_pool, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||
evaluate(dqn, train_pool, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||
|
||||
print("\n=== ② zero-shot 11장 풀 (안 본 카드 2장 포함) ===")
|
||||
evaluate(RandomAdapter(seed), numbers, strat, tcfg.reward, tcfg.state, label="random")
|
||||
evaluate(qt, numbers, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||
evaluate(dqn, numbers, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||
|
||||
print("\n=== ④ 성향 극단 테스트 — 같은 협력사, 성향만 바꾸면 카드를 바꾸는가 (11장 풀) ===")
|
||||
pref_behavior_test([qt, dqn], numbers, strat, tcfg.reward, tcfg.state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""full_autonomy 체크포인트(.pt) → 서빙 번들(autonomy_serving.npz) export.
|
||||
|
||||
dqn_serving 과 동일 패턴: ScoreNet 가중치만 numpy 로 묶어 PyTorch 없이 서빙한다.
|
||||
행동 특징은 코드(autonomy_actions)가 런타임 생성하므로 번들에는 가중치만 담는다.
|
||||
|
||||
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_autonomy_serving
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from negotiation.policies.autonomy_actions import ACTION_DIM, EXTRA_STATE_DIM
|
||||
from negotiation.qtable.domain.service.feature_builder import STATE_FEATURE_DIM, TENANT_FEATURE_DIM
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "autonomy_serving.npz")
|
||||
|
||||
STATE_DIM = STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM
|
||||
|
||||
|
||||
def main():
|
||||
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
assert W0.shape[1] == STATE_DIM + ACTION_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||
|
||||
tmp = OUT_PATH + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
np.savez(f, W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||
state_dim=STATE_DIM, action_dim=ACTION_DIM)
|
||||
if os.path.exists(OUT_PATH):
|
||||
os.replace(OUT_PATH, OUT_PATH + ".prev")
|
||||
os.replace(tmp, OUT_PATH)
|
||||
print(f"[저장] {os.path.abspath(OUT_PATH)} (state {STATE_DIM} + action {ACTION_DIM})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""feature_dqn 체크포인트(.pt) → 서빙 번들(dqn_serving.npz) export.
|
||||
|
||||
서빙 컨테이너에 PyTorch 를 넣지 않기 위해 ScoreNet(3층 MLP) 가중치와 카드 특징
|
||||
(임베딩384 + 전략 one-hot4 + 톤 one-hot4 = 392)을 numpy 번들 하나로 묶는다.
|
||||
추론은 negotiation.policy.dqn_store 의 numpy forward 가 수행한다.
|
||||
|
||||
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_dqn_serving
|
||||
산출: agent/artifacts/dqn_serving.npz (.dockerignore 미제외 → 이미지에 포함)
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from tools.train_feature_dqn import load_cards
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "dqn_serving.npz")
|
||||
|
||||
STATE_DIM = 14 # build_state_features(9) + build_tenant_features(5)
|
||||
CARD_DIM = 392
|
||||
|
||||
|
||||
def _np_forward(x, W0, b0, W1, b1, W2, b2):
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
return h @ W2.T + b2
|
||||
|
||||
|
||||
def export_bundle(sd, out_path: str) -> str:
|
||||
"""state_dict → 서빙 번들 npz (원자적 교체: .tmp 작성 후 replace). 반환: 절대경로.
|
||||
|
||||
retrain_from_logs 재학습 배포도 이 함수를 쓴다 — 검증(torch/numpy 일치)은 main() 전용.
|
||||
"""
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
assert W0.shape[1] == STATE_DIM + CARD_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||
numbers, feat, _ = load_cards()
|
||||
card_feats = np.stack([feat[n] for n in numbers]).astype(np.float32)
|
||||
tmp = out_path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
np.savez(
|
||||
f,
|
||||
W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||
card_numbers=np.array(numbers), card_feats=card_feats,
|
||||
state_dim=STATE_DIM, card_dim=CARD_DIM,
|
||||
)
|
||||
if os.path.exists(out_path):
|
||||
os.replace(out_path, out_path + ".prev") # 직전 번들 백업(롤백용)
|
||||
os.replace(tmp, out_path)
|
||||
return os.path.abspath(out_path)
|
||||
|
||||
|
||||
def main():
|
||||
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||
# 정합성 검증: torch forward == numpy forward
|
||||
from negotiation.policies.feature_dqn_policy import ScoreNet
|
||||
net = ScoreNet(STATE_DIM, CARD_DIM)
|
||||
net.load_state_dict(sd)
|
||||
net.eval()
|
||||
x = np.random.default_rng(0).normal(size=(8, STATE_DIM + CARD_DIM)).astype(np.float32)
|
||||
with torch.no_grad():
|
||||
ref = net(torch.tensor(x)).numpy()
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
out = _np_forward(x, W0, b0, W1, b1, W2, b2).squeeze(-1)
|
||||
diff = float(np.abs(ref - out).max())
|
||||
assert diff < 1e-4, f"numpy/torch forward 불일치: {diff}"
|
||||
|
||||
path = export_bundle(sd, OUT_PATH)
|
||||
print(f"[저장] {path} forward 오차 {diff:.2e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""probe_serving_dqn — 서빙 번들(dqn_serving.npz)의 상황별 카드 선택 프로브.
|
||||
|
||||
배포된 모델이 '상황에 맞게' 고르는지 눈으로 확인하는 진단 도구:
|
||||
협력사 세그먼트 × 고객사 성향 × 협상 국면(가격대)별 선택 카드를 표로 출력한다.
|
||||
전부 다르길 기대하는 게 아니라, 축을 바꿨을 때 선택이 '움직이는지'를 본다.
|
||||
|
||||
실행: APP_ENV=local python -m tools.probe_serving_dqn (numpy 만 필요, DB 불필요)
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import build_state_features, build_tenant_features
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.export_dqn_serving import OUT_PATH
|
||||
from tools.retrain_from_logs import np_scorer_from_bundle
|
||||
from tools.train_feature_dqn import pref_config
|
||||
|
||||
ANCHOR, TARGET = 495_000.0, 500_000.0 # BUGCHECK 견적과 동일 스케일
|
||||
|
||||
SUPPLIERS = {
|
||||
"소형·경쟁多": dict(revenue_amount=5_000_000, partner_count=3, distribution_code="A"),
|
||||
"소형·단독": dict(revenue_amount=5_000_000, partner_count=1, distribution_code="A"),
|
||||
"대형·경쟁多": dict(revenue_amount=200_000_000, partner_count=3, distribution_code="A"),
|
||||
"대형·단독": dict(revenue_amount=200_000_000, partner_count=1, distribution_code="A"),
|
||||
}
|
||||
PHASES = { # (라운드, 제시가): 첫턴 높은 가격 / 중반 목표가 근접 / 막판 앵커존 직전
|
||||
"첫턴(575k)": (1, 575_000.0),
|
||||
"중반(510k)": (2, 510_000.0),
|
||||
"막판(501k)": (3, 501_000.0),
|
||||
}
|
||||
PREFS = {"성사중시": 0.1, "가격중시": 0.9}
|
||||
|
||||
|
||||
def main():
|
||||
score = np_scorer_from_bundle(OUT_PATH)
|
||||
z = np.load(OUT_PATH, allow_pickle=False)
|
||||
numbers = [str(n) for n in z["card_numbers"]]
|
||||
feats = z["card_feats"]
|
||||
base = TenantConfigLoader().load("ktcommerce").reward
|
||||
|
||||
for phase, (turn, price) in PHASES.items():
|
||||
print(f"\n=== {phase} (앵커 {int(ANCHOR):,} / 목표 {int(TARGET):,}) ===")
|
||||
print(f"{'협력사':<12}" + "".join(f"{p:>16}" for p in PREFS))
|
||||
for sup_name, sup in SUPPLIERS.items():
|
||||
row = []
|
||||
for _, p in PREFS.items():
|
||||
tf = build_tenant_features(pref_config(base, p))
|
||||
snap = NegotiationSnapshot(
|
||||
revenue_amount=sup["revenue_amount"], distribution_code=sup["distribution_code"],
|
||||
partner_count=sup["partner_count"],
|
||||
acceptance_ratio=max(0.0, (575_000.0 - price) / 575_000.0),
|
||||
input_price=price, anchor_price=ANCHOR, target_price=TARGET, round_number=turn,
|
||||
)
|
||||
sf = np.concatenate([build_state_features(snap), tf])
|
||||
row.append(numbers[int(np.argmax(score(sf, feats)))])
|
||||
print(f"{sup_name:<12}" + "".join(f"{c:>16}" for c in row))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,238 @@
|
||||
"""retrain_from_logs — experience_logs 실데이터로 feature_dqn 오프라인 재학습 + OPE 게이트.
|
||||
|
||||
파이프라인:
|
||||
① learning.experience_logs 로드(전 테넌트 — 범용 에이전트는 테넌트를 특징으로 조건화하므로 통합 학습)
|
||||
② 세션별 에피소드 재구성: 카드턴(done=False) N개 + 종료행(done=True) 1개.
|
||||
보상은 학습 규약(최종 결과 시점만 채점)에 맞춰 종료행 reward 만 쓰고 중간턴은 0.
|
||||
③ 현재 체크포인트에서 fine-tune (낮은 lr — 시뮬 사전학습 망각 방지)
|
||||
④ OPE(SNIPS, 궤적 IS): 후보 모델 vs 현재 서빙 번들. 후보가 못 넘으면 배포하지 않는다.
|
||||
⑤ 통과 시 dqn_serving.npz 원자적 교체(직전본 .prev 백업) → `docker compose build agent && up -d agent` 로 배포.
|
||||
|
||||
실행(호스트, torch+DB 필요):
|
||||
APP_ENV=local python -m tools.retrain_from_logs
|
||||
환경변수:
|
||||
MIN_EPISODES(기본 200) 재학습 최소 에피소드 수 — 미달 시 skip (과적합 방지)
|
||||
EPOCHS(기본 20) / LR(기본 1e-4) / FORCE_DEPLOY=1 (OPE 게이트 무시 — 테스트 전용)
|
||||
|
||||
주의: 서빙이 greedy(탐색 없음)라 로그가 선택 편향됨 — OPE 의 유효표본(ESS)이 작으면
|
||||
게이트가 보수적으로 배포를 막는다. 이는 의도된 동작이다(조용한 성능저하 방지).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import ExperienceLog
|
||||
from common.enums import DBType, DBWRType
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from sqlalchemy import select
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.export_dqn_serving import CKPT_PATH, OUT_PATH, export_bundle
|
||||
from tools.train_feature_dqn import load_cards
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
RETRAIN_CKPT = os.path.join(_HERE, "..", "artifacts", "feature_dqn_retrained.pt")
|
||||
REPORT_PATH = os.path.join(_HERE, "..", "artifacts", "retrain_report.json")
|
||||
|
||||
MIN_EPISODES = int(os.getenv("MIN_EPISODES", "200"))
|
||||
EPOCHS = int(os.getenv("EPOCHS", "20"))
|
||||
LR = float(os.getenv("LR", "1e-4"))
|
||||
FORCE_DEPLOY = os.getenv("FORCE_DEPLOY") == "1"
|
||||
PROPENSITY_FALLBACK = 0.9 # 구로그 propensity 누락 시 (UCB/DQN 모두 greedy≈(1-ε)+ε/n)
|
||||
|
||||
|
||||
# ---- ① 로그 로드 -------------------------------------------------------------
|
||||
async def fetch_logs():
|
||||
def _q(s):
|
||||
q = (select(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.card_id,
|
||||
ExperienceLog.reward, ExperienceLog.done, ExperienceLog.snapshot,
|
||||
ExperienceLog.propensity, ExperienceLog.turn, ExperienceLog.id)
|
||||
.where(ExperienceLog.is_invalidated == False) # noqa: E712
|
||||
.order_by(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.id))
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return rows
|
||||
|
||||
|
||||
# ---- ② 에피소드 재구성 --------------------------------------------------------
|
||||
def build_episodes(rows, known_cards: set):
|
||||
"""→ [{tenant, steps:[(snapshot, card, propensity)], terminal_reward}], 스킵 사유 카운트."""
|
||||
by_session = defaultdict(list)
|
||||
for r in rows:
|
||||
if r[1] is not None:
|
||||
by_session[(r[0], str(r[1]))].append(r)
|
||||
|
||||
episodes, skipped = [], defaultdict(int)
|
||||
for (company_id, _sid), items in by_session.items():
|
||||
selects = [r for r in items if not r[4] and r[5]] # done=False, snapshot 有
|
||||
terminals = [r for r in items if r[4] and r[3] is not None] # done=True, reward 有
|
||||
if not selects or not terminals:
|
||||
skipped["종료행/카드턴 없음(미완결 세션)"] += 1
|
||||
continue
|
||||
if any(str(r[2] or "").startswith("AUT|") for r in selects):
|
||||
skipped["완전 자율 세션(카드 재학습 대상 아님)"] += 1
|
||||
continue
|
||||
if any(r[2] not in known_cards for r in selects):
|
||||
skipped["임베딩 없는 카드(파일매핑 테넌트 등)"] += 1
|
||||
continue
|
||||
episodes.append(dict(
|
||||
tenant=company_id,
|
||||
steps=[(r[5], r[2], r[6] if r[6] else PROPENSITY_FALLBACK) for r in selects],
|
||||
terminal_reward=float(terminals[-1][3]),
|
||||
))
|
||||
return episodes, skipped
|
||||
|
||||
|
||||
def tenant_feat_for(cache: dict, loader: TenantConfigLoader, company_id: str) -> np.ndarray:
|
||||
"""테넌트 보상설정 → 성향 특징. 미온보딩/로드 실패는 _base 폴백."""
|
||||
if company_id not in cache:
|
||||
try:
|
||||
cfg = loader.load(company_id)
|
||||
except Exception:
|
||||
cfg = loader.load("_base")
|
||||
cache[company_id] = build_tenant_features(cfg.reward)
|
||||
return cache[company_id]
|
||||
|
||||
|
||||
def to_transitions(episodes, feat, tenant_feats):
|
||||
"""학습 규약(train_feature_dqn 과 동일): 중간턴 r=0, 종료턴만 terminal_reward. 다음 후보 = 전체 − 사용분."""
|
||||
all_cards = list(feat.keys())
|
||||
out = []
|
||||
for ep in episodes:
|
||||
tf = tenant_feats[ep["tenant"]]
|
||||
used = set()
|
||||
n = len(ep["steps"])
|
||||
for i, (snap_d, card, _p) in enumerate(ep["steps"]):
|
||||
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||
used.add(card)
|
||||
if i == n - 1:
|
||||
out.append((sf, feat[card], ep["terminal_reward"], None, None, True))
|
||||
else:
|
||||
s2_d = ep["steps"][i + 1][0]
|
||||
s2 = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(s2_d)), tf])
|
||||
cands = [c for c in all_cards if c not in used] or all_cards
|
||||
out.append((sf, feat[card], 0.0, s2, np.stack([feat[c] for c in cands]), False))
|
||||
return out
|
||||
|
||||
|
||||
# ---- ④ OPE (SNIPS, 궤적 단위 IS) ----------------------------------------------
|
||||
def _greedy_match(score_fn, ep, feat, tf) -> float:
|
||||
"""궤적 IS 가중치: Π 1[greedy(sᵢ)=aᵢ]/pᵢ. 한 턴이라도 불일치면 0."""
|
||||
all_cards = list(feat.keys())
|
||||
w, used = 1.0, set()
|
||||
for snap_d, card, p in ep["steps"]:
|
||||
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||
cands = [c for c in all_cards if c not in used] or all_cards
|
||||
sc = score_fn(sf, np.stack([feat[c] for c in cands]))
|
||||
if cands[int(np.argmax(sc))] != card:
|
||||
return 0.0
|
||||
w /= max(p, 1e-3)
|
||||
used.add(card)
|
||||
return w
|
||||
|
||||
|
||||
def snips(score_fn, episodes, feat, tenant_feats):
|
||||
"""SNIPS 추정치 + 유효표본크기(ESS). 매치 0건이면 (None, 0)."""
|
||||
ws, rs = [], []
|
||||
for ep in episodes:
|
||||
w = _greedy_match(score_fn, ep, feat, tenant_feats[ep["tenant"]])
|
||||
ws.append(w)
|
||||
rs.append(ep["terminal_reward"])
|
||||
ws, rs = np.array(ws), np.array(rs)
|
||||
if ws.sum() <= 0:
|
||||
return None, 0.0
|
||||
est = float((ws * rs).sum() / ws.sum())
|
||||
ess = float(ws.sum() ** 2 / (ws ** 2).sum())
|
||||
return est, ess
|
||||
|
||||
|
||||
def np_scorer_from_bundle(path):
|
||||
"""현재 서빙 번들(npz) → score_fn (dqn_store 와 동일 forward)."""
|
||||
z = np.load(path, allow_pickle=False)
|
||||
W0, b0, W1, b1, W2, b2 = z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"]
|
||||
|
||||
def score(sf, card_feats):
|
||||
x = np.concatenate([np.repeat(sf[None, :], card_feats.shape[0], axis=0), card_feats], axis=1)
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
return (h @ W2.T + b2).squeeze(-1)
|
||||
return score
|
||||
|
||||
|
||||
# ---- 메인 ---------------------------------------------------------------------
|
||||
async def run():
|
||||
numbers, feat, _ = load_cards()
|
||||
rows = await fetch_logs()
|
||||
episodes, skipped = build_episodes(rows, set(numbers))
|
||||
print(f"로그 {len(rows)}행 → 에피소드 {len(episodes)}개 (스킵: {dict(skipped) or '없음'})")
|
||||
|
||||
report = dict(rows=len(rows), episodes=len(episodes), skipped=dict(skipped),
|
||||
min_episodes=MIN_EPISODES, deployed=False)
|
||||
if len(episodes) < MIN_EPISODES and not FORCE_DEPLOY:
|
||||
print(f"[skip] 에피소드 {len(episodes)} < MIN_EPISODES {MIN_EPISODES} — 과적합 위험으로 재학습 안 함")
|
||||
report["result"] = "skipped_insufficient_data"
|
||||
return report
|
||||
|
||||
loader = TenantConfigLoader()
|
||||
tenant_feats = {}
|
||||
for ep in episodes:
|
||||
tenant_feat_for(tenant_feats, loader, ep["tenant"])
|
||||
|
||||
# ③ fine-tune (시뮬 사전학습 체크포인트에서 이어서, 낮은 lr)
|
||||
transitions = to_transitions(episodes, feat, tenant_feats)
|
||||
batch = min(64, max(8, len(transitions) // 4))
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=feat[numbers[0]].shape[0], lr=LR, batch_size=batch)
|
||||
if os.path.exists(CKPT_PATH):
|
||||
policy.load(CKPT_PATH)
|
||||
print(f"[fine-tune] 시작점: {os.path.basename(CKPT_PATH)} lr={LR} batch={batch}")
|
||||
policy.buf.extend(transitions)
|
||||
steps = EPOCHS * max(1, len(transitions) // batch)
|
||||
losses = [l for _ in range(steps) if (l := policy.train_step()) is not None]
|
||||
print(f"[fine-tune] {steps} step loss {losses[0]:.4f} → {losses[-1]:.4f}" if losses else "[fine-tune] 스텝 없음")
|
||||
|
||||
# ④ OPE 게이트: 후보 vs 현재 서빙
|
||||
def cand_score(sf, cf):
|
||||
return policy.scores(sf, cf)
|
||||
cand_est, cand_ess = snips(cand_score, episodes, feat, tenant_feats)
|
||||
cur_est, cur_ess = (snips(np_scorer_from_bundle(OUT_PATH), episodes, feat, tenant_feats)
|
||||
if os.path.exists(OUT_PATH) else (None, 0.0))
|
||||
print(f"[OPE/SNIPS] 후보 {cand_est} (ESS {cand_ess:.1f}) vs 현재 {cur_est} (ESS {cur_ess:.1f})")
|
||||
report.update(ope_candidate=cand_est, ope_candidate_ess=cand_ess,
|
||||
ope_current=cur_est, ope_current_ess=cur_ess)
|
||||
|
||||
min_ess = max(3.0, 0.02 * len(episodes))
|
||||
passed = (cand_est is not None and cand_ess >= min_ess
|
||||
and (cur_est is None or cand_est >= cur_est - 0.01))
|
||||
if not passed and not FORCE_DEPLOY:
|
||||
print(f"[게이트 불통과] 배포하지 않음 (필요 ESS ≥ {min_ess:.1f}). 현재 번들 유지.")
|
||||
report["result"] = "gate_failed"
|
||||
return report
|
||||
|
||||
# ⑤ 배포: 후보 저장 + 번들 교체 (.prev 백업)
|
||||
policy.save(RETRAIN_CKPT)
|
||||
path = export_bundle(policy.q.state_dict(), OUT_PATH)
|
||||
print(f"[배포] {path} (직전본 → dqn_serving.npz.prev)")
|
||||
print(" 적용: docker compose build agent && docker compose up -d agent")
|
||||
report.update(result="deployed" if passed else "force_deployed", deployed=True,
|
||||
ckpt=os.path.abspath(RETRAIN_CKPT))
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
report = asyncio.run(run())
|
||||
with open(REPORT_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
print(f"[리포트] {os.path.abspath(REPORT_PATH)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,317 @@
|
||||
"""결함 회귀 게이트 — 실전에서 발견된 협상 결함을 시나리오로 재생해 서빙 번들을 검증한다.
|
||||
|
||||
프로브(probe_serving_dqn)가 '눈으로 보는 행동 표'라면 이것은 '자동 합격/불합격'이다.
|
||||
모든 검사 항목은 과거 실제 발생했던 결함이며, 하나라도 실패하면 exit 1 — 배포 금지.
|
||||
재학습 번들은 반드시 이 게이트를 통과한 뒤에만 autonomy_serving.npz 로 교체한다.
|
||||
|
||||
검사 대상은 서빙 실물이다: AutonomyPolicy.decide(봉투 마스크 포함) + ChatEngine._autonomy_next
|
||||
(최종제안 전환) + ment_generator 가드(목표가 누설·할루시네이션). 시뮬 협력사는 스크립트라
|
||||
결정론적이고, 정책도 greedy 라 실행마다 같은 결과가 나온다. DB/LLM/도커 불필요.
|
||||
|
||||
지형은 복수로 검사한다 — v3.4 가 실스케일(423,198)에선 통과하고 드라이브 지형(10,000)에서
|
||||
'첫 턴 목표가 통보'로 퇴화했던 사고: 한 지형 통과는 다른 지형을 보증하지 않는다.
|
||||
|
||||
실행: agent 디렉터리에서 APP_ENV=local python -m tools.test_autonomy_defects [번들경로]
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.chat.service import ment_generator
|
||||
from negotiation.chat.service.chat_engine import ChatEngine
|
||||
from negotiation.policy import autonomy_store
|
||||
from negotiation.policy.autonomy_store import AutonomyPolicy
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
# 검사 지형: 실제 견적(앵커율 ~1%) + 로컬 드라이브 견적(소액) — 스케일이 달라도 예절은 같아야 한다.
|
||||
GEOS = {
|
||||
"실스케일": dict(anchor=418_966, target=423_198, first=540_000, il=459_000),
|
||||
"소액": dict(anchor=9_900, target=10_000, first=11_500, il=0),
|
||||
}
|
||||
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||
|
||||
_RESULTS = []
|
||||
|
||||
|
||||
def check(name: str, ok: bool, detail: str = ""):
|
||||
_RESULTS.append((name, ok, detail))
|
||||
print(f" {'✔' if ok else '✘ FAIL'} {name}" + (f" — {detail}" if detail and not ok else ""))
|
||||
|
||||
|
||||
# ---- 하니스: 서빙 실물 구동 (chat_service 의 ctx 관리 순서를 그대로 재현) ----------------
|
||||
def base_ctx(geo) -> dict:
|
||||
return dict(revenue_amount=50_000_000, distribution_code="A", partner_count=3,
|
||||
item_price=geo["first"], input_price=geo["first"], round=1,
|
||||
anchor_price=geo["anchor"], target_price=geo["target"],
|
||||
internet_lowest_price=geo["il"])
|
||||
|
||||
|
||||
def run_scenario(policy, supplier, geo, max_steps=30):
|
||||
"""정책 결정 → 스텝 전환 → 컨텍스트 부기(chat_service 순서) → 스크립트 협력사 반응 루프.
|
||||
|
||||
trace 원소: (step, kind, q, 당시 제시가, autonomy_offer, 결정 시점 press_n)
|
||||
"""
|
||||
eng = ChatEngine.__new__(ChatEngine) # _autonomy_next 는 decider 와 ctx 만 쓴다
|
||||
ctx = base_ctx(geo)
|
||||
|
||||
def decide(c):
|
||||
act = policy.decide(c)
|
||||
c["autonomy_pending"] = {"kind": act.kind, "q": act.counter_q, "s": act.strategy}
|
||||
return act
|
||||
|
||||
eng.autonomy_decider = decide
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
trace, end = [], None
|
||||
for _ in range(max_steps):
|
||||
press_n_at = int(ctx.get("autonomy_press_n") or 0)
|
||||
step = eng._autonomy_next(sess)
|
||||
pending = ctx.pop("autonomy_pending", None)
|
||||
if pending: # chat_service 부기: pending → last(+prev), 역제안 별도 보존, press 카운터
|
||||
if ctx.get("autonomy_last"):
|
||||
ctx["autonomy_prev"] = ctx["autonomy_last"]
|
||||
ctx["autonomy_last"] = dict(pending)
|
||||
if pending["kind"] == "counter":
|
||||
ctx["autonomy_last_counter"] = dict(pending)
|
||||
if pending["kind"] == "press":
|
||||
ctx["autonomy_press_n"] = press_n_at + 1
|
||||
trace.append((step, (pending or {}).get("kind"), (pending or {}).get("q"),
|
||||
ctx["input_price"], ctx.get("autonomy_offer"), press_n_at))
|
||||
if step in ("협상완료", "협상실패"):
|
||||
end = step
|
||||
break
|
||||
if step == "자율_최종제안": # 예→그 금액 타결 / 아니오→협상실패 (엔진 스텝 정의)
|
||||
end = "협상완료" if supplier.final_yes(ctx) else "협상실패"
|
||||
break
|
||||
if step == "자율_역제안" and supplier.counter_yes(ctx):
|
||||
ctx["input_price"] = ctx["autonomy_offer"]
|
||||
end = "협상완료"
|
||||
break
|
||||
ctx["input_price"] = int(supplier.next_price(ctx))
|
||||
ctx["round"] = ctx.get("round", 1) + 1
|
||||
return trace, end, ctx
|
||||
|
||||
|
||||
def fmt(trace):
|
||||
out = []
|
||||
for step, kind, q, price, offer, _ in trace:
|
||||
s = f"{price:,}→{step}"
|
||||
if kind == "counter":
|
||||
s += f"({offer:,})"
|
||||
out.append(s)
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
# ---- 스크립트 협력사 (결정론, 지형 비율로 정의) -----------------------------------------
|
||||
class Stubborn:
|
||||
"""조금씩 내리지만 하한이 목표가 위(×1.028) — 성사 불가능. 역제안·최종 전부 거절.
|
||||
|
||||
기대 궤적: 설득 ≥2회 → 앵커 이하 개시 → 단조 상향 사다리 → 최종제안(목표가) → 결렬."""
|
||||
def __init__(self, geo):
|
||||
self.floor = int(geo["target"] * 1.028)
|
||||
|
||||
def next_price(self, ctx):
|
||||
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return False
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return False
|
||||
|
||||
|
||||
class HoverNearTarget:
|
||||
"""목표가 +0.19% 고정 — 마무리 국면. 압박이 나오면 안 되는 구간."""
|
||||
def __init__(self, geo):
|
||||
self.price = int(geo["target"] * 1.0019)
|
||||
|
||||
def next_price(self, ctx):
|
||||
return self.price
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return False
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return False
|
||||
|
||||
|
||||
class Dealable:
|
||||
"""4% 씩 내려와 목표가 바로 아래까지 협조 — 성사 가능 케이스."""
|
||||
def __init__(self, geo):
|
||||
self.floor = int(geo["target"] * 0.9995)
|
||||
self.accept_from = geo["anchor"] + 0.4 * (geo["target"] - geo["anchor"])
|
||||
|
||||
def next_price(self, ctx):
|
||||
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return ctx["autonomy_offer"] >= self.accept_from # 목표가 부근 제안은 수락
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return True
|
||||
|
||||
|
||||
# ---- 시나리오 검사 (각 항목 = 과거 실제 결함) -------------------------------------------
|
||||
def assert_defects(tag, trace, end, geo):
|
||||
anchor, target = geo["anchor"], geo["target"]
|
||||
near = target * 1.005
|
||||
# '역제안' 검사는 일반 역제안 스텝만 센다 — 같은 금액 재시도가 자율_최종제안으로 전환된 것은
|
||||
# 반복이 아니라 설계된 최종 통보(제품 결정: 같은 금액 재호출 = 탄약 소진 → 마지막으로 묻고 종료).
|
||||
counters = [(i, t) for i, t in enumerate(trace) if t[0] == "자율_역제안"]
|
||||
presses = [t for t in trace if t[1] == "press"]
|
||||
|
||||
if trace and trace[0][3] > near:
|
||||
check(f"[{tag}] 개시 턴은 설득 (결함: v3.4 첫턴 walk→목표가 통보)",
|
||||
trace[0][1] == "press", f"첫 결정이 {trace[0][1]}")
|
||||
if counters:
|
||||
i0, first = counters[0]
|
||||
check(f"[{tag}] 첫 역제안은 앵커 이하 (결함: 사다리 꼭대기 개시)",
|
||||
first[4] <= anchor, f"첫 역제안 {first[4]:,} > 앵커 {anchor:,}")
|
||||
pressed_before = sum(1 for t in trace[:i0] if t[1] == "press")
|
||||
if first[3] > near: # 마무리 국면은 해금 예외
|
||||
check(f"[{tag}] 역제시 해금 전 설득 ≥{MIN_PRESS}회 (결함: 첫턴 역제시)",
|
||||
pressed_before >= MIN_PRESS, f"설득 {pressed_before}회 만에 역제안")
|
||||
offers = [t[4] for _, t in counters]
|
||||
check(f"[{tag}] 역제안 단조 상향 (결함: 제안 철회 423,198→420,024)",
|
||||
all(b >= a for a, b in zip(offers, offers[1:])), f"철회 발생: {offers}")
|
||||
check(f"[{tag}] 역제안 ≤ 목표가", all(o <= target for o in offers), f"{offers}")
|
||||
check(f"[{tag}] 같은 금액 역제안 반복 없음 (결함: 421,082 반복)",
|
||||
all(b != a for a, b in zip(offers, offers[1:])), f"{offers}")
|
||||
check(f"[{tag}] 마무리 국면(≤목표가×1.005) 압박 없음 (결함: 802원 푼돈 흥정)",
|
||||
all(t[3] > near for t in presses), "목표가 코앞에서 압박")
|
||||
check(f"[{tag}] 목표가 초과 제시가 수락 없음 (결함: 목표가+14% 매입)",
|
||||
not any(t[1] == "accept" and t[3] > target for t in trace), "")
|
||||
finals = [t for t in trace if t[0] == "자율_최종제안"]
|
||||
for f in finals:
|
||||
check(f"[{tag}] 최종제안 금액 = 목표가 (결함: 직전 금액 재사용 60,548)",
|
||||
f[4] == target, f"최종제안 {f[4]:,} ≠ 목표가 {target:,}")
|
||||
# 결렬 의사(walk)로 끝났다면 반드시 최종제안을 거쳤어야 한다 (턴캡 종료는 예외)
|
||||
walked_direct = any(t[1] == "walk" and t[0] == "협상실패" for t in trace)
|
||||
capped = trace and trace[-1][0] == "협상실패" and trace[-1][1] is None
|
||||
check(f"[{tag}] 결렬 전 최종제안 1회 보장 (결함: 최종 의사 확인 없이 종료)",
|
||||
not walked_direct or capped or bool(finals), "walk 즉시 결렬")
|
||||
check(f"[{tag}] 종료 보장 (무한 세션 없음)", end is not None, "max_steps 내 미종료")
|
||||
|
||||
|
||||
# ---- 엔진 단위 검사 (정책 무관 — 전환 로직 자체) ----------------------------------------
|
||||
def engine_unit_tests():
|
||||
print("\n[엔진 전환 로직 단위 검사]")
|
||||
geo = GEOS["실스케일"]
|
||||
target = geo["target"]
|
||||
|
||||
def force(kind, q=0.0, s=3):
|
||||
eng = ChatEngine.__new__(ChatEngine)
|
||||
eng.autonomy_decider = lambda c: SimpleNamespace(kind=kind, counter_q=q, strategy=s)
|
||||
return eng
|
||||
|
||||
# walk → 최종제안(목표가) → 재차 walk → 협상실패
|
||||
ctx = base_ctx(geo)
|
||||
eng = force("walk")
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step1 = eng._autonomy_next(sess)
|
||||
check("walk 1회차 → 자율_최종제안 전환", step1 == "자율_최종제안", f"got {step1}")
|
||||
check("walk 전환 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
step2 = eng._autonomy_next(sess)
|
||||
check("walk 2회차(최종 거절 후) → 협상실패", step2 == "협상실패", f"got {step2}")
|
||||
|
||||
# 같은 q 역제안 반복 → 최종제안(목표가) 전환
|
||||
ctx = base_ctx(geo)
|
||||
ctx["autonomy_last"] = ctx["autonomy_last_counter"] = {"kind": "counter", "q": 0.5, "s": 3}
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step = force("counter", q=0.5)._autonomy_next(sess)
|
||||
check("같은 금액 재역제안 → 자율_최종제안 전환", step == "자율_최종제안", f"got {step}")
|
||||
check("탄약소진 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
|
||||
# 턴 상한 — 캡 종료도 최종제안 보장을 우회하지 않는다
|
||||
ctx = base_ctx(geo)
|
||||
ctx["round"] = 13
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step = force("press")._autonomy_next(sess)
|
||||
check("턴 상한 초과(최종 미실시) → 자율_최종제안", step == "자율_최종제안", f"got {step}")
|
||||
check("턴캡 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
step = force("press")._autonomy_next(sess)
|
||||
check("턴 상한 초과(최종 거절 후) → 협상실패", step == "협상실패", f"got {step}")
|
||||
|
||||
|
||||
# ---- 봉투 마스크 단위 검사 (모델 무관 — 후보 필터 자체) ----------------------------------
|
||||
def envelope_unit_tests(policy):
|
||||
print("\n[봉투 마스크 단위 검사]")
|
||||
geo = GEOS["소액"]
|
||||
ctx = base_ctx(geo) # 설득 0회, 제시가 목표가 위 → 설득만 가능해야 한다
|
||||
act = policy.decide(ctx)
|
||||
check("설득 0회 상태의 결정은 press 만 가능 (walk·counter·accept 잠금)",
|
||||
act.kind == "press", f"got {act.kind}")
|
||||
|
||||
|
||||
# ---- 멘트 가드 검사 (목표가 누설·할루시네이션 — LLM 호출 없음) ---------------------------
|
||||
def ment_guard_tests():
|
||||
print("\n[멘트 가드 검사]")
|
||||
geo = GEOS["실스케일"]
|
||||
target, anchor, il = geo["target"], geo["anchor"], geo["il"]
|
||||
ctx = base_ctx(geo)
|
||||
|
||||
prompt = ment_generator._prompt_for("자율_압박_3", ctx)
|
||||
check("압박 프롬프트에 목표가 숫자 없음 (결함: 목표가 노출 멘트)",
|
||||
str(target) not in prompt.replace(",", ""), "프롬프트가 목표가를 담고 있음")
|
||||
|
||||
leak = f"저희 내부 산정 기준은 {target:,}원입니다. 이 가격에 맞춰 재검토 부탁드립니다."
|
||||
check("목표가 포함 압박 멘트 → 폐기", not ment_generator._guard("자율_압박_3", ctx, leak), "")
|
||||
|
||||
invented = "시장 상황을 고려해 400,000원 수준으로 재검토 부탁드립니다."
|
||||
check("지어낸 금액 멘트 → 폐기 (할루시네이션)",
|
||||
not ment_generator._guard("자율_압박_3", ctx, invented), "")
|
||||
|
||||
ctx2 = dict(ctx, autonomy_offer=anchor)
|
||||
ok_ment = f"내부 검토 결과 {anchor:,}원이면 즉시 진행이 가능합니다. 수락해 주시겠습니까?"
|
||||
check("정상 역제안 멘트(제안가 포함) → 통과",
|
||||
ment_generator._guard("자율_역제안", ctx2, ok_ment), "")
|
||||
no_offer = "말씀하신 조건을 검토했고 조정이 필요합니다. 수락해 주시겠습니까?"
|
||||
check("제안가 없는 역제안 멘트 → 폐기",
|
||||
not ment_generator._guard("자율_역제안", ctx2, no_offer), "")
|
||||
|
||||
ev = f"동일 품목 인터넷 최저가가 {il:,}원으로 확인됩니다. 재검토 부탁드립니다."
|
||||
check("최저가 인용: 근거 있음(수집됨+제시가>최저가) → 허용",
|
||||
ment_generator._guard("자율_압박_1", ctx, ev), "")
|
||||
ctx3 = dict(ctx, internet_lowest_price=0)
|
||||
ev0 = "동일 품목 인터넷 최저가 대비 높은 수준입니다. 재검토 부탁드립니다."
|
||||
check("최저가 인용: 미수집 품목 → 폐기 (지어낸 시장 주장)",
|
||||
not ment_generator._guard("자율_압박_1", ctx3, ev0), "")
|
||||
|
||||
|
||||
def main():
|
||||
bundle = sys.argv[1] if len(sys.argv) > 1 else autonomy_store.BUNDLE_PATH
|
||||
z = np.load(bundle, allow_pickle=False)
|
||||
policy = AutonomyPolicy(z, TenantConfigLoader().load("ktcommerce").reward)
|
||||
print(f"번들: {os.path.abspath(bundle)} (state_dim={int(z['state_dim'])})")
|
||||
|
||||
for geo_name, geo in GEOS.items():
|
||||
print(f"\n{'─' * 60}\n지형 [{geo_name}] 앵커 {geo['anchor']:,} / 목표 {geo['target']:,} "
|
||||
f"/ 첫 제시가 {geo['first']:,}")
|
||||
for tag, sup_cls in (("완고", Stubborn), ("목표가위 고정", HoverNearTarget),
|
||||
("협조", Dealable)):
|
||||
trace, end, _ = run_scenario(policy, sup_cls(geo), geo)
|
||||
full_tag = f"{geo_name}·{tag}"
|
||||
print(f"\n[{full_tag}] {fmt(trace)} ⇒ {end}")
|
||||
assert_defects(full_tag, trace, end, geo)
|
||||
|
||||
engine_unit_tests()
|
||||
envelope_unit_tests(policy)
|
||||
ment_guard_tests()
|
||||
|
||||
fails = [(n, d) for n, ok, d in _RESULTS if not ok]
|
||||
print(f"\n{'=' * 60}\n결과: {len(_RESULTS) - len(fails)}/{len(_RESULTS)} 통과")
|
||||
if fails:
|
||||
print("실패 항목 — 이 번들은 배포 금지:")
|
||||
for n, d in fails:
|
||||
print(f" ✘ {n} {d}")
|
||||
sys.exit(1)
|
||||
print("전 항목 통과 — 배포 가능.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""action-as-feature DQN 학습 (Phase 2·3) — 공용 환경 헬퍼 + 단독 학습 엔트리.
|
||||
|
||||
카드 특징 = 스크립트 임베딩(384) + 전략 one-hot(4) + 톤 one-hot(4) = 392차원
|
||||
상태 특징 = 연속 상태(9) + 고객사 성향(5) = 14차원 ← 협력사·고객사 조건화
|
||||
학습 환경 = FeatureBuyer(양보력/수락력 2축) + 에피소드마다 협력사·고객사성향 랜덤 샘플링
|
||||
|
||||
비교 평가는 tools.compare_qtable_vs_dqn 에서 수행한다.
|
||||
실행: APP_ENV=local python -m tools.train_feature_dqn
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.buyer import Scenario
|
||||
from eval_harness.feature_buyer import FeatureBuyer, sample_supplier
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
EMB_PATH = os.path.join(_HERE, "..", "artifacts", "card_embeddings.npz")
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||
|
||||
# zero-shot 실험용 홀드아웃 (전략 1·4 — 남은 풀에도 같은 전략 존재).
|
||||
# 서빙용 최종 학습은 전체 풀 사용: FULL_POOL=1 python -m tools.train_feature_dqn
|
||||
HOLDOUT = [] if os.getenv("FULL_POOL") == "1" else ["NGC-002", "NGC-010"]
|
||||
ANCHOR, TARGET = 8000.0, 10000.0
|
||||
MAX_TURNS = 5
|
||||
N_STRATEGY, N_TONE = 4, 4
|
||||
|
||||
|
||||
# ---- 카드 특징: 임베딩 + 전략/톤 one-hot ------------------------------------------
|
||||
def load_cards():
|
||||
z = np.load(EMB_PATH, allow_pickle=True)
|
||||
numbers = [str(n) for n in z["numbers"]]
|
||||
feat, strat = {}, {}
|
||||
for i, n in enumerate(numbers):
|
||||
s, t = int(z["strategy"][i]), int(z["tone"][i])
|
||||
s_oh = np.eye(N_STRATEGY, dtype=np.float32)[s - 1]
|
||||
t_oh = np.eye(N_TONE, dtype=np.float32)[t - 1]
|
||||
feat[n] = np.concatenate([z["embeddings"][i].astype(np.float32), s_oh, t_oh])
|
||||
strat[n] = s
|
||||
return numbers, feat, strat
|
||||
|
||||
|
||||
# ---- 고객사 성향: 보상 설정 샘플링 ---------------------------------------------------
|
||||
def sample_tenant_pref(rng: np.random.Generator, base_cfg):
|
||||
"""p ∈ [0,1]: 0=성사중시(협력 유리) ↔ 1=가격중시(경쟁 유리). 반환: (RewardConfig, tenant_feat)."""
|
||||
p = float(rng.uniform(0.0, 1.0))
|
||||
cfg = base_cfg.model_copy(update=dict(
|
||||
max_weight=0.25 + 0.60 * p, # 가격보상 비중
|
||||
min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||
success_reward=1.6 - 1.2 * p, # 성사중시일수록 성공보상↑
|
||||
failure_penalty=-(1.4 - 1.1 * p), # 성사중시일수록 결렬이 아픔
|
||||
beta=0.1 + 0.4 * p,
|
||||
penalty_lambda=float(rng.uniform(0.005, 0.05)),
|
||||
))
|
||||
return cfg, build_tenant_features(cfg)
|
||||
|
||||
|
||||
def pref_config(base_cfg, p: float, lam: float = 0.02):
|
||||
"""평가용: 성향 p 를 고정해 RewardConfig 생성 (극단 테스트)."""
|
||||
return base_cfg.model_copy(update=dict(
|
||||
max_weight=0.25 + 0.60 * p, min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||
success_reward=1.6 - 1.2 * p, failure_penalty=-(1.4 - 1.1 * p),
|
||||
beta=0.1 + 0.4 * p, penalty_lambda=lam,
|
||||
))
|
||||
|
||||
|
||||
def make_snapshot(sup, price: float, turn: int, acceptance: float,
|
||||
outcome=NegotiationOutcome.ONGOING) -> NegotiationSnapshot:
|
||||
return NegotiationSnapshot(
|
||||
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||
partner_count=sup.partner_count, acceptance_ratio=acceptance,
|
||||
input_price=price, anchor_price=ANCHOR, target_price=TARGET,
|
||||
round_number=turn, outcome=outcome,
|
||||
)
|
||||
|
||||
|
||||
# ---- 단독 학습 엔트리 (비교는 compare_qtable_vs_dqn) --------------------------------
|
||||
def main(episodes=10000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
numbers, feat, strat = load_cards()
|
||||
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||
card_dim = feat[numbers[0]].shape[0]
|
||||
print(f"카드 {len(numbers)}장 (학습 {len(train_pool)} / 홀드아웃 {HOLDOUT}) card_dim={card_dim}")
|
||||
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=card_dim, eps_decay=4000, gamma=0.95)
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
print(f"=== 학습 {episodes} 에피소드 (협력사·성향 랜덤, CPU) ===")
|
||||
recent = []
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||
rc = RewardCalculator(rcfg, tcfg.state)
|
||||
buyer = FeatureBuyer(sup, strat, seed=seed * 100 + ep, max_turns=MAX_TURNS)
|
||||
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||
price0 = TARGET * 1.15
|
||||
price, used, total_r = price0, set(), 0.0
|
||||
for turn in range(1, MAX_TURNS + 1):
|
||||
acceptance = max(0.0, (price0 - price) / price0)
|
||||
s = make_snapshot(sup, price, turn, acceptance)
|
||||
sf = np.concatenate([build_state_features(s), tf])
|
||||
avail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||
embs = np.stack([feat[c] for c in avail])
|
||||
i, _, _ = policy.select(sf, embs)
|
||||
card = avail[i]; used.add(card)
|
||||
resp = buyer.respond(card, scenario, turn, price)
|
||||
price = resp.new_price
|
||||
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||
success = resp.accept or price <= ANCHOR
|
||||
outcome = (NegotiationOutcome.SUCCESS if success
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
# 최종 결과 시점만 채점 (중간 0 → γ 부트스트랩) — compare 스크립트와 동일 규칙.
|
||||
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||
total_r += r
|
||||
if done:
|
||||
policy.remember(sf, feat[card], r, None, None, True)
|
||||
else:
|
||||
acc2 = max(0.0, (price0 - price) / price0)
|
||||
s2 = make_snapshot(sup, price, turn + 1, acc2)
|
||||
navail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||
policy.remember(sf, feat[card], r, np.concatenate([build_state_features(s2), tf]),
|
||||
np.stack([feat[c] for c in navail]), False)
|
||||
policy.train_step()
|
||||
if done:
|
||||
break
|
||||
recent.append(total_r)
|
||||
if ep % 2000 == 0:
|
||||
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근2000 평균보상={np.mean(recent[-2000:]):.4f}")
|
||||
|
||||
policy.save(CKPT_PATH)
|
||||
print(f"[저장] {CKPT_PATH}")
|
||||
return policy
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,365 @@
|
||||
"""train_full_autonomy — 행동 룰 0개, 완전 자율 협상 에이전트 (v2 시뮬 프로토타입).
|
||||
|
||||
기존 시스템의 룰(앵커 이하 강제타결 / 3라운드 강제결렬 / 와일드카드 존 / 카드 카탈로그)을
|
||||
전부 제거하고, 모든 결정을 에이전트 행동으로 이관한다:
|
||||
|
||||
행동 공간 (action-as-feature, ScoreNet 이 후보 열거 채점):
|
||||
ACCEPT 현재 제시가로 타결 ← '앵커 이하 강제타결' 룰 대체
|
||||
WALK 협상 결렬 선언 ← '3라운드 강제결렬' 룰 대체
|
||||
COUNTER(C) "C원이면 수락" 역제안 ← '와일드카드 1%' 룰 대체 (금액도 학습)
|
||||
PRESS(strategy) 설득 압박(카드의 일반화) ← 카드 카탈로그 대체 (전략만 남음)
|
||||
|
||||
룰이 사라진 자리는 보상이 채운다(유일한 스펙):
|
||||
R = W×R_price + (1−W)×R_end − λ×round (기존 RewardCalculator 그대로)
|
||||
협상이 끝나는 길: 에이전트의 ACCEPT/WALK, 협력사의 COUNTER 수락, 협력사의 인내심 소진(이탈).
|
||||
마지막 것은 시스템 룰이 아니라 상대방 특성이다.
|
||||
|
||||
베이스라인 = 현행 룰 시스템을 같은 환경에서 재현(앵커타결/1%클로징/3라운드결렬 + 압박).
|
||||
|
||||
실행: APP_ENV=local PYTHONUTF8=1 python -m tools.train_full_autonomy
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.feature_buyer import AFFINITY, STRATEGY_PROFILE, SupplierProfile, sample_supplier
|
||||
from negotiation.policies.autonomy_actions import (
|
||||
ACTION_DIM, ACTIONS, COUNTER_GRID, EXTRA_STATE_DIM, Action, extra_state,
|
||||
internet_gap_feat, settle_norm as extra_settle)
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.train_feature_dqn import pref_config, sample_tenant_pref
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||
|
||||
TARGET = 10000.0
|
||||
# 앵커율(v3.1): 실운영 기하 정합 — 앵커가 = 목표가×(1−a), a ∈ [0.8%, 6%] 를 에피소드마다 샘플링.
|
||||
# (기존 고정 20% 폭은 실제(≈1%)와 지형이 달라, 실서비스에서 압박/역제안 밸런스가 어긋났다.)
|
||||
ANCHOR_RATE_RANGE = (0.008, 0.06)
|
||||
# 행동 공간(Action/ACTIONS/COUNTER_GRID/ACTION_DIM)은 negotiation.policies.autonomy_actions 공유
|
||||
# — 서빙(autonomy_store, numpy 전용)과 학습이 같은 인코딩을 쓴다.
|
||||
|
||||
|
||||
# ---- 협력사 모델 (상대 반응: 역제안 수락/재제안 포함) ---------------------------------
|
||||
class AutonomousBuyer:
|
||||
"""FeatureBuyer 확장: 역제안(C)에 반응한다. 이탈은 '인내심' — 시스템 룰이 아닌 상대 특성."""
|
||||
|
||||
def __init__(self, sup: SupplierProfile, seed: int):
|
||||
self.sup = sup
|
||||
self.rng = np.random.default_rng(seed)
|
||||
# 기질 t ∈ [0,1]: 0=터프(하한 높고 안 물러섬) ↔ 1=수월. 관측 가능한 이력·최저가가
|
||||
# 이 숨은 기질과 상관되게 생성된다 → 에이전트가 이력/최저가 특징을 읽을 '이유'가 생긴다.
|
||||
# 하한은 '우리 앵커'가 아니라 협력사 사정(≈목표가 기준)으로 정해진다(v3.1) —
|
||||
# 하한 > 목표가(≈35%)면 애초에 성사 불가능한 협상이고, 그걸 빨리 알아채고 끊는 것도 실력이다.
|
||||
t = float(self.rng.uniform(0.0, 1.0))
|
||||
self.floor = TARGET * float(np.clip(1.12 - 0.24 * t + self.rng.normal(0, 0.02), 0.85, 1.18))
|
||||
self.patience = int(self.rng.integers(4, 9)) + (1 if t > 0.7 else 0)
|
||||
# 첫 제시가: 목표가의 105~150% — 실운영(기존 공급가가 목표가를 26%+ 상회) 분포를 덮는다.
|
||||
# 좁게(110~125%) 학습하면 큰 갭 상황에서 정책이 분포 밖 일반화(대형컷 역제안)를 한다.
|
||||
self.price = TARGET * float(self.rng.uniform(1.05, 1.50))
|
||||
# 하한가가 첫 제시가보다 높을 수 없다(자기 하한 밑으로 부르고 시작하는 판매자는 없음).
|
||||
# 이 보정이 없으면 on_press 의 max(floor,·)가 가격을 '역주행'시키는 비현실이 생긴다.
|
||||
self.floor = min(self.floor, self.price * 0.98)
|
||||
self._last_c: Optional[float] = None # 직전 역제안 (같은 숫자 반복 짜증 모델링)
|
||||
# ---- 관측 가능 부가정보 (v3 특징 소스 — 기질과 상관, 노이즈 있음) ----
|
||||
self.hist_n = int(self.rng.integers(0, 6)) # 과거 협상 횟수 (0=신규)
|
||||
if self.hist_n:
|
||||
self.hist_success = float(np.clip(0.25 + 0.6 * t + self.rng.normal(0, 0.10), 0.0, 1.0))
|
||||
self.hist_settle_ratio = float(np.clip(1.18 - 0.28 * t + self.rng.normal(0, 0.04), 0.80, 1.30))
|
||||
else:
|
||||
self.hist_success = self.hist_settle_ratio = None
|
||||
# 인터넷최저가: 숨은 하한가의 노이즈 관측치. 60% 확률로만 수집돼 있음(현실: 미수집 흔함).
|
||||
self.internet_lowest = (self.floor * float(self.rng.uniform(0.98, 1.08))
|
||||
if self.rng.random() < 0.6 else None)
|
||||
|
||||
def _powers(self, strategy: int) -> Tuple[float, float]:
|
||||
conc, acc = STRATEGY_PROFILE.get(strategy, (0.5, 0.5))
|
||||
m = AFFINITY[self.sup.segment].get(strategy, 0.5)
|
||||
scale = 0.35 + 0.85 * m
|
||||
return conc * scale, acc * scale
|
||||
|
||||
def on_press(self, strategy: int, turn: int) -> Tuple[bool, float]:
|
||||
"""(이탈여부, 새 제시가). 압박이 안 먹히는 세그먼트면 이탈 위험이 실재한다."""
|
||||
c_pow, a_pow = self._powers(strategy)
|
||||
walk_p = 0.04 + 0.30 * (1.0 - a_pow) * (turn / self.patience)
|
||||
if self.rng.random() < walk_p:
|
||||
return True, self.price
|
||||
concession = (self.price - self.floor) * (0.10 + 0.55 * c_pow)
|
||||
self.price = max(self.floor, self.price - concession)
|
||||
return False, self.price
|
||||
|
||||
def on_counter(self, c: float, strategy: int, turn: int) -> Tuple[str, float]:
|
||||
"""역제안 C 반응: 'accept'(C로 타결) | 'walk' | 'counter'(새 제시가).
|
||||
|
||||
현실화(v2): 현 제시가 대비 인하 요구폭(cut)이 클수록 수락률이 급감하고 이탈 위험이 커진다
|
||||
— 초기 버전에서 에이전트가 't1 원샷 로우볼'로 시뮬 허점을 착취하던 것을 막는다.
|
||||
압박으로 가격을 충분히 끌어내린 뒤 작은 컷으로 클로징해야 통하는 구조.
|
||||
"""
|
||||
_, a_pow = self._powers(strategy or 3)
|
||||
cut = max(0.0, (self.price - c) / max(self.price, 1.0)) # 인하 요구폭 (현 제시가 대비)
|
||||
prev_c = self._last_c
|
||||
repeated = prev_c is not None and abs(c - prev_c) < 1e-6 # 같은 숫자 반복
|
||||
self._last_c = c
|
||||
# 양보 상호성(v3.3): 직전 제안보다 올려 부르면(성의 있는 양보) 호의적으로 반응한다.
|
||||
# 이 신호가 있어야 '상대가 내리면 우리도 조금 올리는' tit-for-tat 이 학습으로 나온다.
|
||||
warm = 0.0
|
||||
if prev_c is not None and c > prev_c + 1e-9:
|
||||
warm = float(np.clip((c - prev_c) / max(self.price - self.floor, 1.0), 0.0, 0.35))
|
||||
if c >= self.floor:
|
||||
margin = (c - self.floor) / max(self.floor, 1.0)
|
||||
p_acc = float(np.clip(0.20 + 0.9 * margin / 0.08, 0.0, 0.95)) * (0.75 + 0.35 * a_pow)
|
||||
p_acc *= float(np.clip(1.0 - (cut - 0.05) / 0.20, 0.0, 1.0)) # 컷 5% 초과부터 반발, 25%면 수락 0
|
||||
if repeated:
|
||||
p_acc *= 0.25 # 이미 거절한 숫자를 또 내밀면 설득력 급감
|
||||
p_acc *= 1.0 + warm
|
||||
if self.rng.random() < min(p_acc, 0.97):
|
||||
return "accept", c
|
||||
# 모욕적 요구(하한 미달·과도한 원샷 컷·앵무새 반복) → 이탈 위험
|
||||
low = max(0.0, (self.floor - c) / max(self.floor, 1.0))
|
||||
p_walk = min(0.5, 2.0 * low) + 0.35 * max(0.0, cut - 0.20) / 0.20 + (0.15 if repeated else 0.0)
|
||||
if self.rng.random() < min(p_walk * (1.0 - warm), 0.7):
|
||||
return "walk", self.price
|
||||
self.price = max(self.floor, c + (self.price - c) * float(self.rng.uniform(0.30, 0.60) + warm))
|
||||
return "counter", self.price
|
||||
|
||||
|
||||
# ---- 에피소드 실행 (룰 없음 — 종료는 행동 또는 상대 특성으로만) ------------------------
|
||||
def make_snapshot(sup, price, turn, p0, anchor, outcome=NegotiationOutcome.ONGOING):
|
||||
return NegotiationSnapshot(
|
||||
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||
partner_count=sup.partner_count, acceptance_ratio=max(0.0, (p0 - price) / p0),
|
||||
input_price=price, anchor_price=anchor, target_price=TARGET,
|
||||
round_number=turn, outcome=outcome)
|
||||
|
||||
|
||||
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2")) # 역제시 해금에 필요한 최소 설득 횟수
|
||||
|
||||
|
||||
def available_actions(price: float, last_counter_q: Optional[float] = None,
|
||||
counter_locked: bool = False) -> list:
|
||||
"""행동 봉투 (serving autonomy_store 와 동일해야 한다):
|
||||
① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(목표가 초과 수락 착취 방지)
|
||||
② 직전 역제안 미만 금액의 역제안 제외 — 단조 양보 원칙(제안 철회 금지;
|
||||
양보 '속도'는 정책이 배우고, 후퇴 '금지'만 구조로 보장)
|
||||
③ counter_locked: 설득 MIN_PRESS 회 전에는 역제시 잠금 — 옛 제품 의미론
|
||||
(일반 카드=설득, 역제시=와일드카드 성격의 마무리 수단) 복원
|
||||
④ 마무리 국면(제시가 ≤ 목표가×1.005): 압박 제외 — 푼돈 차이에서 재검토 요청 반복 방지
|
||||
⑤ 첫 역제안은 앵커 이하(q ≤ 0)만 — 낮게 개시해 사다리를 다 쓰며 올라간다"""
|
||||
near_target = price <= TARGET * 1.005
|
||||
return [a for a in ACTIONS
|
||||
if not (a.kind == "accept" and price > TARGET)
|
||||
and not (a.kind == "counter" and counter_locked and not near_target)
|
||||
and not (a.kind == "walk" and counter_locked and not near_target)
|
||||
and not (a.kind == "press" and near_target)
|
||||
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||
and not (a.kind == "counter" and last_counter_q is not None
|
||||
and a.counter_q < last_counter_q - 1e-9)]
|
||||
|
||||
|
||||
def action_feats(price: float, anchor: float, last_counter_q: Optional[float] = None,
|
||||
counter_locked: bool = False):
|
||||
"""현 제시가 기준 (가용 행동 리스트, 특징 [K, ACTION_DIM]). counter 는 컷폭 포함."""
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
pos = (price - anchor) / span
|
||||
acts = available_actions(price, last_counter_q, counter_locked)
|
||||
rows = []
|
||||
for a in acts:
|
||||
cut = 0.0
|
||||
if a.kind == "counter":
|
||||
c = anchor + a.counter_q * span
|
||||
cut = max(0.0, (price - c) / max(price, 1.0))
|
||||
rows.append(a.feat(pos, cut))
|
||||
return acts, np.stack(rows)
|
||||
|
||||
|
||||
def run_episode(policy_fn, sup, rc: RewardCalculator, tf: np.ndarray, seed: int,
|
||||
learner: Optional[FeatureDQNPolicy] = None, trace: Optional[list] = None):
|
||||
"""policy_fn(state_feat, price_pos) → Action. learner 지정 시 replay 저장+학습."""
|
||||
buyer = AutonomousBuyer(sup, seed)
|
||||
p0 = buyer.price
|
||||
env_rng = np.random.default_rng(seed + 7)
|
||||
# 앵커율 샘플링(v3.1): 실운영처럼 앵커가 목표가 바로 아래(0.8~6%) — 좁은 스팬 지형에서 학습.
|
||||
anchor = TARGET * (1.0 - float(env_rng.uniform(*ANCHOR_RATE_RANGE)))
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
turn, settled, walked = 0, None, False
|
||||
last_kind, last_q = "", 0.0 # 직전 역제안 기억 (같은 숫자 반복 방지의 학습 근거)
|
||||
press_n = 0 # 설득 횟수 — 역제시 해금(MIN_PRESS) 카운터
|
||||
# 견적 마감(환경 사실): 마감 도달 시 협상은 미타결 종료된다 — 룰이 아니라 세상의 시계.
|
||||
deadline_turns = int(env_rng.integers(3, 11))
|
||||
# 관측성 마스크(v3.5): 실서빙은 마감·이력·최저가가 '없는' 세션이 흔하고 로더가 중립값
|
||||
# (0.5/0)을 대입한다. 시뮬이 항상 다 아는 세계만 학습하면 그 중립 상태가 분포 밖이 된다
|
||||
# — v3.4 가 라이브 소액 지형에서 첫 턴 결렬로 퇴화한 원인 추정. 세계(마감 종료·상대 특성)는
|
||||
# 그대로 두고 관측만 가린다: 마감은 40% 미관측(0.5 고정), 15% 는 전부 미상(신규 견적의 전형).
|
||||
deadline_known = env_rng.random() < 0.6
|
||||
blind = env_rng.random() < 0.15
|
||||
if blind:
|
||||
deadline_known = False
|
||||
# 협력사 이력·최저가 특징 (에피소드 내 불변)
|
||||
known_hist = buyer.hist_n and not blind
|
||||
fixed_extra = dict(
|
||||
hist_n=min(buyer.hist_n, 5) / 5.0 if not blind else 0.0,
|
||||
hist_success=buyer.hist_success if known_hist else 0.5,
|
||||
hist_settle=extra_settle(buyer.hist_settle_ratio) if known_hist else 0.5,
|
||||
internet_gap=internet_gap_feat(buyer.internet_lowest or 0.0, anchor) if not blind else 0.0,
|
||||
)
|
||||
pending = None # (state_feat, action_feat) — 최종 결과 시점만 채점, 중간 r=0
|
||||
|
||||
while True:
|
||||
turn += 1
|
||||
price = buyer.price
|
||||
deadline_remain = (max(0.0, (deadline_turns - turn + 1) / deadline_turns)
|
||||
if deadline_known else 0.5) # 미관측 → 서빙 로더와 동일한 중립값
|
||||
sf = np.concatenate([build_state_features(make_snapshot(sup, price, turn, p0, anchor)), tf,
|
||||
extra_state(last_kind, last_q, deadline=deadline_remain, **fixed_extra)])
|
||||
lcq = last_q if last_kind == "counter" else None
|
||||
locked = lcq is None and press_n < MIN_PRESS
|
||||
act = policy_fn(sf, price, anchor, lcq, locked)
|
||||
if trace is not None:
|
||||
trace.append((turn, int(price), act))
|
||||
|
||||
if act.kind == "accept":
|
||||
settled = price
|
||||
elif act.kind == "walk":
|
||||
walked = True
|
||||
elif act.kind == "counter":
|
||||
c = anchor + act.counter_q * span
|
||||
resp, val = buyer.on_counter(c, act.strategy, turn)
|
||||
last_kind, last_q = "counter", act.counter_q # 역제안 기억 갱신
|
||||
if resp == "accept":
|
||||
settled = c
|
||||
elif resp == "walk":
|
||||
walked = True
|
||||
else: # press
|
||||
press_n += 1
|
||||
left, _ = buyer.on_press(act.strategy, turn)
|
||||
walked = walked or left
|
||||
if not settled and not walked and turn >= buyer.patience:
|
||||
walked = True # 인내심 소진(상대 특성) — 시스템 룰 아님
|
||||
if not settled and not walked and turn >= deadline_turns:
|
||||
walked = True # 견적 마감 도달(환경 사실) — 미타결 종료
|
||||
|
||||
done = settled is not None or walked
|
||||
final_price = settled if settled is not None else buyer.price
|
||||
# 성사 보너스는 목표가 이하 타결에만 — v3.1 이 '비싸게라도 성사'로 착취한 보상 구멍의
|
||||
# 원인 차단(봉투 ① 의 마스크와 이중 방어: 유인 자체를 올바르게). 초과 타결 = 결렬 취급.
|
||||
outcome = (NegotiationOutcome.SUCCESS if settled is not None and settled <= TARGET
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
r = rc.calculate(make_snapshot(sup, final_price, turn, p0, anchor, outcome)).total if done else 0.0
|
||||
|
||||
if learner is not None:
|
||||
pos = (price - anchor) / span
|
||||
cut = 0.0
|
||||
if act.kind == "counter":
|
||||
cut = max(0.0, (price - (anchor + act.counter_q * span)) / max(price, 1.0))
|
||||
af = act.feat(pos, cut)
|
||||
if pending:
|
||||
nxt_lcq = last_q if last_kind == "counter" else None
|
||||
learner.remember(*pending, 0.0, sf,
|
||||
action_feats(price, anchor, nxt_lcq,
|
||||
nxt_lcq is None and press_n < MIN_PRESS)[1], False)
|
||||
pending = (sf, af)
|
||||
if done:
|
||||
learner.remember(sf, af, r, None, None, True)
|
||||
learner.train_step()
|
||||
if done:
|
||||
return settled, turn, r
|
||||
|
||||
|
||||
# ---- 정책들 ------------------------------------------------------------------
|
||||
def dqn_policy(policy: FeatureDQNPolicy):
|
||||
def f(sf, price, anchor, last_counter_q=None, counter_locked=False):
|
||||
acts, feats = action_feats(price, anchor, last_counter_q, counter_locked)
|
||||
i, _, _ = policy.select(sf, feats)
|
||||
return acts[i]
|
||||
return f
|
||||
|
||||
|
||||
class RuleBaseline:
|
||||
"""현행 시스템 룰 재현: 앵커 이하 수락 / 존내 1% 클로징 / 3회 압박 후 결렬."""
|
||||
|
||||
def __init__(self):
|
||||
self.presses, self.closed = 0, False
|
||||
|
||||
def __call__(self, sf, price, anchor, last_counter_q=None, counter_locked=False) -> Action:
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
if price <= anchor:
|
||||
return Action("accept")
|
||||
if price <= anchor * 1.02 and not self.closed:
|
||||
self.closed = True
|
||||
return Action("counter", (price * 0.99 - anchor) / span, 3)
|
||||
if self.presses < 3:
|
||||
self.presses += 1
|
||||
return Action("press", 0.0, 3)
|
||||
return Action("walk")
|
||||
|
||||
|
||||
# ---- 학습/평가 ----------------------------------------------------------------
|
||||
def evaluate(name, make_policy_fn, base_cfg, tcfg_state, episodes=3000, seed0=777):
|
||||
rc = RewardCalculator(pref_config(base_cfg, 0.5), tcfg_state)
|
||||
tf = build_tenant_features(pref_config(base_cfg, 0.5))
|
||||
rng = np.random.default_rng(seed0)
|
||||
rewards, settles, rounds = [], [], []
|
||||
for i in range(episodes):
|
||||
sup = sample_supplier(rng)
|
||||
settled, turn, r = run_episode(make_policy_fn(), sup, rc, tf, seed0 * 91 + i)
|
||||
rewards.append(r)
|
||||
rounds.append(turn)
|
||||
if settled is not None:
|
||||
settles.append(settled / TARGET)
|
||||
sr = len(settles) / episodes
|
||||
print(f"{name:<14} 보상 {np.mean(rewards):.4f} ±{np.std(rewards)/np.sqrt(episodes):.4f}"
|
||||
f" 성사율 {sr:.3f} 타결가/목표 {np.mean(settles):.3f} 평균라운드 {np.mean(rounds):.2f}")
|
||||
return dict(reward=float(np.mean(rewards)), success=sr,
|
||||
settle_ratio=float(np.mean(settles)) if settles else None, rounds=float(np.mean(rounds)))
|
||||
|
||||
|
||||
def main(episodes=15000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM,
|
||||
card_dim=ACTION_DIM, eps_decay=5000, gamma=0.97)
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
print(f"=== 완전 자율 학습 {episodes}ep (행동 {len(ACTIONS)}개, 룰 0개) ===")
|
||||
recent = []
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||
rc = RewardCalculator(rcfg, tcfg.state)
|
||||
_, _, r = run_episode(dqn_policy(policy), sup, rc, tf, seed * 131 + ep, learner=policy)
|
||||
recent.append(r)
|
||||
if ep % 3000 == 0:
|
||||
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근3000 평균보상={np.mean(recent[-3000:]):.4f}")
|
||||
policy.save(CKPT_PATH)
|
||||
|
||||
print("\n=== 평가 3000ep (중립 성향 p=0.5, 동일 협력사 분포) ===")
|
||||
policy.greedy = True
|
||||
evaluate("룰시스템(현행)", lambda: RuleBaseline(), tcfg.reward, tcfg.state)
|
||||
evaluate("완전자율 DQN", lambda: dqn_policy(policy), tcfg.reward, tcfg.state)
|
||||
|
||||
# 궤적 예시 — 에이전트가 룰 없이 뭘 하는지 눈으로
|
||||
print("\n=== 궤적 예시 (완전자율) ===")
|
||||
rc = RewardCalculator(pref_config(tcfg.reward, 0.5), tcfg.state)
|
||||
tf = build_tenant_features(pref_config(tcfg.reward, 0.5))
|
||||
rng2 = np.random.default_rng(7)
|
||||
for k in range(3):
|
||||
sup = sample_supplier(rng2)
|
||||
trace = []
|
||||
settled, turn, r = run_episode(dqn_policy(policy), sup, rc, tf, 5000 + k, trace=trace)
|
||||
seg = "·".join(sup.segment)
|
||||
print(f"[{seg}] " + " → ".join(
|
||||
f"t{t}:{p:,}원 {a.kind}{'' if a.kind in ('accept', 'walk') else f'({a.counter_q:.2f},전략{a.strategy})' if a.kind == 'counter' else f'(전략{a.strategy})'}"
|
||||
for t, p, a in trace) + f" ⇒ {'타결 ' + format(int(settled), ',') + '원' if settled else '결렬'} (r={r:.3f})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user