From bda968883f6280ffc00e933d2f240759657463ca Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:08:17 -0800 Subject: [PATCH] Integrate Collab-Overcooked with isolated Harbor roles and native scoring --- .github/workflows/games.yml | 28 ++++- README.md | 7 +- ci_checks/check-collab-overcooked.py | 93 ++++++++++++++ .../native_benchmarks/collab-overcooked.toml | 11 ++ .../benchmarks/collab_overcooked/Dockerfile | 44 +++++++ .../benchmarks/collab_overcooked/README.md | 27 ++++ .../benchmarks/collab_overcooked/adapter.py | 96 ++++++++++++++ .../collab_overcooked/fixture_policy.py | 25 ++++ .../benchmarks/collab_overcooked/grade.py | 54 ++++++++ .../collab_overcooked/requirements.txt | 17 +++ .../benchmarks/collab_overcooked/role.py | 71 +++++++++++ .../task/environment/Dockerfile | 4 + .../task/environment/docker-compose.yaml | 35 ++++++ .../collab_overcooked/task/instruction.md | 1 + .../collab_overcooked/task/solution/solve.sh | 9 ++ .../collab_overcooked/task/task.toml | 26 ++++ .../collab_overcooked/task/tests/Dockerfile | 4 + .../task/tests/docker-compose.yaml | 3 + .../collab_overcooked/task/tests/test.sh | 11 ++ .../benchmarks/collab_overcooked/wire.py | 19 +++ game_first_exam/tests/collab_native_probe.py | 23 ++++ scripts/collab_overcooked.py | 119 ++++++++++++++++++ scripts/efe.py | 10 ++ 23 files changed, 732 insertions(+), 5 deletions(-) create mode 100644 ci_checks/check-collab-overcooked.py create mode 100644 configs/native_benchmarks/collab-overcooked.toml create mode 100644 game_first_exam/benchmarks/collab_overcooked/Dockerfile create mode 100644 game_first_exam/benchmarks/collab_overcooked/README.md create mode 100644 game_first_exam/benchmarks/collab_overcooked/adapter.py create mode 100644 game_first_exam/benchmarks/collab_overcooked/fixture_policy.py create mode 100644 game_first_exam/benchmarks/collab_overcooked/grade.py create mode 100644 game_first_exam/benchmarks/collab_overcooked/requirements.txt create mode 100644 game_first_exam/benchmarks/collab_overcooked/role.py create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/environment/Dockerfile create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/environment/docker-compose.yaml create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/instruction.md create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/solution/solve.sh create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/task.toml create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/tests/Dockerfile create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/tests/docker-compose.yaml create mode 100644 game_first_exam/benchmarks/collab_overcooked/task/tests/test.sh create mode 100644 game_first_exam/benchmarks/collab_overcooked/wire.py create mode 100644 game_first_exam/tests/collab_native_probe.py create mode 100644 scripts/collab_overcooked.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..8c5cb26 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -42,6 +42,29 @@ jobs: - run: python -m pip install -e . - run: harbor run --game-suite minihack-balrog --standard --list - run: python game_first_exam/tests/test_game_harbor.py + collab-overcooked: + 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: actions/checkout@v4 + with: + repository: YusaeMeow/Collab-Overcooked + ref: d7ae1aa5e63d8ec076e96ee437fcbbd095278ef4 + path: .local/reference + persist-credentials: false + - run: python -m pip install -e . + - run: harbor run --game-suite collab-overcooked --offline-smoke --job-name collab-smoke -y + - run: python ci_checks/check-collab-overcooked.py jobs/collab-smoke .local/reference + - if: always() + uses: actions/upload-artifact@v4 + with: + name: collab-overcooked-harbor + path: jobs/ + retention-days: 7 fresh-clone-smoke: runs-on: ubuntu-latest timeout-minutes: 30 @@ -78,7 +101,7 @@ jobs: path: jobs/ retention-days: 7 invariants: - needs: [static, adapters, harbor, fresh-clone-smoke] + needs: [static, adapters, harbor, fresh-clone-smoke, collab-overcooked] if: ${{ always() }} runs-on: ubuntu-latest steps: @@ -87,4 +110,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 + COLLAB: ${{ needs.collab-overcooked.result }} + run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success && test "$COLLAB" = success diff --git a/README.md b/README.md index 5e00e1f..ea8010f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-first-exam) 的任务封装和 [Harbor](https://github.com/laude-institute/harbor) 执行方式构建。本仓库只包含游戏任务、游戏适配器和它们依赖的公共工具,不包含机器人 benchmark、网站源码、个人配置或历史评测日志。 -模型通过 Harbor 原生 coding agent 阅读任务的 `instruction.md`,在容器内编写并执行 Python 等程序,通过客户端操作游戏。游戏环境负责推进状态,独立 verifier 根据可信记录评分。这里没有另建直接 LLM 对话式动作入口或 RL 训练入口。 +冻结任务通过 Harbor 原生 coding agent 阅读 `instruction.md`,在容器内编写并执行程序,通过客户端操作游戏。Collab-Overcooked 使用作者的双角色协议。游戏环境负责推进状态,独立 verifier 根据可信记录评分。 > 当前是开发与接入验证版本。冻结任务是已确定环境、实例、seed、观测方式和预算的可复现配置,不等于 benchmark 的全部任务,也不是新的官方排行榜。网站源码在单独的私人仓库维护。 @@ -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**。其中 5 个提供冻结任务,共 42 个 standard、1 个 privileged 和 1 个 realtime 配置。Collab-Overcooked 另提供论文的 30 道菜,可用 `harbor run --game-suite collab-overcooked --list` 查看。 | Benchmark | standard | 其他模式 | 主要内容 | 说明 | |---|---:|---|---|---| @@ -33,8 +33,9 @@ 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 版本 | +| Collab-Overcooked | — | 原生双角色 | Chef 和 Assistant 合作完成 6 档食谱 | [运行与隔离说明](game_first_exam/benchmarks/collab_overcooked/README.md) | -套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加: +以下冻结任务套件可以重叠,完整清单见 [configs/game_suites/](configs/game_suites/)。 | `--game-suite` | 配置数 | 用途 | |---|---:|---| diff --git a/ci_checks/check-collab-overcooked.py b/ci_checks/check-collab-overcooked.py new file mode 100644 index 0000000..9754df5 --- /dev/null +++ b/ci_checks/check-collab-overcooked.py @@ -0,0 +1,93 @@ +"""Compare the Harbor split to a direct run of the unedited upstream benchmark.""" +import ast +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import tomllib + +ROOT = Path(__file__).resolve().parents[1] + + +def check_live_isolation(catalog): + import yaml + sys.path.insert(0, str(ROOT / "scripts")) + from collab_overcooked import prepare + + images = {"sim": "sim", "role": "role", "grader": "grader"} + with tempfile.TemporaryDirectory() as tmp: + dest = Path(tmp) + source = ROOT / "game_first_exam/benchmarks/collab_overcooked" + prepare(source, dest, ["boiled_egg"], catalog, "gpt-4o", False, images) + task = dest / "collab-boiled-egg" + config = yaml.safe_load((task / "environment/docker-compose.yaml").read_text()) + services = config["services"] + for role in ("chef", "assistant"): + assert services[role]["volumes"] == [role + ":/role:ro"] + assert services[role]["secrets"] == ["model_key"] + assert services[role]["read_only"] and services[role]["cap_drop"] == ["ALL"] + assert "COLLAB_PROBE" not in services[role]["environment"] + assert not set(services["chef"]["networks"]).intersection(services["assistant"]["networks"]) + assert all(services[name]["network_mode"] == "none" and "secrets" not in services[name] + for name in ("sim", "main")) + assert int(services["sim"]["environment"]["REPEATS"]) == 10 + assert (task / "solution/solve.sh").stat().st_mode & 0o001 + + +def main(job, upstream): + catalog = tomllib.loads((ROOT / "configs/native_benchmarks/collab-overcooked.toml").read_text()) + head = subprocess.check_output(["git", "-C", upstream, "rev-parse", "HEAD"], text=True).strip() + assert head == catalog["revision"] + levels = {node.targets[0].id: ast.literal_eval(node.value) + for node in ast.parse((upstream / "src/convert_result.py").read_text()).body + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) + and node.targets[0].id.startswith("level_")} + assert levels == catalog["levels"] + check_live_isolation(catalog) + [trial_result] = job.glob("*/result.json") + trial = trial_result.parent + result = json.loads(trial_result.read_text()) + assert result["exception_info"] is None, result["exception_info"] + assert not (trial / "agent/exit-code.txt").exists(), (trial / "agent/oracle.txt").read_text() + data = trial / "artifacts" + manifest = json.loads((data / "manifest.json").read_text()) + assert any(a["source"] == "/evidence" and a["service"] == "sim" and a["status"] == "ok" for a in manifest) + timeline = (trial / "trial.log").read_text() + assert timeline.index("Main service stopped") < timeline.index("Collect hook in service 'sim' completed") + [evaluated] = (data / "evidence").rglob("experiment_*.json") + rewards = json.loads((trial / "verifier/reward.json").read_text()) + assert rewards == {"SR": 1.0, "PC": 1.0, "IC": 1.0, "RC": 1.0}, rewards + assert result["verifier_result"]["rewards"] == rewards + [config] = (job.parent / "prepared").glob("collab-*/job.json") + task = Path(json.loads(config.read_text())["tasks"][0]["path"]) + import yaml + services = yaml.safe_load((task / "environment/docker-compose.yaml").read_text())["services"] + sim = services["sim"]["image"] + for name in ("chef", "assistant"): + assert services[name]["network_mode"] == "none" and services[name]["read_only"] + assert services[name]["volumes"] == [name + ":/role:ro"] + for name in ("sim", "chef", "assistant", "main"): + assert services[name]["network_mode"] == "none" + checks = {"main.py": "src/main.py", "collab/collab.py": "src/collab/collab.py", + "collab/modules.py": "src/collab/modules.py", + "/bench/lib/overcooked_ai_py/mdp/overcooked_mdp.py": "lib/overcooked_ai/overcooked_ai_py/mdp/overcooked_mdp.py"} + grader = (task / "tests/Dockerfile").read_text().splitlines()[0].split()[1] + for image, files in ((sim, checks), (grader, {"eval_utils.py": "src/eval_utils.py", "time_step.py": "src/time_step.py"})): + hashes = subprocess.check_output(["docker", "run", "--rm", "--network", "none", image, + "sha256sum", *files], text=True).splitlines() + for line, path in zip(hashes, files.values(), strict=True): + assert line.split()[0] == hashlib.sha256((upstream / path).read_bytes()).hexdigest(), path + direct = subprocess.check_output([ + "docker", "run", "--rm", "--network", "none", + "-v", f"{ROOT}/game_first_exam/tests/collab_native_probe.py:/integration/direct.py:ro", + "-v", f"{ROOT}/game_first_exam/benchmarks/collab_overcooked/fixture_policy.py:/integration/fixture_policy.py:ro", + sim, "sh", "-ec", "python /integration/direct.py /tmp/golden >&2 && cat /tmp/golden/*/*/experiment_*.json", + ]) + assert json.loads(evaluated.read_text()) == json.loads(direct), "Native trajectories differ" + print("PASS: sealed Harbor trajectory matches direct native run; SR=PC=IC=RC=1") + + +if __name__ == "__main__": + main(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve()) diff --git a/configs/native_benchmarks/collab-overcooked.toml b/configs/native_benchmarks/collab-overcooked.toml new file mode 100644 index 0000000..b8ce3e8 --- /dev/null +++ b/configs/native_benchmarks/collab-overcooked.toml @@ -0,0 +1,11 @@ +source = "https://github.com/YusaeMeow/Collab-Overcooked.git" +revision = "d7ae1aa5e63d8ec076e96ee437fcbbd095278ef4" +repetitions = 10 + +[levels] +level_1 = ["baked_bell_pepper", "baked_sweet_potato", "boiled_egg", "boiled_mushroom", "boiled_sweet_potato"] +level_2 = ["baked_potato_slices", "baked_pumpkin_slices", "boiled_corn_slices", "boiled_green_bean_slices", "boiled_potato_slices"] +level_3 = ["baked_bell_pepper_soup", "baked_carrot_soup", "baked_mushroom_soup", "baked_potato_soup", "baked_pumpkin_soup"] +level_4 = ["sliced_bell_pepper_and_corn_stew", "sliced_bell_pepper_and_lentil_stew", "sliced_eggplant_and_chickpea_stew", "sliced_pumpkin_and_chickpea_stew", "sliced_zucchini_and_chickpea_stew"] +level_5 = ["mashed_broccoli_and_bean_patty", "mashed_carrot_and_chickpea_patty", "mashed_cauliflower_and_lentil_patty", "mashed_potato_and_pea_patty", "mashed_sweet_potato_and_bean_patty"] +level_6 = ["potato_carrot_and_onion_patty", "romaine_lettuce_pea_and_tomato_patty", "sweet_potato_spinach_and_mushroom_patty", "taro_bean_and_bell_pepper_patty", "zucchini_green_pea_and_onion_patty"] diff --git a/game_first_exam/benchmarks/collab_overcooked/Dockerfile b/game_first_exam/benchmarks/collab_overcooked/Dockerfile new file mode 100644 index 0000000..b7c2ae2 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/Dockerfile @@ -0,0 +1,44 @@ +# syntax=docker/dockerfile:1.7 +FROM python:3.10-slim-bookworm AS base +WORKDIR /bench/src +ENV PYTHONUTF8=1 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=/bench/src:/bench/lib:/integration +COPY --from=upstream /LICENSE /licenses/Collab-Overcooked +COPY --from=upstream /lib/overcooked_ai/LICENSE /licenses/Overcooked-AI + +FROM base AS dependencies +COPY requirements.txt /requirements.txt +RUN pip install --no-cache-dir -r /requirements.txt + +FROM dependencies AS role +COPY --from=upstream /src/collab/modules.py /src/collab/utils.py /src/collab/web_util.py ./collab/ +COPY --from=upstream /lib/overcooked_ai/overcooked_ai_py/mdp/actions.py /bench/lib/overcooked_ai_py/mdp/actions.py +COPY --from=upstream /lib/llama_tokenizer /bench/lib/llama_tokenizer +ENV TIKTOKEN_CACHE_DIR=/opt/tokens +RUN python -c "import tiktoken; tiktoken.encoding_for_model('gpt-4')" +COPY role.py wire.py /integration/ +RUN touch openai_key.txt +USER 65534:65534 +CMD ["python","/integration/role.py"] + +FROM role AS probe +COPY fixture_policy.py /integration/ + +FROM dependencies AS engine +COPY --from=upstream /lib/overcooked_ai/overcooked_ai_py /bench/lib/overcooked_ai_py +COPY --from=upstream /lib/overcooked_ai/setup.py /bench/lib/setup.py +RUN pip install --no-deps -e ../lib + +FROM engine AS sim +COPY --from=upstream /src/collab ./collab +COPY --from=upstream /src/main.py /src/utils.py ./ +COPY --from=upstream /src/prompts/gpt ./prompts/gpt +COPY --from=upstream /src/prompts/recipe ./prompts/recipe +COPY adapter.py wire.py /integration/ +RUN touch openai_key.txt && mkdir -p /channels/Chef /channels/Assistant /status /evidence && chown -R 65534:65534 /channels /status /evidence /bench/lib/overcooked_ai_py/data/planners && chmod 777 /channels/* /status +USER 65534:65534 +CMD ["python","/integration/adapter.py"] + +FROM engine AS grader +COPY --from=upstream /src/eval_utils.py /src/time_step.py ./ +COPY --from=upstream /src/prompts/reference ./prompts/reference +COPY grade.py /integration/ diff --git a/game_first_exam/benchmarks/collab_overcooked/README.md b/game_first_exam/benchmarks/collab_overcooked/README.md new file mode 100644 index 0000000..5537d53 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/README.md @@ -0,0 +1,27 @@ +# Collab-Overcooked + +这是 Game Exam 的原生双角色套件,入口为 `harbor run --game-suite collab-overcooked`。论文将同一模型放在 Chef(Bob)和 Assistant(Alice)两个位置。双方共享厨房状态,各有可执行动作,只有 Chef 收到完整食谱。两者通过作者定义的语言对话和 `request(...)` 协作。[论文 §3–5](https://aclanthology.org/2025.emnlp-main.249.pdf) · [固定版本的作者实现](https://github.com/YusaeMeow/Collab-Overcooked/tree/d7ae1aa5e63d8ec076e96ee437fcbbd095278ef4) + +在已按项目首页安装 Game Exam 的机器上执行。列目录只需要项目的 Python 环境。运行需要 Linux 容器、Docker Compose v2 和支持命名构建上下文的 BuildKit。 + +```bash +harbor run --game-suite collab-overcooked --list +harbor run --game-suite collab-overcooked --family level_3 --list +harbor run --game-suite collab-overcooked --offline-smoke --job-name collab-smoke -y +``` + +真实模型运行前,在宿主环境配置 `COLLAB_API_KEY`。默认模型为作者公开实现支持的 `gpt-4o`。运行时使用当前服务提供的模型版本。可通过 `OPENAI_BASE_URL` 指定角色容器能够访问的服务地址,该服务需要兼容所选模型的上游 chat 接口和重复对话检测用的 `text-embedding-3-small` 接口。上游的通用 vLLM 分支使用其自带的占位 API key,适用于允许该配置的自托管服务。 + +```bash +harbor run --game-suite collab-overcooked -i boiled_egg -m gpt-4o --job-name collab-egg -y +harbor run --game-suite collab-overcooked -m gpt-4o --job-name collab-full -y +``` + +每个 Harbor trial 对应一道菜,独立启动作者的 `main.py` 十次。完整套件为六档、每档五道菜,共 300 局。每局使用 `new_env`、两个 `LLMPair`、`fix_task` 和上游默认 120 步上限。独立 verifier 对完整轨迹执行作者的 `time_step.py`(γ=1.5)和 `Evaluation.evaluate`,以整道菜的十局为一组计算 SR、PC、IC、RC。PC 取两名角色 TES 的均值。每道菜的四项指标写入 trial 的 `verifier/reward.json`,作者的详细结果在 `verifier/evaluation_result.json`,原始轨迹在 `artifacts/evidence/raw/`。Harbor 的 agent 名称为 `oracle`,职责仅为等待模拟器结束。实际决策模型及角色策略记录在任务元数据里。 + +## 隔离与上游差异 + +- 作者的厨房引擎、调度、角色提示、动作解析、轨迹、参考动作模板与评分代码均从注册清单指定的 Git 提交构建。接入层把原本在进程内执行的规划查询和重复发言相似度调用送入对应角色容器。真实模型使用作者的 `Module.query` 和相似度实现。 +- 两个只读、非 root 的角色容器各自只能连接自己的 Unix socket。每个容器收到自己的提示和公共对话,镜像中没有食谱库、参考动作模板、轨迹或 verifier。真实模式中每个角色拥有单独的桥接网络以访问推理服务;这些网络允许出站,并未按域名限制。推理凭据通过只挂载到角色容器的 Compose secret 提供。 +- 模拟器、Harbor 主容器和独立 verifier 均关闭网络。模拟器持有食谱并记录轨迹,主容器只读运行状态。Harbor 停止主容器后从模拟器收集可信轨迹,verifier 在独立环境加载参考模板。主容器、角色与模拟器均没有 Docker socket。 +- `--offline-smoke` 针对 `boiled_egg` 运行一局,角色容器也关闭网络。固定回答和重复发言测试替身只用于 CI。CI 检查角色提示可见性、镜像中的上游文件哈希、收集来源、verifier 奖励,以及同一固定策略直接运行作者入口所产生的完整轨迹。 diff --git a/game_first_exam/benchmarks/collab_overcooked/adapter.py b/game_first_exam/benchmarks/collab_overcooked/adapter.py new file mode 100644 index 0000000..80f55cf --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/adapter.py @@ -0,0 +1,96 @@ +"""Run the upstream episode, moving only role inference across the isolation boundary.""" +import os +from pathlib import Path +import runpy +import socket +import subprocess +import sys +import time + +from wire import receive, send + +ROLES = ("Chef", "Assistant") + + +def episode(): + from collab import collab, modules + + listeners = {} + for role in ROLES: + path = Path("/channels") / role / "planner.sock" + path.unlink(missing_ok=True) + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(str(path)) + path.chmod(0o666) + listener.listen(1) + listener.settimeout(300) + listeners[role] = listener + + def call(role, request): + conn, _ = listeners[role].accept() + with conn, conn.makefile("rwb") as stream: + conn.settimeout(300) + send(stream, request) + answer = receive(stream) + if "error" in answer: + raise RuntimeError(f"{role} inference failed: {answer['error']}") + return answer["value"] + + def query(planner, key, proxy, **options): + # Upstream uses map only for its interactive human UI. + options.pop("map", None) + data = call(planner.name, {"op": "plan", "head": planner.instruction_head_list, + "user": planner.current_user_message, "options": options}) + response, tokens, updated = data + if not isinstance(response, str) or type(tokens) is not int or tokens < 0: + raise ValueError("Invalid role response") + if updated is not None: + if not isinstance(updated, str) or not planner.current_user_message["content"].startswith(updated): + raise ValueError("Invalid retry context") + planner.current_user_message["content"] = updated + return response, tokens + + # Upstream compares two spoken lines only while this role answers a teammate. + original_answer = collab.LLMAgents.answer + def answer(agent, *args, **kwargs): + def similar(key, proxy, first, second): + result = call(agent.name, {"op": "similar", "lines": [first, second]}) + if type(result) is not bool: + raise ValueError("Invalid similarity result") + return result + previous = collab.if_two_sentence_similar_meaning + collab.if_two_sentence_similar_meaning = similar + try: + return original_answer(agent, *args, **kwargs) + finally: + collab.if_two_sentence_similar_meaning = previous + + modules.Module.query = query + collab.LLMAgents.answer = answer + game_args = ["main.py", "--layout", "new_env", "--p0", "LLMPair", "--p1", "LLMPair", + "--episode", "1", "--horizon", "120", "--test_mode", "fix_task", + "--order", os.environ["ORDER"], "--gpt_model", os.environ["MODEL"], + "--statistics_save_dir", "/evidence/raw"] + sys.argv = game_args + runpy.run_path("main.py", run_name="__main__") + + +def run(): + status = Path("/status/state") + try: + for _ in range(int(os.environ["REPEATS"])): + subprocess.run([sys.executable, __file__, "episode"], check=True) + status.write_text("complete") + except Exception: + status.write_text("failed") + raise + # Harbor collects sidecar files after the main environment stops. + while True: + time.sleep(60) + + +if __name__ == "__main__": + if sys.argv[1:] == ["episode"]: + episode() + else: + run() diff --git a/game_first_exam/benchmarks/collab_overcooked/fixture_policy.py b/game_first_exam/benchmarks/collab_overcooked/fixture_policy.py new file mode 100644 index 0000000..369ee44 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/fixture_policy.py @@ -0,0 +1,25 @@ +"""Deterministic boiled-egg responses used only by the offline integration test.""" +def choose(role, messages): + prompt = messages[-1]["content"] + head, _, scene = prompt.partition("\n") + has_recipe = "Place the egg in the pot and cook for 3 timesteps" in head + assert has_recipe == (role == "Chef"), f"Incorrect recipe visibility for {role}" + assert f"Suppose you are a {role}" in head + say = "[NOTHING]" + if role == "Assistant": + if "egg" in scene and "place_obj_on_counter()" not in scene.split("Order:")[0]: + plan = "pickup(egg,ingredient_dispenser);place_obj_on_counter()" + else: + plan = "wait(3)" + elif "Scene 0:" in scene and "say history" not in scene: + plan = "request(pickup(egg,ingredient_dispenser));request(place_obj_on_counter());wait(3)" + say = "Please put an egg on the counter. [END]" + elif " holds boiled_egg" in scene: + plan = "deliver_soup()" + elif " has boiled_egg" in scene: + plan = "pickup(boiled_egg,pot0);deliver_soup()" + elif " starts processing" in scene: + plan = "wait(1)" + else: + plan = "pickup(egg,counter);put_obj_in_utensil(pot0);cook(pot0);wait(3);pickup(boiled_egg,pot0);deliver_soup()" + return f"{role} analysis: Follow the current order.\n{role} plan: {plan}\n{role} say: {say}", 0 diff --git a/game_first_exam/benchmarks/collab_overcooked/grade.py b/game_first_exam/benchmarks/collab_overcooked/grade.py new file mode 100644 index 0000000..9aa2923 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/grade.py @@ -0,0 +1,54 @@ +"""Evaluate a sealed set of complete native logs using the authors' two scoring stages.""" +import json +import math +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +from eval_utils import Evaluation, ExpLog + + +def grade(order, model, repeats, evidence, output): + raw = evidence / "raw" / model / order + logs = sorted(raw.glob("experiment_*.json")) + if len(logs) != repeats: + raise ValueError(f"Expected {repeats} complete episodes, collected {len(logs)}") + for log in logs: + data = json.loads(log.read_text()) + ticks = data["total_timestamp"] + if (not ticks or ticks != list(range(len(ticks))) or len(data["content"]) != len(ticks) + or data["total_order_finished"] not in ([], [order]) + or (not data["total_order_finished"] and len(ticks) != 120)): + raise ValueError(f"Incomplete native trajectory in {log.name}") + # time_step.py hardcodes this directory label. It operates only on logs, + # and never consults the model name while applying the timing rule. + label = Path("deepseek-ai/DeepSeek-V3") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + input_dir = root / "src/data" / label / order + input_dir.mkdir(parents=True) + for log in logs: + shutil.copyfile(log, input_dir / log.name) + subprocess.run([sys.executable, str(Path("time_step.py").resolve())], cwd=root, check=True) + truncated = root / "src/data/truncate_1_5" / label / order + episodes = ExpLog(str(truncated)) + if len(episodes) != repeats: + raise ValueError("The native evaluator did not load every episode") + output.mkdir(exist_ok=True, parents=True) + result = Evaluation(order_name_list=[order] * repeats, exp_log=episodes).evaluate(str(output))[order] + tes = result["average"]["similarity_and_redundancy"] + scores = {"SR": result["task_metrics"]["success_rate"], + "PC": (tes["agent_0"]["mean_f1"] + tes["agent_1"]["mean_f1"]) / 2, + "IC": result["statistic"]["initiate_collaboration"], + "RC": result["statistic"]["respond_collaboration"]} + if not all(math.isfinite(value) and 0 <= value <= 1 for value in scores.values()): + raise ValueError("Invalid native metric") + (output / "reward.json").write_text(json.dumps(scores, allow_nan=False)) + return scores + + +if __name__ == "__main__": + order, model, repeats = json.loads(Path("/tests/selection.json").read_text()) + grade(order, model, repeats, Path("/evidence"), Path("/logs/verifier")) diff --git a/game_first_exam/benchmarks/collab_overcooked/requirements.txt b/game_first_exam/benchmarks/collab_overcooked/requirements.txt new file mode 100644 index 0000000..c9d3592 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/requirements.txt @@ -0,0 +1,17 @@ +setuptools==75.8.0 +numpy==1.23.5 +scipy==1.10.1 +pandas==1.5.3 +gym==0.26.2 +rich==13.5.2 +openai==1.54.3 +httpx==0.27.2 +tiktoken==0.8.0 +transformers==4.46.3 +websocket-client==1.8.0 +websockets==12.0 +dtw-python==1.5.3 +scikit-learn==1.5.2 +plotly==5.24.1 +importlib-metadata==8.5.0 +matplotlib==3.7.5 diff --git a/game_first_exam/benchmarks/collab_overcooked/role.py b/game_first_exam/benchmarks/collab_overcooked/role.py new file mode 100644 index 0000000..b6daaf9 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/role.py @@ -0,0 +1,71 @@ +"""One role per service. The live path calls the authors' original inference module.""" +import os +from pathlib import Path +import socket +import time + +from wire import receive, send + + +def main(): + from collab import modules + + role = os.environ["ROLE"] + model = os.environ["MODEL"] + assert role in {"Chef", "Assistant"} + assert not any(Path(p).exists() for p in ( + "prompts", "main.py", "eval_utils.py", "/evidence", "/channels", "/tests", "/var/run/docker.sock")) + probe = os.getenv("COLLAB_PROBE") == "1" + if probe: + from fixture_policy import choose + assert sorted(os.listdir("/sys/class/net")) == ["lo"] + else: + # The author code reads its key file in the embedding helper and its + # cached module variable in the chat helper. Both see the same secret. + modules.gpt4_key_file = "/run/secrets/model_key" + modules.openai_key = Path(modules.gpt4_key_file).read_text().strip() + modules.openai.api_base = os.environ["OPENAI_BASE_URL"] + if not modules.openai_key: + raise ValueError("Missing model credential") + + while True: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn: + try: + conn.connect("/role/planner.sock") + except (FileNotFoundError, ConnectionRefusedError): + time.sleep(0.1) + continue + with conn.makefile("rwb") as stream: + try: + try: + item = receive(stream) + except (ConnectionResetError, ValueError): + # Each fresh upstream episode recreates its private sockets. + continue + if item["op"] == "similar": + if probe: + value = item["lines"][0] == item["lines"][1] + else: + value = bool(modules.if_two_sentence_similar_meaning("", "", *item["lines"])) + elif item["op"] == "plan": + planner = modules.Module(item["head"], model=model, model_dirname="", + local_server_api=os.getenv("OPENAI_BASE_URL"), K=0) + planner.current_user_message = item["user"].copy() + if probe: + response, tokens = choose(role, planner.query_messages(False)) + else: + response, tokens = planner.query(key="", proxy="", **item["options"]) + # Native retries may shorten the current message before + # returning an empty answer to the controller for correction. + current = planner.current_user_message["content"] + value = [response, tokens, current if current != item["user"]["content"] else None] + else: + raise ValueError("Unknown role request") + except Exception as exc: + send(stream, {"error": type(exc).__name__}) + raise + send(stream, {"value": value}) + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/benchmarks/collab_overcooked/task/environment/Dockerfile b/game_first_exam/benchmarks/collab_overcooked/task/environment/Dockerfile new file mode 100644 index 0000000..5b48a1a --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/environment/Dockerfile @@ -0,0 +1,4 @@ +FROM python:3.10-slim-bookworm +WORKDIR /app +RUN mkdir /status /solution && chmod 777 /status && chmod 755 /solution +USER 65534:65534 diff --git a/game_first_exam/benchmarks/collab_overcooked/task/environment/docker-compose.yaml b/game_first_exam/benchmarks/collab_overcooked/task/environment/docker-compose.yaml new file mode 100644 index 0000000..c95a2c3 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/environment/docker-compose.yaml @@ -0,0 +1,35 @@ +services: + main: + network_mode: none + depends_on: [sim, chef, assistant] + volumes: ["status:/status:ro"] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + sim: + image: SIM_IMAGE + pull_policy: never + network_mode: none + environment: + ORDER: ORDER_NAME + MODEL: MODEL_NAME + REPEATS: "EPISODES" + volumes: ["chef:/channels/Chef", "assistant:/channels/Assistant", "status:/status"] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + chef: &role + image: ROLE_IMAGE + pull_policy: never + read_only: true + user: "65534:65534" + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + environment: {ROLE: Chef, MODEL: MODEL_NAME} + volumes: ["chef:/role:ro"] + assistant: + <<: *role + environment: {ROLE: Assistant, MODEL: MODEL_NAME} + volumes: ["assistant:/role:ro"] +volumes: + chef: {} + assistant: {} + status: {} diff --git a/game_first_exam/benchmarks/collab_overcooked/task/instruction.md b/game_first_exam/benchmarks/collab_overcooked/task/instruction.md new file mode 100644 index 0000000..ef00a82 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/instruction.md @@ -0,0 +1 @@ +Run the native Chef and Assistant controllers on ORDER_NAME. The simulator provides each role with its own observation, action vocabulary and dialogue. The Chef receives the recipe. The Assistant can ask for instructions. The trial ends after EPISODES episodes. Harbor collects the simulator's trajectories and grades success, progress and collaboration in a separate verifier. The main container can read the trial status from /status/state. diff --git a/game_first_exam/benchmarks/collab_overcooked/task/solution/solve.sh b/game_first_exam/benchmarks/collab_overcooked/task/solution/solve.sh new file mode 100644 index 0000000..11a286d --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/solution/solve.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +test "$(id -u)" = 65534 +test "$(ls /sys/class/net)" = lo +for path in /bench /evidence /tests /channels /role /var/run/docker.sock /run/secrets/model_key; do test ! -e "$path"; done +test ! -w /status +touch /logs/verifier/agent-marker +while [ ! -s /status/state ]; do sleep 1; done +test "$(cat /status/state)" = complete diff --git a/game_first_exam/benchmarks/collab_overcooked/task/task.toml b/game_first_exam/benchmarks/collab_overcooked/task/task.toml new file mode 100644 index 0000000..88f3a4e --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/task.toml @@ -0,0 +1,26 @@ +schema_version = "1.3" +artifacts = [{ source = "/evidence", service = "sim" }] + +[task] +name = "game-exam/ORDER_SLUG" +description = "Collab-Overcooked native two-role episode group" + +[metadata] +protocol = "collab-overcooked/native" +source_commit = "REVISION" +model = "MODEL_NAME" +episodes = EPISODES +policy = "POLICY" + +[agent] +user = "65534" +timeout_sec = TRIAL_TIMEOUT + +[verifier] +environment_mode = "separate" +network_mode = "no-network" +timeout_sec = 300 + +[[verifier.collect]] +service = "sim" +command = "test \"$(cat /status/state)\" = complete && test ! -e /logs/verifier && test ! -e /run/secrets/model_key && test ! -d /bench/src/prompts/reference" diff --git a/game_first_exam/benchmarks/collab_overcooked/task/tests/Dockerfile b/game_first_exam/benchmarks/collab_overcooked/task/tests/Dockerfile new file mode 100644 index 0000000..6ee0f0e --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/tests/Dockerfile @@ -0,0 +1,4 @@ +FROM GRADER_IMAGE +COPY selection.json /tests/selection.json +COPY test.sh /tests/test.sh +RUN chmod +x /tests/test.sh diff --git a/game_first_exam/benchmarks/collab_overcooked/task/tests/docker-compose.yaml b/game_first_exam/benchmarks/collab_overcooked/task/tests/docker-compose.yaml new file mode 100644 index 0000000..f9e01ab --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/tests/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + network_mode: none diff --git a/game_first_exam/benchmarks/collab_overcooked/task/tests/test.sh b/game_first_exam/benchmarks/collab_overcooked/task/tests/test.sh new file mode 100644 index 0000000..bfdc219 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/task/tests/test.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +test "$(ls /sys/class/net)" = lo +test ! -e /solution +test ! -e /status +test ! -e /role +test ! -e /run/secrets/model_key +test ! -e /var/run/docker.sock +test ! -e /logs/verifier/agent-marker +cd /bench/src +python /integration/grade.py diff --git a/game_first_exam/benchmarks/collab_overcooked/wire.py b/game_first_exam/benchmarks/collab_overcooked/wire.py new file mode 100644 index 0000000..2588b88 --- /dev/null +++ b/game_first_exam/benchmarks/collab_overcooked/wire.py @@ -0,0 +1,19 @@ +"""One request and one response on an already role-bound Unix socket.""" +import json + +LIMIT = 2 * 1024 * 1024 + + +def send(stream, value): + data = json.dumps(value, allow_nan=False).encode() + b"\n" + if len(data) > LIMIT: + raise ValueError("Collab-Overcooked message exceeds size limit") + stream.write(data) + stream.flush() + + +def receive(stream): + data = stream.readline(LIMIT + 1) + if not data.endswith(b"\n") or len(data) > LIMIT: + raise ValueError("Incomplete or oversized Collab-Overcooked message") + return json.loads(data) diff --git a/game_first_exam/tests/collab_native_probe.py b/game_first_exam/tests/collab_native_probe.py new file mode 100644 index 0000000..4e4cc47 --- /dev/null +++ b/game_first_exam/tests/collab_native_probe.py @@ -0,0 +1,23 @@ +"""Drive the pristine upstream CLI with the same deterministic role responses as CI.""" +import os +from pathlib import Path +import runpy +import sys +from unittest.mock import patch + +from collab import collab, modules +from fixture_policy import choose + + +def query(planner, key, proxy, **options): + return choose(planner.name, planner.query_messages(options.get("rethink", False))) + + +if __name__ == "__main__": + output = Path(sys.argv[1]).resolve() + sys.argv = ["main.py", "--order", "boiled_egg", "--gpt_model", "gpt-4o", + "--statistics_save_dir", str(output)] + with patch.object(modules.Module, "query", query), patch.object( + collab, "if_two_sentence_similar_meaning", lambda key, proxy, left, right: left == right + ): + runpy.run_path(os.path.abspath("main.py"), run_name="__main__") diff --git a/scripts/collab_overcooked.py b/scripts/collab_overcooked.py new file mode 100644 index 0000000..5313710 --- /dev/null +++ b/scripts/collab_overcooked.py @@ -0,0 +1,119 @@ +"""Prepare native Collab-Overcooked recipe groups and hand them to Harbor.""" +import argparse +import fnmatch +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import tomllib + + +def select(catalog, families, include, exclude, limit): + levels = catalog["levels"] + if set(families) - levels.keys(): + raise ValueError("Unknown recipe family (choose level_1 through level_6)") + orders = [order for level, group in levels.items() if not families or level in families + for order in group if (not include or any(fnmatch.fnmatchcase(order, p) for p in include)) + and not any(fnmatch.fnmatchcase(order, p) for p in exclude)] + if limit is not None: + orders = orders[:limit] + if not orders: + raise ValueError("No matching Collab-Overcooked recipes") + return orders + + +def build_images(source, catalog, smoke): + digest = hashlib.sha256(catalog["revision"].encode()) + for file in sorted(source.iterdir()): + if file.is_file(): + digest.update(file.read_bytes()) + images = {} + for target in ("sim", "probe" if smoke else "role", "grader"): + tag = f"game-exam-collab-{target}:{digest.hexdigest()[:16]}" + upstream = catalog["source"] + "#" + catalog["revision"] + subprocess.run(["docker", "build", "--build-context", "upstream=" + upstream, + "--target", target, "-t", tag, str(source)], check=True) + images[target] = tag + return images + + +def prepare(source, dest, orders, catalog, model, smoke, images): + repeats = 1 if smoke else catalog["repetitions"] + policy = "offline-fixture" if smoke else "upstream-llmpair" + tasks = [] + for order in orders: + task = dest / ("collab-" + order.replace("_", "-")) + replacements = {"SIM_IMAGE": images["sim"], "ROLE_IMAGE": images["probe" if smoke else "role"], + "GRADER_IMAGE": images["grader"], "ORDER_NAME": order, "ORDER_SLUG": task.name, + "EPISODES": str(repeats), "TRIAL_TIMEOUT": str(1800 * repeats if smoke else 86400), + "MODEL_NAME": model, "REVISION": catalog["revision"], "POLICY": policy} + for file in (source / "task").rglob("*"): + if not file.is_file(): + continue + target = task / file.relative_to(source / "task") + target.parent.mkdir(parents=True, exist_ok=True) + content = file.read_text(encoding="utf-8") + if file.name == "docker-compose.yaml" and file.parent.name == "environment": + for role in ("Chef", "Assistant"): + mount = ' volumes: ["' + role.lower() + ':/role:ro"]' + network = " network_mode: none" if smoke else " networks: [" + role.lower() + "_egress]" + settings = "COLLAB_PROBE: '1'" if smoke else 'OPENAI_BASE_URL: "${OPENAI_BASE_URL:-https://api.openai.com/v1}"' + content = content.replace("{ROLE: " + role + ", MODEL: MODEL_NAME}", + "{ROLE: " + role + ", MODEL: MODEL_NAME, " + settings + "}") + content = content.replace(mount, mount + "\n" + network) + if not smoke: + content = content.replace(" read_only: true", " secrets: [model_key]\n read_only: true") + content += "\nnetworks:\n chef_egress: {}\n assistant_egress: {}\nsecrets:\n model_key:\n environment: COLLAB_API_KEY\n" + for key, value in replacements.items(): + content = content.replace(key, value) + target.write_text(content, encoding="utf-8", newline="\n") + if target.suffix == ".sh": + target.chmod(0o755) + (task / "tests/selection.json").write_text(json.dumps([order, model, repeats])) + tasks.append({"path": str(task)}) + config = {"tasks": tasks, "agents": [{"name": "oracle"}], "n_attempts": 1, + "n_concurrent_trials": 1, "retry": {"max_retries": 0}} + path = dest / "job.json" + path.write_text(json.dumps(config, indent=2)) + return path + + +def launch(root, families, include, exclude, limit, listing, args, harbor): + catalog = tomllib.loads((root / "configs/native_benchmarks/collab-overcooked.toml").read_text()) + parser = argparse.ArgumentParser(prog="harbor run --game-suite collab-overcooked") + parser.add_argument("--offline-smoke", action="store_true", help="fixed boiled-egg responses, no model calls") + parser.add_argument("-m", "--model", default="gpt-4o") + parser.add_argument("--job-name") + parser.add_argument("--jobs-dir", type=Path) + parser.add_argument("-y", "--yes", action="store_true") + options = parser.parse_args(args) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?", options.model): + raise ValueError("Invalid upstream model identifier") + if options.model == "human" or ("gpt" in options.model.lower() and options.model not in {"gpt-4o", "gpt-3.5-turbo-0125"}): + raise ValueError("Select a supported upstream chat model (e.g. gpt-4o)") + orders = select(catalog, families, include, exclude, limit) + if options.offline_smoke: + if "boiled_egg" not in orders or options.model != "gpt-4o": + raise ValueError("The offline smoke fixture covers boiled_egg with the gpt-4o prompt format") + orders = ["boiled_egg"] + if listing: + print("\n".join(orders)) + return 0 + if not options.offline_smoke and not os.environ.get("COLLAB_API_KEY"): + raise ValueError("Set COLLAB_API_KEY for the native model or select --offline-smoke") + source = root / "game_first_exam/benchmarks/collab_overcooked" + images = build_images(source, catalog, options.offline_smoke) + prepared = root / "jobs/prepared" + prepared.mkdir(parents=True, exist_ok=True) + dest = Path(tempfile.mkdtemp(prefix="collab-", dir=prepared)) + config = prepare(source, dest, orders, catalog, options.model, options.offline_smoke, images) + argv = ["run", "-c", str(config)] + if options.job_name: + argv.extend(["--job-name", options.job_name]) + argv.extend(["--jobs-dir", str((options.jobs_dir or Path("jobs")).resolve())]) + if options.yes: + argv.append("-y") + return harbor(argv) diff --git a/scripts/efe.py b/scripts/efe.py index 16d55c7..1f62303 100755 --- a/scripts/efe.py +++ b/scripts/efe.py @@ -335,6 +335,16 @@ def run(argv: list[str], app=None) -> int: games = _Scripts("prepare_games") if game_suite is None: game_suite = "all" if which == "all" else "core" + if game_suite == "collab-overcooked": + if modes or benches or paths or which != "core": + print("Collab-Overcooked uses the native two-role protocol. Select recipes with --family or -i.", file=sys.stderr) + return 2 + try: + return _Scripts("collab_overcooked").launch( + find_root(), families, inc, exc, n_tasks, listing, rest, lambda args: harbor(args, app)) + except (ValueError, OSError) as exc: + print(str(exc), file=sys.stderr) + return 2 if game_suite is not None: try: suite, plans = games.load_suite(game_suite)