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
36 changes: 34 additions & 2 deletions .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,38 @@ jobs:
with: {python-version: '3.12'}
- run: python -m pip install -e .
- run: harbor run --game-suite minihack-balrog --standard --list
- run: harbor run --game-suite connectfour --standard --list
- run: python game_first_exam/tests/test_game_harbor.py
connectfour-smoke:
runs-on: ubuntu-latest
timeout-minutes: 35
steps:
- uses: actions/checkout@v4
with: {persist-credentials: false}
- uses: actions/setup-python@v5
with: {python-version: '3.12'}
- uses: docker/setup-docker-action@v5
with:
version: v29.5.2
set-host: true
daemon-config: '{"features":{"containerd-snapshotter":true}}'
- run: python -m pip install -e . -r game_first_exam/benchmarks/connectfour/requirements.txt
- run: python game_first_exam/tests/test_connectfour.py
- name: Win through Harbor
run: |
harbor run --game-suite connectfour --standard \
-c configs/harbor/oracle.json --plugin game_harbor:GameRecords \
--jobs-dir "$PWD/jobs" --job-name connectfour-win -y
- name: Loss through Harbor
run: python game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py
- name: Check both native results and recordings
run: python ci_checks/check-connectfour-result.py jobs/connectfour-win jobs/connectfour-loss
- uses: actions/upload-artifact@v4
if: always()
with:
name: connectfour-evidence
path: jobs/
retention-days: 7
fresh-clone-smoke:
runs-on: ubuntu-latest
timeout-minutes: 30
Expand Down Expand Up @@ -78,7 +109,7 @@ jobs:
path: jobs/
retention-days: 7
invariants:
needs: [static, adapters, harbor, fresh-clone-smoke]
needs: [static, adapters, harbor, fresh-clone-smoke, connectfour-smoke]
if: ${{ always() }}
runs-on: ubuntu-latest
steps:
Expand All @@ -87,4 +118,5 @@ jobs:
ADAPTERS: ${{ needs.adapters.result }}
HARBOR: ${{ needs.harbor.result }}
SMOKE: ${{ needs.fresh-clone-smoke.result }}
run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success
CONNECTFOUR: ${{ needs.connectfour-smoke.result }}
run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success && test "$CONNECTFOUR" = success
8 changes: 5 additions & 3 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 版本 |
| [PettingZoo Connect Four](game_first_exam/tasks/connectfour/README.md) | 1 | — | 棋盘规划与固定对手对弈 | 冻结红方对局,含胜负录像 |

套件由 [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 | 所有套件去重后的任务;汇总时应选择一种模式 |
| `connectfour` | 1 | PettingZoo Connect Four 固定对局 |
| `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
36 changes: 36 additions & 0 deletions ci_checks/check-connectfour-result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Check the winning and losing Harbor trials independently."""

import json
import sys
from pathlib import Path


def check(job: Path, outcome: str, score: int):
trials = list(job.glob("*/result.json"))
if len(trials) != 1:
raise ValueError(f"{job}: expected one completed trial, found {len(trials)}")

trial = trials[0].parent
result = json.loads(trials[0].read_text())
reward = json.loads((trial / "verifier/reward.json").read_text())
final = json.loads((trial / "artifacts/data/final.json").read_text())
recording = json.loads((trial / "artifacts/data/recording.json").read_text())

if result.get("exception_info") is not None or result["task_name"].split("/")[-1] != "connectfour-match-i01-standard":
raise ValueError(f"{job}: wrong task or Harbor exception")
if reward["result_valid"] != 1 or reward["primary_score"] != score or reward["success"] != score:
raise ValueError(f"{job}: unexpected verifier grade")
if any(reward.get(key) != 0 for key in ("infra_error", "sim_error", "environment_error")):
raise ValueError(f"{job}: environment or simulator error")
if (final["metrics"]["outcome"] != outcome or final["success"] != bool(score)
or final["metrics"]["agent_decisions"] != 12 or final["steps"] != 12):
raise ValueError(f"{job}: native match did not reach its expected outcome")
if recording.get("render_error") is not None or not (trial / "artifacts/data/replay.mp4").stat().st_size:
raise ValueError(f"{job}: replay missing or rendering failed")
print(f"{job}: {outcome}, score {score}, 12 decisions, replay recorded")


if __name__ == "__main__":
check(Path(sys.argv[1]), "win", 1)
check(Path(sys.argv[2]), "loss", 0)
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.connectfour]
schema = "game_first_exam/benchmarks/connectfour/instance_schema.py"
10 changes: 10 additions & 0 deletions configs/game_suites/connectfour.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
schema_version = "game-suite/2.1"
version = "1.0.0"
tier = "smoke"
name = "games-connectfour-minimal-v1.0.0"
files_images = ["connection-files", "game-files", "connectfour-files"]

[[tasks]]
name = "connectfour-match-i01-standard"
benchmark = "connectfour"
family = "fixed-opponent"
Binary file added docs/demos/connectfour/red-loss.mp4
Binary file not shown.
Binary file added docs/demos/connectfour/red-win.mp4
Binary file not shown.
6 changes: 6 additions & 0 deletions game_first_exam/benchmarks/connectfour/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"repository": "https://github.com/Farama-Foundation/PettingZoo",
"environment": "classic/connect_four-v3",
"package": "pettingzoo==1.26.1",
"opponent": "block-win-hash-v1, implemented in opponent.py"
}
108 changes: 108 additions & 0 deletions game_first_exam/benchmarks/connectfour/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""One column decision for Red, followed by one fixed Yellow response."""

import copy
from importlib.metadata import version

import numpy as np
from pettingzoo.classic import connect_four_v3

from contracts import Capabilities, Transition
from encoding import png, state_hash
from opponent import choose


RED, YELLOW = "player_0", "player_1"


class Adapter:
def __init__(self, instance, assets=None):
if version("pettingzoo") != instance["engine_version"]:
raise ValueError("The pinned Connect Four version is not installed")
self.instance = instance
self.env = connect_four_v3.env(render_mode="rgb_array")
try:
self.env.reset(seed=instance["seed"])
self.turns = []
self.decisions = 0
self.outcome = "playing"
self.native_rewards = (0, 0)
self.capture()
except BaseException:
self.env.close()
raise

def spec(self):
return {"adapter_version": "1.0.0",
"capabilities": Capabilities(True, "enum", native_truncation=True).to_dict(),
"action_schema": {"type": "string", "enum": [str(i) for i in range(7)]},
"goal": "Win a native Connect Four match as Red."}

def board(self):
return list(self.env.unwrapped.board)

def legal(self, actor):
return [int(column) for column in np.flatnonzero(self.env.observe(actor)["action_mask"])]

def capture(self):
frame = self.env.render()
# The native 891-pixel board needs one padded pixel for H.264 recording.
if frame.shape[1] % 2:
frame = np.pad(frame, ((0, 0), (0, 1), (0, 0)), mode="edge")
self.rgb = np.ascontiguousarray(frame)

def observe(self):
return {"image_png_base64": png(self.rgb),
"board": [self.board()[row:row + 7] for row in range(0, 42, 7)],
"legal_columns": [] if self.outcome != "playing" else self.legal(RED),
"last_moves": copy.deepcopy(self.turns[-2:]),
"outcome": self.outcome}

def play(self, actor, column):
if self.env.agent_selection != actor:
raise RuntimeError("Unexpected Connect Four turn")
legal = self.legal(actor)
before = self.board()
self.env.step(column)
after = self.board()
self.native_rewards = tuple(self.env.rewards[agent] for agent in (RED, YELLOW))
if all(self.env.terminations.values()):
self.outcome = ("illegal" if column not in legal else
"win" if self.native_rewards[0] == 1 else
"loss" if self.native_rewards[0] == -1 else "draw")
self.turns.append({"actor": actor, "column": column, "board_before": before,
"board_after": after, "rewards": list(self.native_rewards)})

def step(self, action):
if self.outcome != "playing":
raise ValueError("Match already ended")
self.decisions += 1
self.play(RED, int(action))
reward = self.native_rewards[0]
if self.outcome == "playing":
response = choose(self.board(), self.legal(YELLOW), self.instance["opponent_seed"])
self.play(YELLOW, response)
reward += self.native_rewards[0]
self.capture()
return Transition(float(reward), self.outcome != "playing",
self.outcome == "illegal")

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

def metrics(self):
return {"outcome": self.outcome, "success": int(self.success()),
"native_rewards": list(self.native_rewards), "agent_decisions": self.decisions,
"total_plies": len(self.turns), "final_board": self.board(),
"moves": copy.deepcopy(self.turns)}

def fingerprint(self):
return state_hash({"board": self.board(), "turn": self.env.agent_selection,
"outcome": self.outcome, "seed": self.instance["seed"],
"opponent_seed": self.instance["opponent_seed"],
"policy": self.instance["opponent_policy"]})

def frame(self):
return self.rgb

def close(self):
self.env.close()
25 changes: 25 additions & 0 deletions game_first_exam/benchmarks/connectfour/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Frozen Connect Four settings shared by the host and isolated verifier."""

BENCHMARK = "connectfour"
SCHEMA_VERSION = "1.0.0"
FIELDS = {"engine_version", "opponent_policy", "opponent_seed", "controlled_agent"}
PROFILES = {"native-rgb-board-v1"}
METRICS = {"success"}
REDUCERS = {("family_macro", "1.0.0")}


def validate(value):
expected = {
"env_id": "connect_four_v3", "family": "fixed-opponent",
"engine_version": "1.26.1", "controlled_agent": "player_0",
"opponent_policy": "block-win-hash-v1", "opponent_seed": 2117382936,
"capabilities": {"images": True, "action_mode": "enum", "timing": "action-stepped",
"native_truncation": True},
"metric_spec": {"primary": "success", "reducer": "family_macro",
"reducer_version": "1.0.0", "success_label": "native_red_win"},
}
for key, frozen in expected.items():
if value[key] != frozen:
raise ValueError(f"Unsupported Connect Four {key}")
if value["max_steps"] != 21:
raise ValueError("Connect Four has at most 21 Red turns")
52 changes: 52 additions & 0 deletions game_first_exam/benchmarks/connectfour/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Independently replay public Connect Four moves and check the native verdict."""

from opponent import choose, winning_move


def validate_metrics(final, instance):
metrics = final["metrics"]
board = [0] * 42
moves = metrics["moves"]
if not isinstance(moves, list) or len(moves) > 42:
raise ValueError("Invalid Connect Four move count")

outcome = "playing"
for index, move in enumerate(moves):
actor = "player_0" if index % 2 == 0 else "player_1"
player = 1 if index % 2 == 0 else 2
column = move["column"]
legal = [c for c in range(7) if board[c] == 0]
if (outcome != "playing" or move["actor"] != actor or type(column) is not int
or not 0 <= column < 7 or move["board_before"] != board):
raise ValueError("Connect Four move order or board is inconsistent")
if actor == "player_1" and column != choose(board, legal, instance["opponent_seed"]):
raise ValueError("Connect Four opponent did not follow its frozen policy")

if column not in legal:
outcome = "illegal"
rewards = [-1, 0]
else:
won = winning_move(board, column, player)
row = next(r for r in range(5, -1, -1) if board[r * 7 + column] == 0)
board[row * 7 + column] = player
if won:
outcome = "win" if player == 1 else "loss"
elif all(board[:7]):
outcome = "draw"
rewards = ([1, -1] if outcome == "win" else
[-1, 1] if outcome == "loss" else [0, 0])
if move["board_after"] != board or move["rewards"] != rewards:
raise ValueError("Connect Four board or native reward disagrees with replay")

decisions = (len(moves) + 1) // 2
if (type(metrics["agent_decisions"]) is not int or metrics["agent_decisions"] != decisions
or decisions != final["steps"] or metrics["total_plies"] != len(moves)
or metrics["final_board"] != board or metrics["outcome"] != outcome
or metrics["native_rewards"] != (rewards if moves else [0, 0])):
raise ValueError("Connect Four final metrics disagree with move replay")
success = outcome == "win"
if (metrics["success"] != int(success) or final["success"] != success
or final["terminated"] != (outcome != "playing")
or final["truncated"] != (outcome == "illegal")
or final["return"] != (rewards if moves else [0, 0])[0]):
raise ValueError("Connect Four terminal result disagrees with replay")
45 changes: 45 additions & 0 deletions game_first_exam/benchmarks/connectfour/opponent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""A deterministic opponent that takes wins, blocks threats, then plays a seeded move."""

import hashlib
import json


ROWS, COLUMNS = 6, 7


def winning_move(board, column, player):
"""Check a proposed drop on the native, row-major PettingZoo board."""
row = next((r for r in range(ROWS - 1, -1, -1) if board[r * COLUMNS + column] == 0), None)
if row is None:
return False

def occupied(r, c):
return (r, c) == (row, column) or (
0 <= r < ROWS and 0 <= c < COLUMNS and board[r * COLUMNS + c] == player
)

for dr, dc in ((0, 1), (1, 0), (1, 1), (1, -1)):
count = 1
for sign in (-1, 1):
r, c = row + sign * dr, column + sign * dc
while occupied(r, c):
count += 1
r += sign * dr
c += sign * dc
if count >= 4:
return True
return False


def choose(board, legal, seed):
"""Return a legal column; same board and seed always yield the same answer."""
legal = sorted(int(column) for column in legal)
if not legal:
raise ValueError("Cannot choose from a full board")
for player in (2, 1):
for column in legal:
if winning_move(board, column, player):
return column
encoded = json.dumps([seed, board], separators=(",", ":")).encode()
index = int.from_bytes(hashlib.sha256(encoded).digest(), "big") % len(legal)
return legal[index]
10 changes: 10 additions & 0 deletions game_first_exam/benchmarks/connectfour/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pettingzoo==1.26.1
gymnasium==1.3.0
numpy==2.5.1
pygame-ce==2.5.8
imageio==2.37.4
imageio-ffmpeg==0.6.0
pillow==11.3.0
cloudpickle==3.1.2
farama-notifications==0.0.6
typing-extensions==4.16.0
Loading