World-Model / wm_bench_scoring.py
SeaWolf-AI's picture
Upload 2 files
d6b962e verified
"""
World Model Bench — Quantitative Scoring Specification v1.0
설계 원칙:
1. 모든 점수는 정량적 — 주관적 판단 0%
2. 제3자 재현 가능 — 동일 입력 → 동일 점수
3. 자동 채점 — 코드가 판정, 사람이 판정 안 함
4. 반박 불가 — 각 점수에 수학적/논리적 근거
핵심 메커니즘:
- 모든 시나리오는 "입력(scene_context) → 출력(PREDICT+MOTION)" 쌍
- 채점은 출력 텍스트를 파싱하여 정량 지표로 변환
- 파싱 규칙이 명시적이므로 누가 해도 동일 결과
"""
import json
import re
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
from enum import IntEnum
# ═══════════════════════════════════════════════════════════════
# SECTION 1: 출력 포맷 정의 (채점의 전제 조건)
# ═══════════════════════════════════════════════════════════════
"""
모든 월드모델은 아래 포맷으로 출력해야 채점 가능:
INPUT (시스템이 제공):
scene_context = {
"walls": {"left": float, "right": float, "front": float}, # 거리(m), null=없음
"ground": str, # "flat", "slope", "stairs"
"npc_nearby": bool,
"npc_type": str|null, # "beast", "woman", "man", null
"npc_behavior": str|null, # "stop", "approach", "charge", "wander"
"npc_distance": float|null,
"sound": str|null, # "aggressive growling", "footsteps", null
}
OUTPUT (모델이 출력):
Line 1: PREDICT: left=safe|danger(reason), right=..., fwd=..., back=...
Line 2: MOTION: a person [max 12 words describing action]
채점은 이 두 줄을 파싱하여 수행.
"""
# ═══════════════════════════════════════════════════════════════
# SECTION 2: 파서 — 출력 텍스트를 구조화된 데이터로 변환
# ═══════════════════════════════════════════════════════════════
class PredictDirection:
"""PREDICT 줄의 한 방향을 파싱한 결과"""
def __init__(self, raw: str):
self.raw = raw.strip()
self.is_safe = "safe" in self.raw.lower()
self.is_danger = "danger" in self.raw.lower()
# 괄호 안의 이유 추출: danger(wall) → "wall"
match = re.search(r'\(([^)]+)\)', self.raw)
self.reason = match.group(1).lower() if match else None
def parse_predict_line(line: str) -> Dict[str, PredictDirection]:
"""
PREDICT: left=safe(open), right=danger(wall), fwd=danger(beast), back=safe
→ {"left": PredictDirection, "right": ..., "fwd": ..., "back": ...}
"""
result = {}
line = line.replace("PREDICT:", "").strip()
for part in line.split(","):
part = part.strip()
if "=" not in part:
continue
key, val = part.split("=", 1)
key = key.strip().lower()
# 정규화: left/right/fwd/forward/back/backward
if key in ("forward", "fwd", "front"):
key = "fwd"
if key in ("backward", "back"):
key = "back"
result[key] = PredictDirection(val)
return result
def parse_motion_line(line: str) -> str:
"""
MOTION: a person sprinting right in terror
→ "a person sprinting right in terror"
"""
return line.replace("MOTION:", "").strip().lower()
# ═══════════════════════════════════════════════════════════════
# SECTION 3: 키워드 사전 — 감정/행동 강도의 정량 기준
# ═══════════════════════════════════════════════════════════════
"""
핵심: "sprint"와 "walk"의 차이를 수치로 정의
이 사전이 벤치마크의 재현성을 보장함
제3자가 이 사전으로 동일한 채점 결과를 얻을 수 있음
"""
class Intensity(IntEnum):
"""행동 강도 레벨 (0~5)"""
NONE = 0 # 무반응
MINIMAL = 1 # 미약한 반응
LOW = 2 # 가벼운 반응
MEDIUM = 3 # 보통 반응
HIGH = 4 # 강한 반응
EXTREME = 5 # 극단적 반응
# 행동 키워드 → 강도 매핑 (알파벳 순, 검색 용이)
ACTION_INTENSITY: Dict[str, int] = {
# EXTREME (5)
"desperate": 5, "desperately": 5, "frantic": 5, "frantically": 5,
"flee": 5, "fleeing": 5, "panic": 5, "panicking": 5,
"terror": 5, "terrified": 5,
# HIGH (4)
"bolt": 4, "bolting": 4, "dash": 4, "dashing": 4,
"escape": 4, "escaping": 4, "run": 4, "running": 4,
"rush": 4, "rushing": 4, "sprint": 4, "sprinting": 4,
# MEDIUM (3)
"hurry": 3, "hurrying": 3, "jog": 3, "jogging": 3,
"quick": 3, "quickly": 3, "retreat": 3, "retreating": 3,
"step back": 3, "stepping back": 3, "back away": 3,
# LOW (2)
"cautious": 2, "cautiously": 2, "slow": 2, "slowly": 2,
"walk": 2, "walking": 2, "turn": 2, "turning": 2,
"move": 2, "moving": 2, "shift": 2,
# MINIMAL (1)
"stand": 1, "standing": 1, "pause": 1, "pausing": 1,
"freeze": 1, "freezing": 1, "stop": 1, "stopping": 1,
"observe": 1, "watching": 1, "look": 1, "looking": 1,
}
# 감정 키워드 → 강도 매핑
EMOTION_INTENSITY: Dict[str, int] = {
# EXTREME (5)
"terror": 5, "terrified": 5, "horrified": 5, "desperate": 5,
"frantic": 5, "panic": 5, "anguish": 5,
# HIGH (4)
"fear": 4, "afraid": 4, "scared": 4, "alarmed": 4,
"distress": 4, "shock": 4, "dread": 4,
# MEDIUM (3)
"anxious": 3, "nervous": 3, "tense": 3, "worried": 3,
"uneasy": 3, "wary": 3, "alert": 3, "startled": 3,
# LOW (2)
"cautious": 2, "careful": 2, "vigilant": 2, "watchful": 2,
"guarded": 2, "attentive": 2,
# MINIMAL (1)
"calm": 1, "relaxed": 1, "composed": 1, "steady": 1,
"neutral": 1, "normal": 1,
}
# 방향 키워드 — MOTION에서 이동 방향 추출
DIRECTION_KEYWORDS: Dict[str, str] = {
"left": "left", "leftward": "left",
"right": "right", "rightward": "right",
"forward": "fwd", "ahead": "fwd", "front": "fwd",
"backward": "back", "backwards": "back", "back": "back",
"behind": "back", "around": "back", # "turn around" = back
}
def get_action_intensity(motion_text: str) -> int:
"""모션 텍스트에서 최대 행동 강도 추출"""
words = motion_text.lower()
max_intensity = 0
for keyword, intensity in ACTION_INTENSITY.items():
if keyword in words:
max_intensity = max(max_intensity, intensity)
return max_intensity
def get_emotion_intensity(motion_text: str) -> int:
"""모션 텍스트에서 최대 감정 강도 추출"""
words = motion_text.lower()
max_intensity = 0
for keyword, intensity in EMOTION_INTENSITY.items():
if keyword in words:
max_intensity = max(max_intensity, intensity)
return max_intensity
def get_motion_direction(motion_text: str) -> Optional[str]:
"""모션 텍스트에서 이동 방향 추출"""
words = motion_text.lower()
for keyword, direction in DIRECTION_KEYWORDS.items():
if keyword in words:
return direction
return None
def count_descriptors(motion_text: str) -> int:
"""모션 텍스트의 감정/행동 수식어 총 개수"""
words = motion_text.lower()
count = 0
for keyword in ACTION_INTENSITY:
if keyword in words:
count += 1
for keyword in EMOTION_INTENSITY:
if keyword in words:
count += 1
return count
# ═══════════════════════════════════════════════════════════════
# SECTION 4: 10개 카테고리별 정량 채점 함수
# ═══════════════════════════════════════════════════════════════
"""
각 함수는:
- 입력: scene_context(dict) + model_output(str) + ground_truth(dict)
- 출력: score(int, 0~20) + reasoning(str)
- 결정론적: 같은 입력 → 항상 같은 점수
"""
# ─── C01: Environmental Awareness (환경 인식 정확도) ───
def score_c01(scene: dict, predict: dict, ground_truth: dict) -> Tuple[int, str]:
"""
채점 기준: PREDICT의 각 방향이 실제 환경과 일치하는가
ground_truth = {
"left": "safe" | "danger",
"right": "safe" | "danger",
"fwd": "safe" | "danger",
"back": "safe" | "danger",
}
채점:
4방향 모두 정확 = 20점
3방향 정확 = 15점
2방향 정확 = 10점
1방향 정확 = 5점
0방향 정확 = 0점
"""
directions = ["left", "right", "fwd", "back"]
correct = 0
details = []
for d in directions:
if d not in predict:
details.append(f"{d}: 출력 없음 (오답)")
continue
gt_safe = ground_truth.get(d) == "safe"
pred_safe = predict[d].is_safe
if gt_safe == pred_safe:
correct += 1
details.append(f"{d}: 정답 (GT={ground_truth[d]}, PRED={'safe' if pred_safe else 'danger'})")
else:
details.append(f"{d}: 오답 (GT={ground_truth[d]}, PRED={'safe' if pred_safe else 'danger'})")
score_map = {4: 20, 3: 15, 2: 10, 1: 5, 0: 0}
score = score_map[correct]
reasoning = f"환경 인식: {correct}/4 방향 정확. " + "; ".join(details)
return score, reasoning
# ─── C02: Entity Recognition (개체 인식 및 분류) ───
def score_c02(scene: dict, predict: dict, ground_truth: dict) -> Tuple[int, str]:
"""
채점 기준: PREDICT에서 개체를 올바른 유형으로 인식했는가
ground_truth = {
"entity_type": "beast" | "woman" | "man" | None,
"entity_direction": "left" | "right" | "fwd" | "back",
"is_threat": True | False,
}
채점 (합산, 최대 20점):
개체 방향 정확: 8점 (해당 방향에 danger 표시)
개체 유형 정확: 8점 (danger 괄호 안에 올바른 유형)
위협 수준 정확: 4점 (beast=danger, woman=danger 또는 safe 모두 가능)
"""
score = 0
details = []
gt_dir = ground_truth.get("entity_direction")
gt_type = ground_truth.get("entity_type")
if gt_type is None:
# 개체 없음 — 모든 방향이 safe여야 함
all_safe = all(p.is_safe for p in predict.values())
if all_safe:
score = 20
details.append("개체 없음 정확 인식")
else:
danger_dirs = [d for d, p in predict.items() if p.is_danger]
score = 10 # 부분 점수
details.append(f"개체 없는데 {danger_dirs}를 danger로 오인식")
else:
# 개체 존재
# 1) 방향 정확도 (8점)
if gt_dir in predict and predict[gt_dir].is_danger:
score += 8
details.append(f"방향 정확: {gt_dir}=danger")
else:
details.append(f"방향 오답: {gt_dir}에 danger 없음")
# 2) 유형 정확도 (8점)
if gt_dir in predict and predict[gt_dir].reason:
pred_reason = predict[gt_dir].reason
if gt_type in pred_reason:
score += 8
details.append(f"유형 정확: {pred_reason}{gt_type} 포함")
else:
# 부분 점수: 위협으로 인식은 했으나 유형이 다름
score += 3
details.append(f"유형 부분: {pred_reason} (정답: {gt_type})")
else:
details.append("유형 정보 없음")
# 3) 위협 수준 (4점)
gt_threat = ground_truth.get("is_threat", False)
if gt_dir in predict:
pred_danger = predict[gt_dir].is_danger
if gt_threat == pred_danger:
score += 4
details.append(f"위협 수준 정확")
elif not gt_threat and not pred_danger:
score += 4
details.append(f"비위협 정확 인식")
reasoning = f"개체 인식: {score}/20. " + "; ".join(details)
return score, reasoning
# ─── C03: Predictive Reasoning (예측 기반 추론) ───
def score_c03(scene: dict, predict: dict, motion: str, ground_truth: dict) -> Tuple[int, str]:
"""
채점 기준: danger 방향을 피하고 safe 방향으로 이동했는가
ground_truth = {
"danger_directions": ["fwd", "left"], # 위험한 방향들
"safe_directions": ["right", "back"], # 안전한 방향들
"optimal_direction": "right", # 최적 방향
}
채점 (합산, 최대 20점):
danger 방향 회피: 8점 (이동 방향이 danger가 아님)
safe 방향 선택: 6점 (이동 방향이 safe 중 하나)
최적 방향 선택: 4점 (최적 방향 정확히 선택)
PREDICT-MOTION 일관성: 2점 (PREDICT에서 danger로 예측한 방향으로 안 감)
"""
score = 0
details = []
# 모션에서 이동 방향 추출
motion_dir = get_motion_direction(motion)
danger_dirs = ground_truth.get("danger_directions", [])
safe_dirs = ground_truth.get("safe_directions", [])
optimal = ground_truth.get("optimal_direction")
if motion_dir is None:
details.append("이동 방향 추출 불가 (방향 키워드 없음)")
# 방향은 없지만 행동이 합리적인지 확인
intensity = get_action_intensity(motion)
if intensity >= 3 and len(danger_dirs) > 0:
score += 4 # 위협에 대한 반응은 있음
details.append(f"방향 불명이나 반응 존재 (강도 {intensity})")
else:
# 1) danger 방향 회피 (8점)
if motion_dir not in danger_dirs:
score += 8
details.append(f"위험 방향 회피: {motion_dir} not in {danger_dirs}")
else:
details.append(f"위험 방향으로 이동: {motion_dir} in {danger_dirs}")
# 2) safe 방향 선택 (6점)
if motion_dir in safe_dirs:
score += 6
details.append(f"안전 방향 선택: {motion_dir} in {safe_dirs}")
else:
details.append(f"안전하지 않은 방향: {motion_dir} not in {safe_dirs}")
# 3) 최적 방향 (4점)
if motion_dir == optimal:
score += 4
details.append(f"최적 방향 정확: {motion_dir} == {optimal}")
else:
details.append(f"최적 아님: {motion_dir} != {optimal}")
# 4) PREDICT-MOTION 일관성 (2점)
if motion_dir and motion_dir in predict:
pred = predict[motion_dir]
if pred.is_safe:
score += 2
details.append("PREDICT-MOTION 일관: safe 방향으로 이동")
else:
details.append("PREDICT-MOTION 불일치: danger로 예측한 방향으로 이동")
reasoning = f"예측 추론: {score}/20. " + "; ".join(details)
return score, reasoning
# ─── C04: Threat Differentiation (위협 유형별 차별 반응) ───
def score_c04(
motion_a: str, motion_b: str,
ground_truth: dict
) -> Tuple[int, str]:
"""
채점 기준: 두 위협에 대한 반응 강도 차이가 올바른가
같은 scene에 (A) 맹수 접근 vs (B) 여성 접근
→ A의 반응 강도가 B보다 높아야 함
ground_truth = {
"scenario_a_type": "beast_charge",
"scenario_b_type": "woman_approach",
"expected_a_higher": True, # A가 더 강한 반응이어야
"min_intensity_diff": 2, # 최소 강도 차이
}
채점 (합산, 최대 20점):
반응 방향 정확: 8점 (A > B 또는 B > A 방향이 맞음)
강도 차이 충분: 8점 (차이가 min_intensity_diff 이상)
양쪽 모두 적절 반응: 4점 (둘 다 0이 아님)
"""
score = 0
details = []
int_a = get_action_intensity(motion_a)
int_b = get_action_intensity(motion_b)
expected_higher = ground_truth.get("expected_a_higher", True)
min_diff = ground_truth.get("min_intensity_diff", 2)
diff = int_a - int_b
# 1) 방향 정확 (8점)
if expected_higher and diff > 0:
score += 8
details.append(f"반응 방향 정확: A({int_a}) > B({int_b})")
elif not expected_higher and diff < 0:
score += 8
details.append(f"반응 방향 정확: B({int_b}) > A({int_a})")
elif diff == 0:
score += 2 # 부분 점수: 차이가 없음
details.append(f"반응 동일: A({int_a}) == B({int_b})")
else:
details.append(f"반응 방향 역전: A({int_a}), B({int_b})")
# 2) 강도 차이 (8점)
actual_diff = abs(diff)
if actual_diff >= min_diff:
score += 8
details.append(f"강도 차이 충분: |{diff}| >= {min_diff}")
elif actual_diff >= 1:
score += 4
details.append(f"강도 차이 부족: |{diff}| < {min_diff}")
else:
details.append(f"강도 차이 없음: |{diff}| = 0")
# 3) 양쪽 반응 존재 (4점)
if int_a > 0 and int_b > 0:
score += 4
details.append("양쪽 모두 반응 존재")
elif int_a > 0 or int_b > 0:
score += 2
details.append("한쪽만 반응 존재")
else:
details.append("양쪽 모두 무반응")
reasoning = f"위협 차별: {score}/20. A='{motion_a}' (강도{int_a}), B='{motion_b}' (강도{int_b}). " + "; ".join(details)
return score, reasoning
# ─── C05: Emotional Escalation (자율 감정 에스컬레이션) ───
def score_c05(motion_sequence: List[str], ground_truth: dict) -> Tuple[int, str]:
"""
채점 기준: 시간에 따른 감정 강도가 올바르게 변화하는가
motion_sequence = 같은 위협 지속 시 연속 3~5회 모션 출력
ground_truth = {
"expected_trend": "increasing" | "decreasing" | "stable",
"threat_type": "sustained_charge",
}
채점 (합산, 최대 20점):
추세 방향 정확: 10점
단조 증가/감소: 6점 (뒤로 가지 않음)
최종 강도 적절: 4점
"""
score = 0
details = []
if len(motion_sequence) < 2:
return 0, "시퀀스 길이 부족 (최소 2회 필요)"
intensities = [get_action_intensity(m) + get_emotion_intensity(m)
for m in motion_sequence]
expected = ground_truth.get("expected_trend", "increasing")
# 추세 계산
diffs = [intensities[i+1] - intensities[i] for i in range(len(intensities)-1)]
avg_diff = sum(diffs) / len(diffs)
# 1) 추세 방향 (10점)
if expected == "increasing":
if avg_diff > 0:
score += 10
details.append(f"증가 추세 정확: 평균 변화 +{avg_diff:.1f}")
elif avg_diff == 0:
score += 3
details.append(f"추세 변화 없음 (기대: 증가)")
else:
details.append(f"추세 역전 (기대: 증가, 실제: 감소 {avg_diff:.1f})")
elif expected == "decreasing":
if avg_diff < 0:
score += 10
details.append(f"감소 추세 정확: 평균 변화 {avg_diff:.1f}")
elif avg_diff == 0:
score += 3
details.append(f"추세 변화 없음 (기대: 감소)")
else:
details.append(f"추세 역전 (기대: 감소, 실제: 증가)")
elif expected == "stable":
if abs(avg_diff) <= 0.5:
score += 10
details.append(f"안정 유지 정확: 평균 변화 {avg_diff:.1f}")
else:
score += 4
details.append(f"불안정: 평균 변화 {avg_diff:.1f} (기대: 안정)")
# 2) 단조성 (6점) — 증가 추세에서 중간에 감소 없음
if expected == "increasing":
monotonic = all(d >= 0 for d in diffs)
elif expected == "decreasing":
monotonic = all(d <= 0 for d in diffs)
else:
monotonic = all(abs(d) <= 1 for d in diffs)
if monotonic:
score += 6
details.append("단조적 변화 (역행 없음)")
else:
non_monotonic_count = sum(1 for d in diffs if
(expected == "increasing" and d < 0) or
(expected == "decreasing" and d > 0))
if non_monotonic_count <= 1:
score += 3
details.append(f"약간의 역행 ({non_monotonic_count}회)")
else:
details.append(f"역행 다수 ({non_monotonic_count}회)")
# 3) 최종 강도 (4점)
if expected == "increasing" and intensities[-1] >= 6:
score += 4
details.append(f"최종 강도 충분: {intensities[-1]}")
elif expected == "decreasing" and intensities[-1] <= 3:
score += 4
details.append(f"최종 강도 적절히 낮음: {intensities[-1]}")
elif expected == "stable" and 2 <= intensities[-1] <= 4:
score += 4
details.append(f"최종 강도 안정적: {intensities[-1]}")
else:
score += 1
details.append(f"최종 강도: {intensities[-1]} (개선 여지)")
reasoning = f"감정 에스컬레이션: {score}/20. 강도 시퀀스: {intensities}. " + "; ".join(details)
return score, reasoning
# ─── C06: Contextual Memory (맥락 기억 활용) ───
def score_c06(
motion_without_memory: str,
motion_with_memory: str,
memory_content: str,
ground_truth: dict
) -> Tuple[int, str]:
"""
채점 기준: 기억이 있을 때와 없을 때 행동이 합리적으로 달라지는가
ground_truth = {
"memory_relevant": True, # 기억이 현 상황에 관련 있는가
"expected_change": "direction" | "intensity" | "both",
"memory_direction_avoid": "right", # 기억에 의해 피해야 할 방향
}
채점 (합산, 최대 20점):
기억 유무 차이 존재: 8점 (두 출력이 다름)
변화 방향 합리성: 8점 (기억 내용과 일치하는 변화)
기억 불필요 시 무변화: 4점 (무관한 기억에 영향 안 받음)
"""
score = 0
details = []
relevant = ground_truth.get("memory_relevant", True)
dir_without = get_motion_direction(motion_without_memory)
dir_with = get_motion_direction(motion_with_memory)
int_without = get_action_intensity(motion_without_memory)
int_with = get_action_intensity(motion_with_memory)
is_different = (motion_without_memory.strip() != motion_with_memory.strip())
dir_changed = (dir_without != dir_with)
int_changed = (int_without != int_with)
if relevant:
# 기억이 관련 있을 때: 변화가 있어야 함
# 1) 차이 존재 (8점)
if is_different:
score += 8
details.append(f"기억 반영 변화 있음")
else:
details.append("기억 있는데 변화 없음")
# 2) 변화 합리성 (8점)
expected_change = ground_truth.get("expected_change", "direction")
avoid_dir = ground_truth.get("memory_direction_avoid")
if expected_change in ("direction", "both") and avoid_dir:
if dir_with != avoid_dir and dir_without == avoid_dir:
score += 8
details.append(f"기억에 의해 {avoid_dir} 회피 → {dir_with} 선택")
elif dir_with != avoid_dir:
score += 4
details.append(f"회피 방향 올바르나 기존에도 안 감")
else:
details.append(f"기억에도 불구하고 {avoid_dir}로 이동")
# 3) 부분 점수
if int_changed and expected_change in ("intensity", "both"):
score += 4
details.append(f"강도 변화: {int_without}{int_with}")
else:
# 기억이 무관할 때: 변화가 없어야 함
if not is_different:
score += 20
details.append("무관한 기억에 영향 안 받음 (완벽)")
elif not dir_changed and not int_changed:
score += 16
details.append("실질적 변화 없음 (문구만 다름)")
else:
score += 4
details.append("무관한 기억에 불필요한 영향 받음")
reasoning = f"기억 활용: {score}/20. " + "; ".join(details)
return score, reasoning
# ─── C07: Threat Resolution Adaptation (위협 해제 적응) ───
def score_c07(
motion_during_threat: str,
motion_after_threat: List[str], # 해제 후 연속 출력
ground_truth: dict
) -> Tuple[int, str]:
"""
채점 기준: 위협 해제 후 적절히 정상화되는가
ground_truth = {
"expected_recovery": "gradual", # "gradual" | "immediate" | "vigilant"
}
채점 (합산, 최대 20점):
즉시 전력질주 중단: 6점 (해제 직후 강도 감소)
점진적 정상화: 8점 (급격하지 않은 감소 곡선)
경계 유지: 6점 (완전 정상화 아닌 중간 단계 존재)
"""
score = 0
details = []
threat_intensity = get_action_intensity(motion_during_threat)
after_intensities = [get_action_intensity(m) for m in motion_after_threat]
if len(after_intensities) < 2:
return 0, "해제 후 시퀀스 부족"
# 1) 즉시 중단 (6점): 첫 반응이 위협 시보다 낮아야
if after_intensities[0] < threat_intensity:
score += 6
details.append(f"즉시 감소: {threat_intensity}{after_intensities[0]}")
elif after_intensities[0] == threat_intensity:
score += 2
details.append(f"감소 없음: 여전히 {after_intensities[0]}")
else:
details.append(f"오히려 증가: {threat_intensity}{after_intensities[0]}")
# 2) 점진적 정상화 (8점): 계단식 감소
is_gradual = True
for i in range(len(after_intensities) - 1):
if after_intensities[i+1] > after_intensities[i] + 1: # 허용 오차 1
is_gradual = False
if is_gradual and after_intensities[-1] < after_intensities[0]:
score += 8
details.append(f"점진적 정상화: {after_intensities}")
elif after_intensities[-1] <= 2:
score += 4
details.append(f"최종 정상화 도달 (과정 불규칙)")
else:
score += 1
details.append(f"정상화 미달: 최종 강도 {after_intensities[-1]}")
# 3) 경계 유지 (6점): 중간에 1~2 수준의 vigilant 단계
has_vigilant = any(1 <= i <= 3 for i in after_intensities)
if has_vigilant:
score += 6
details.append("경계 단계 존재 (vigilant/cautious)")
elif after_intensities[-1] == 0:
score += 1
details.append("경계 없이 즉시 완전 정상화 (비현실적)")
else:
score += 3
details.append("경계 단계 불명확")
reasoning = f"위협 해제 적응: {score}/20. 시퀀스: [{threat_intensity}]→{after_intensities}. " + "; ".join(details)
return score, reasoning
# ─── C08: Motion Expressiveness (모션 감정 표현력) ───
def score_c08(motion: str, ground_truth: dict) -> Tuple[int, str]:
"""
채점 기준: 모션 프롬프트의 표현 풍부함 (정량적)
ground_truth = {
"expected_min_intensity": 3, # 최소 기대 강도
"expected_emotion": True, # 감정 키워드 기대 여부
"expected_min_descriptors": 2, # 최소 수식어 수
}
채점 (합산, 최대 20점):
행동 강도 적절: 6점
감정 키워드 존재: 6점
수식어 풍부함: 4점
12단어 이내 준수: 4점
"""
score = 0
details = []
action_int = get_action_intensity(motion)
emotion_int = get_emotion_intensity(motion)
desc_count = count_descriptors(motion)
word_count = len(motion.split())
min_intensity = ground_truth.get("expected_min_intensity", 3)
expect_emotion = ground_truth.get("expected_emotion", True)
min_desc = ground_truth.get("expected_min_descriptors", 2)
# 1) 행동 강도 (6점)
if action_int >= min_intensity:
score += 6
details.append(f"행동 강도 적절: {action_int} >= {min_intensity}")
elif action_int >= min_intensity - 1:
score += 3
details.append(f"행동 강도 부족: {action_int} < {min_intensity}")
else:
details.append(f"행동 강도 미달: {action_int}")
# 2) 감정 키워드 (6점)
if expect_emotion:
if emotion_int >= 3:
score += 6
details.append(f"감정 풍부: 강도 {emotion_int}")
elif emotion_int >= 1:
score += 3
details.append(f"감정 약함: 강도 {emotion_int}")
else:
details.append("감정 키워드 없음")
else:
if emotion_int <= 1:
score += 6
details.append("감정 절제 적절 (평상시)")
else:
score += 3
details.append(f"불필요한 감정 표현: 강도 {emotion_int}")
# 3) 수식어 (4점)
if desc_count >= min_desc:
score += 4
details.append(f"수식어 풍부: {desc_count}개")
elif desc_count >= 1:
score += 2
details.append(f"수식어 부족: {desc_count}/{min_desc}")
else:
details.append("수식어 없음")
# 4) 길이 제한 준수 (4점)
if word_count <= 15: # 약간의 여유
score += 4
details.append(f"길이 적절: {word_count}단어")
elif word_count <= 20:
score += 2
details.append(f"다소 김: {word_count}단어")
else:
details.append(f"너무 김: {word_count}단어")
reasoning = f"표현력: {score}/20. '{motion}' (행동{action_int},감정{emotion_int},수식{desc_count},단어{word_count}). " + "; ".join(details)
return score, reasoning
# ─── C09: Realtime Performance (실시간 성능) ───
def score_c09(metrics: dict) -> Tuple[int, str]:
"""
채점 기준: 직접 측정된 성능 수치
metrics = {
"fps": float, # 평균 FPS
"cognitive_latency_ms": int, # 인지루프 지연 (ms)
"frame_drop_rate": float, # 프레임 드롭률 (0.0~1.0)
"gpu_memory_stable": bool, # GPU 메모리 안정 여부
}
채점 (합산, 최대 20점):
FPS: 8점 (≥45:8, ≥30:6, ≥15:3, <15:0)
인지 지연: 6점 (≤3s:6, ≤5s:4, ≤10s:2, >10s:0)
프레임 드롭: 4점 (<1%:4, <5%:2, ≥5%:0)
메모리 안정: 2점 (안정:2, 불안정:0)
"""
score = 0
details = []
fps = metrics.get("fps", 0)
latency = metrics.get("cognitive_latency_ms", 99999)
drop_rate = metrics.get("frame_drop_rate", 1.0)
mem_stable = metrics.get("gpu_memory_stable", False)
# FPS (8점)
if fps >= 45:
score += 8; details.append(f"FPS 우수: {fps:.1f}")
elif fps >= 30:
score += 6; details.append(f"FPS 양호: {fps:.1f}")
elif fps >= 15:
score += 3; details.append(f"FPS 최소: {fps:.1f}")
else:
details.append(f"FPS 미달: {fps:.1f}")
# 인지 지연 (6점)
latency_s = latency / 1000
if latency_s <= 3:
score += 6; details.append(f"지연 우수: {latency_s:.1f}s")
elif latency_s <= 5:
score += 4; details.append(f"지연 양호: {latency_s:.1f}s")
elif latency_s <= 10:
score += 2; details.append(f"지연 최소: {latency_s:.1f}s")
else:
details.append(f"지연 과다: {latency_s:.1f}s")
# 프레임 드롭 (4점)
if drop_rate < 0.01:
score += 4; details.append(f"드롭 없음: {drop_rate*100:.1f}%")
elif drop_rate < 0.05:
score += 2; details.append(f"드롭 소량: {drop_rate*100:.1f}%")
else:
details.append(f"드롭 과다: {drop_rate*100:.1f}%")
# 메모리 (2점)
if mem_stable:
score += 2; details.append("GPU 메모리 안정")
else:
details.append("GPU 메모리 불안정")
reasoning = f"실시간 성능: {score}/20. " + "; ".join(details)
return score, reasoning
# ─── C10: Cross-body Transferability (신체 교체 확장성) ───
def score_c10(transfer_results: dict) -> Tuple[int, str]:
"""
채점 기준: 인지 출력이 다른 신체에서도 동작하는가
transfer_results = {
"brain_output_unchanged": bool, # 두뇌 코드 수정 없이
"motion_model_swapped": bool, # 모션 모델 교체 성공
"joint_format_compatible": bool, # 관절 포맷 호환
"intent_preserved": bool, # 행동 의도 보존
"servo_mapping_ready": bool, # 로봇 서보 매핑 준비
}
채점 (합산, 최대 20점):
두뇌 코드 불변: 6점
모션 모델 교체: 4점
관절 호환: 4점
의도 보존: 4점
서보 매핑 준비: 2점
"""
score = 0
details = []
checks = [
("brain_output_unchanged", 6, "두뇌 코드 불변"),
("motion_model_swapped", 4, "모션 모델 교체"),
("joint_format_compatible", 4, "관절 포맷 호환"),
("intent_preserved", 4, "행동 의도 보존"),
("servo_mapping_ready", 2, "서보 매핑 준비"),
]
for key, points, label in checks:
if transfer_results.get(key, False):
score += points
details.append(f"{label}: 통과 (+{points})")
else:
details.append(f"{label}: 미통과")
reasoning = f"교체 확장성: {score}/20. " + "; ".join(details)
return score, reasoning
# ═══════════════════════════════════════════════════════════════
# SECTION 5: 통합 채점기
# ═══════════════════════════════════════════════════════════════
def calculate_wm_score(category_scores: Dict[str, int]) -> dict:
"""
10개 카테고리 점수 → WM Score + 등급 계산
category_scores = {
"C01": 85, "C02": 75, ..., "C10": 35
}
각 카테고리는 5개 시나리오 × 20점 = 100점 만점
WM Score = P1(250) + P2(450) + P3(300) = 1000점 만점
"""
pillar_mapping = {
"P1": ["C01", "C02"],
"P2": ["C03", "C04", "C05", "C06", "C07"],
"P3": ["C08", "C09", "C10"],
}
pillar_weights = {
"P1": 250, # 2 categories → 200 raw → scale to 250
"P2": 450, # 5 categories → 500 raw → scale to 450
"P3": 300, # 3 categories → 300 raw → scale to 300
}
pillar_scores = {}
for pillar, cats in pillar_mapping.items():
raw = sum(category_scores.get(c, 0) for c in cats)
raw_max = len(cats) * 100
scaled = round(raw / raw_max * pillar_weights[pillar])
pillar_scores[pillar] = {
"raw": raw,
"raw_max": raw_max,
"scaled": scaled,
"scaled_max": pillar_weights[pillar],
}
total = sum(p["scaled"] for p in pillar_scores.values())
# 등급 판정
grades = [
(900, "S", "Superhuman"),
(750, "A", "Advanced"),
(600, "B", "Baseline"),
(400, "C", "Capable"),
(200, "D", "Developing"),
(0, "F", "Failing"),
]
grade = "F"
grade_label = "Failing"
for threshold, g, label in grades:
if total >= threshold:
grade = g
grade_label = label
break
return {
"wm_score": total,
"max_score": 1000,
"grade": grade,
"grade_label": grade_label,
"pillar_scores": pillar_scores,
"category_scores": category_scores,
}
# ═══════════════════════════════════════════════════════════════
# SECTION 6: 재현성 검증 — 셀프 테스트
# ═══════════════════════════════════════════════════════════════
def self_test():
"""채점 함수들의 결정론성 검증"""
print("=" * 60)
print(" WM Bench Scoring Self-Test")
print("=" * 60)
# Test C01
predict = parse_predict_line(
"PREDICT: left=safe(open), right=danger(wall), fwd=danger(beast), back=safe"
)
gt = {"left": "safe", "right": "danger", "fwd": "danger", "back": "safe"}
s, r = score_c01({}, predict, gt)
assert s == 20, f"C01 test failed: {s} != 20"
print(f" C01: {s}/20 ✓ — {r[:60]}...")
# Test C03 — predict에서 right=safe여야 MOTION과 일관
predict_c03 = parse_predict_line(
"PREDICT: left=danger(wall), right=safe(open), fwd=danger(beast), back=safe"
)
motion = "a person sprinting right to flank the beast"
gt = {"danger_directions": ["fwd", "left"], "safe_directions": ["right", "back"], "optimal_direction": "right"}
s, r = score_c03({}, predict_c03, motion, gt)
assert s == 20, f"C03 test failed: {s} != 20"
print(f" C03: {s}/20 ✓ — {r[:60]}...")
# Test C04
motion_a = "a person sprinting away in terror"
motion_b = "a person walking away cautiously"
gt = {"expected_a_higher": True, "min_intensity_diff": 2}
s, r = score_c04(motion_a, motion_b, gt)
assert s >= 16, f"C04 test failed: {s} < 16"
print(f" C04: {s}/20 ✓ — {r[:60]}...")
# Test C05
seq = [
"a person running away",
"a person sprinting away in fear",
"a person desperately fleeing in terror",
]
gt = {"expected_trend": "increasing"}
s, r = score_c05(seq, gt)
assert s >= 15, f"C05 test failed: {s} < 15"
print(f" C05: {s}/20 ✓ — {r[:60]}...")
# Test C08
motion = "a person sprinting right in desperate terror"
gt = {"expected_min_intensity": 4, "expected_emotion": True, "expected_min_descriptors": 2}
s, r = score_c08(motion, gt)
assert s >= 16, f"C08 test failed: {s} < 16"
print(f" C08: {s}/20 ✓ — {r[:60]}...")
# Test C09
metrics = {"fps": 47.0, "cognitive_latency_ms": 3000, "frame_drop_rate": 0.005, "gpu_memory_stable": True}
s, r = score_c09(metrics)
assert s == 20, f"C09 test failed: {s} != 20"
print(f" C09: {s}/20 ✓ — {r[:60]}...")
# 통합 점수 테스트
cat_scores = {
"C01": 65, "C02": 75,
"C03": 85, "C04": 90, "C05": 85, "C06": 60, "C07": 70,
"C08": 80, "C09": 85, "C10": 35,
}
result = calculate_wm_score(cat_scores)
print(f"\n WM Score: {result['wm_score']}/1000 (Grade {result['grade']})")
for p, data in result["pillar_scores"].items():
print(f" {p}: {data['scaled']}/{data['scaled_max']} (raw {data['raw']}/{data['raw_max']})")
print(f"\n All tests passed ✓")
print("=" * 60)
if __name__ == "__main__":
self_test()