Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
strategy:
fail-fast: false
matrix:
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack]
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, chess]
steps:
- uses: actions/checkout@v4
with: {persist-credentials: false}
Expand Down
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi

## 已接入的游戏

当前共有 **5 个 benchmark、42 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 44 个任务目录**。同一原生任务的不同模式单独计数。
当前共有 **6 个 benchmark、43 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 45 个任务目录**。同一原生任务的不同模式单独计数。

| Benchmark | standard | 其他模式 | 主要内容 | 说明 |
|---|---:|---|---|---|
Expand All @@ -33,6 +33,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi
| TextWorld | 9 | — | 文字探索、寻宝、烹饪 | 冻结 `.z8` 游戏,通过原生引擎执行 |
| Baba Is AI | 2 | — | 移动文字、改变规则、解谜 | 基础关卡与复合关卡的最小 smoke 验证 |
| MiniHack | 10 | 1 privileged | Room、River、导航、战斗、Quest、Boxoban | 原生 MiniHack/NLE 环境;Room 另有 privileged 版本 |
| Chess | 1 | — | 标准开局,执白对固定黑方 | [PettingZoo Chess 工程验证](game_first_exam/tasks/chess/README.md) |

套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加:

Expand All @@ -46,7 +47,8 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi
| `babaisai` | 2 | Baba Is AI smoke |
| `minihack` | 3 | Room/River standard + Room privileged |
| `minihack-balrog` | 8 | 参考 BALROG 选取的原生 MiniHack 任务 |
| `all` | 44 | 所有套件去重后的任务;汇总时应选择一种模式 |
| `chess` | 1 | PettingZoo Chess Standard 工程验证 |
| `all` | 45 | 所有套件去重后的任务;汇总时应选择一种模式 |

`minihack-balrog` 包含 MazeWalk 9×9、MazeWalk 15×15、Corridor R3、CorridorBattle Dark、Quest Easy、Quest Medium、Boxoban Medium、Boxoban Hard。**使用相同原生环境名称不意味着与 BALROG 的 LLM 输入、prompt、agent、seed 和预算完全相同**,成绩不能直接当作 BALROG 排行榜成绩。

Expand Down Expand Up @@ -153,7 +155,7 @@ harbor run --game-suite minihack --standard --family room \

| 模式 | 执行方式 | 当前覆盖 |
|---|---|---|
| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 5 个游戏、42 个配置 |
| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 6 个游戏、43 个配置 |
| `privileged` | agent 可本地探索和规划;最终动作序列由独立 verifier 重新执行 | MiniHack Room |
| `realtime` | 首次有效动作计划启动固定 tick;程序与模型思考期间游戏继续推进 | Crafter survival i01 |

Expand Down Expand Up @@ -246,6 +248,7 @@ harbor view jobs
| MiniGrid / Baba Is AI | 原生目标是否成功 | reward、步数、原生终局 |
| TextWorld | 原生 score / max_score | 原生得分、胜负、步数 |
| MiniHack | 完成 100,未完成 0 | 原生 return、end status、动作数;100 是分数,不是 100 步 |
| Chess | 原生胜 100、和 50、负或未完成 0 | 原生结果、白方决策数、双方半回合数 |
| Crafter | 单局成就比例;跨局另计算成就成功率的 Crafter score | 22 个成就、原生 return、存活状态;木镐是辅助目标 |

普通 reducer 按任务族汇总,Crafter 使用独立、带版本的成就 reducer。缺失局、重复局、环境故障和有效失败分开处理;模型未完成应计为有效失败,不能随意删掉。单局成就比例不是官方完整评测集的总分。
Expand Down Expand Up @@ -326,12 +329,12 @@ docker build -f game_first_exam/tests/envs/common.Dockerfile -t game-tests:commo
docker run --rm -v "$PWD:/repo:ro" game-tests:common \
bash game_first_exam/tests/run.sh common

# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack
# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack / chess
# Harbor 选择、配置合并、锁定和报告测试:
python game_first_exam/tests/test_game_harbor.py
```

GitHub Actions 执行静态检查、公共测试、5 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。
GitHub Actions 执行静态检查、公共测试、6 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。

- **`harbor` 不识别 `--game-suite`:**确认当前环境执行过 `pip install -e .`,并检查 `which harbor`。也可用 `game-exam run ...`;单独安装 Harbor 不包含本仓库选择逻辑。
- **选不到任务:**先 `--list`;只有 Room 有 MiniHack privileged,只有 Crafter i01 有 realtime。模式不匹配会拒绝启动。
Expand Down
3 changes: 3 additions & 0 deletions configs/game_benchmarks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ schema = "game_first_exam/benchmarks/babaisai/instance_schema.py"

[benchmarks.minihack]
schema = "game_first_exam/benchmarks/minihack/instance_schema.py"

[benchmarks.chess]
schema = "game_first_exam/benchmarks/chess/instance_schema.py"
10 changes: 10 additions & 0 deletions configs/game_suites/chess.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
schema_version = "game-suite/2.1"
version = "0.1.2"
tier = "smoke"
name = "games-chess-native-smoke-v0.1.2"
files_images = ["connection-files", "game-files", "chess-files"]

[[tasks]]
name = "chess-match-i01-standard"
benchmark = "chess"
family = "standard-start"
9 changes: 9 additions & 0 deletions game_first_exam/benchmarks/chess/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"repository": "https://github.com/Farama-Foundation/PettingZoo",
"commit": "7221e4b15873a8b16555fda038a77a6ae595e88d",
"environment": "classic/chess-v6",
"pettingzoo_wheel_sha256": "075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61",
"chess_sdist_sha256": "a8b43e5678fdb3000695bdaa573117ad683761e5ca38e591c4826eba6d25bb39",
"chess_py_sha256": "2b5c6f684951bb1b476213db88fcbebf63ed7acf0c565e288454f3174752726a",
"chess_utils_py_sha256": "e9a7418ab85bbbb2f5ed5cd766b5afcc7ff07a6ca110842f48465f4ec9717cc1"
}
152 changes: 152 additions & 0 deletions game_first_exam/benchmarks/chess/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""One white client decision and at most one black AEC response."""
import copy
import hashlib
from importlib.metadata import version
import json
import os
from pathlib import Path

import numpy as np
from pettingzoo import make
from pettingzoo.classic.chess import chess_utils

from contracts import Capabilities, Transition
from encoding import state_hash
from metric_rules import ACTION_COUNT, BLACK, POINTS, WHITE
from opponent import choose


class Adapter:
def __init__(self, instance, assets=None):
for package, expected in instance['engine_versions'].items():
if version(package) != expected:
raise ValueError(f'Chess dependency version mismatch: {package}')
self.instance = instance
self.env = make('aec', instance['env_id'], render_mode='rgb_array', screen_height=384)
try:
self.env.reset(seed=instance['seed'])
self.board = self.env.unwrapped.board
self.history = []
self.decisions = 0
self.outcome = 'unfinished'
self.result = '*'
self.draw_reason = None
self.rewards = [0, 0]
self.terminated = self.truncated = False
self.trace_digest = hashlib.sha256()
trace = os.environ.get('CHESS_TRACE_PATH')
self.trace_path = Path(trace) if trace else None
if self.trace_path is not None:
self.trace_path.parent.mkdir(parents=True, exist_ok=True)
with self.trace_path.open('xb'):
pass
self.refresh_observation([])
except Exception:
self.env.close()
raise

def spec(self):
return {
'adapter_version': '1.0.0',
'capabilities': Capabilities(False, 'enum', native_truncation=True).to_dict(),
'action_schema': {'type': 'string', 'enum': [str(i) for i in range(ACTION_COUNT)],
'max_length': 4},
'goal': 'Win the native game as white.',
}

def legal_map(self, actor, mask):
return {str(index): chess_utils.action_to_move(self.board, int(index), int(actor == BLACK)).uci()
for index in np.flatnonzero(mask)}

def refresh_observation(self, moves):
native = self.env.observe(WHITE)
self.white_legal = {} if self.terminated or self.truncated else self.legal_map(WHITE, native['action_mask'])
self.public = {
'native_observation': native['observation'].tolist(),
'action_mask': native['action_mask'].tolist(),
'controlled_agent': WHITE,
'side_to_move': 'white' if self.board.turn else 'black',
'board_fen': self.board.fen(),
'board_ascii': str(self.board),
'legal_moves': self.white_legal,
'last_round_moves': moves,
'move_history_uci': list(self.history),
'outcome': self.outcome,
}

def observe(self):
return copy.deepcopy(self.public)

def native_step(self, actor, action, legal):
if self.env.agent_selection != actor:
raise RuntimeError('unexpected native Chess actor')
before = self.board.fen()
uci = legal.get(action)
self.env.step(int(action))
self.rewards = [self.env.rewards[player] for player in (WHITE, BLACK)]
self.terminated = all(self.env.terminations.values())
self.truncated = all(self.env.truncations.values())
if uci is not None:
self.history.append(uci)
if self.terminated:
if uci is None:
self.outcome = 'illegal_action'
else:
outcome = self.board.outcome(claim_draw=True)
self.result = outcome.result()
self.outcome = {'1-0': 'win', '0-1': 'loss', '1/2-1/2': 'draw'}[self.result]
if self.outcome == 'draw':
self.draw_reason = outcome.termination.name.lower()
row = {'actor': actor, 'action_id': action, 'uci': uci, 'decision': self.decisions,
'ply': self.board.ply(), 'fen_before': before, 'fen_after': self.board.fen(),
'rewards': self.rewards, 'terminated': self.terminated, 'truncated': self.truncated,
'legal_moves': legal}
data = (json.dumps(row, sort_keys=True, separators=(',', ':')) + '\n').encode()
if self.trace_path is not None:
with self.trace_path.open('ab') as stream:
stream.write(data)
self.trace_digest.update(data)
return {'actor': actor, 'action_id': action, 'uci': uci}

def step(self, action):
if self.terminated or self.truncated:
raise ValueError('episode closed')
self.decisions += 1
moves = [self.native_step(WHITE, action, self.white_legal)]
reward = self.rewards[0]
if not (self.terminated or self.truncated):
legal = self.legal_map(BLACK, self.env.observe(BLACK)['action_mask'])
response = choose(legal, self.instance['opponent_seed'], self.history)
if response not in legal:
raise RuntimeError('fixed opponent returned an illegal Chess action')
moves.append(self.native_step(BLACK, response, legal))
reward += self.rewards[0]
self.refresh_observation(moves)
return Transition(float(reward), self.terminated, self.truncated)

def success(self):
return self.outcome == 'win'

def metrics(self):
plies = len(self.history)
return {'outcome': self.outcome, 'match_points': POINTS[self.outcome],
'success': int(self.success()), 'native_result': self.result,
'native_return': self.rewards[0], 'native_rewards': self.rewards.copy(),
'draw_reason': self.draw_reason, 'agent_decisions': self.decisions,
'agent_legal_plies': (plies + 1) // 2, 'opponent_plies': plies // 2,
'total_board_plies': plies, 'setup_plies': 0,
'native_illegal_actions': int(self.outcome == 'illegal_action'),
'final_fen': self.board.fen(), 'trace_sha256': self.trace_digest.hexdigest()}

def fingerprint(self):
return state_hash({'metrics': self.metrics(), 'actor': self.env.agent_selection,
'flags': [self.env.terminations, self.env.truncations],
'board_history': self.env.unwrapped.board_history,
'seed': self.instance['seed'], 'opponent_seed': self.instance['opponent_seed'],
'opponent_policy': self.instance['opponent_policy']})

def frame(self):
return self.env.render()

def close(self):
self.env.close()
2 changes: 2 additions & 0 deletions game_first_exam/benchmarks/chess/build-requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
setuptools==80.9.0 --hash=sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922
wheel==0.45.1 --hash=sha256:708e7481cc80179af0e556bbf0cc00b8444c7321e2700b8d8580231d13017248
1 change: 1 addition & 0 deletions game_first_exam/benchmarks/chess/chess-requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
chess==1.11.2 --hash=sha256:a8b43e5678fdb3000695bdaa573117ad683761e5ca38e591c4826eba6d25bb39
37 changes: 37 additions & 0 deletions game_first_exam/benchmarks/chess/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Trusted Chess configuration, usable without native dependencies."""
from config_schema import validate_engine_versions

BENCHMARK = 'chess'
SCHEMA_VERSION = '1.0.0'
ENV_ID = 'classic/chess-v6'
PROFILE = 'chess-public-board-native-v1'
PROFILES = {PROFILE}
METRICS = {'match_points'}
REDUCERS = {('family_macro', '1.0.0')}
FIELDS = {'engine_versions', 'engine_commit', 'engine_wheel_sha256', 'controlled_agent',
'initialization_policy', 'opponent_policy', 'opponent_seed', 'tool_policy'}
VERSIONS = {'pettingzoo': '1.27.0', 'chess': '1.11.2', 'gymnasium': '1.0.0',
'numpy': '1.26.4', 'pygame-ce': '2.5.6'}
COMMIT = '7221e4b15873a8b16555fda038a77a6ae595e88d'
WHEEL = '075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61'


def validate(value):
validate_engine_versions(value['engine_versions'], VERSIONS)
expected = {
'env_id': ENV_ID, 'family': 'standard-start', 'controlled_agent': 'player_0',
'initialization_policy': 'native-start-v1', 'opponent_policy': 'hash-legal-v1',
'engine_commit': COMMIT, 'engine_wheel_sha256': WHEEL,
'tool_policy': 'public-tools-no-task-solutions-v1',
'capabilities': {'images': False, 'action_mode': 'enum', 'timing': 'action-stepped',
'native_truncation': True},
'metric_spec': {'primary': 'match_points', 'reducer': 'family_macro',
'reducer_version': '1.0.0', 'success_label': 'native_white_win'},
}
for field, frozen in expected.items():
if value[field] != frozen:
raise ValueError(f'unsupported Chess {field}')
if type(value['opponent_seed']) is not int or not 0 <= value['opponent_seed'] < 2**31:
raise ValueError('invalid Chess opponent seed')
if value['max_steps'] is None:
raise ValueError('Chess requires a public decision budget')
Loading