File size: 12,188 Bytes
7fcf0b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
"""Parallel BioAgentBench rerun scheduler for BioManus vs Biomni-2000.

The script intentionally does not implement benchmark logic. It launches the
existing method-specific runners with separate output roots and bounded
parallelism so long-running jobs can be monitored or resumed from logs.
"""

from __future__ import annotations

import argparse
import json
import os
import shlex
import signal
import subprocess
import sys
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path


PROJECT_ROOT = Path("/225040511/project/Beyond_Prompt-Based_Planning")
ENV_FILE = Path("/225040511/project/.env")
PYTHON_BIN = Path("/225040511/miniconda3/envs/biomni_e1/bin/python")
EXEC_ENV_PREFIX = Path("/225040511/miniconda3/envs/biomni_e1")
BIOAGENT_BENCH_ROOT = PROJECT_ROOT / "bioagent-bench"
BIOAGENT_METADATA = BIOAGENT_BENCH_ROOT / "src" / "task_metadata.json"
BIOAGENT_DATASET_ROOT = BIOAGENT_BENCH_ROOT / "dataset"

TASKS = [
    "alzheimer-mouse",
    "comparative-genomics",
    "cystic-fibrosis",
    "deseq",
    "evolution",
    "giab",
    "metagenomics",
    "single-cell",
    "transcript-quant",
    "viral-metagenomics",
]


def utc_stamp() -> str:
    return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")


def load_dotenv(path: Path) -> dict[str, str]:
    env: dict[str, str] = {}
    if not path.exists():
        return env
    for raw in path.read_text(encoding="utf-8", errors="ignore").splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        if line.startswith("export "):
            line = line[len("export ") :].strip()
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip("'").strip('"')
        if key:
            env[key] = value
    return env


@dataclass(frozen=True)
class Job:
    method: str
    task: str
    cmd: list[str]
    log_path: Path
    output_root: Path


@dataclass
class RunningJob:
    job: Job
    process: subprocess.Popen
    log_handle: object
    started: float


def build_env(args: argparse.Namespace) -> dict[str, str]:
    env = os.environ.copy()
    env.update(load_dotenv(ENV_FILE))
    if not env.get("DEEPSEEK_API_KEY"):
        raise SystemExit(f"DEEPSEEK_API_KEY is required in {ENV_FILE}")

    base_url = args.base_url or env.get("DEEPSEEK_BASE_URL") or "https://api.deepseek.com/v1"
    model = args.model

    env["DEEPSEEK_BASE_URL"] = base_url
    env["DEEPSEEK_MODEL_NAME"] = model
    env["BIOMNI_LLM_PROVIDER"] = "deepseek"
    env["BIOMNI_CUSTOM_API_KEY"] = env.get("BIOMNI_CUSTOM_API_KEY") or env["DEEPSEEK_API_KEY"]
    env["BIOMNI_CUSTOM_BASE_URL"] = env.get("BIOMNI_CUSTOM_BASE_URL") or base_url
    env["BIOMNI_LLM"] = model
    env["BIOMNI_SOURCE"] = "Custom"
    env["BIOMNI_TIMEOUT_SECONDS"] = str(args.timeout_seconds)
    env["BIOMNI_MCP_TIMEOUT_SECONDS"] = env.get("BIOMNI_MCP_TIMEOUT_SECONDS", "180")
    env["BIOMNI_EXECUTION_ENV_PREFIX"] = str(EXEC_ENV_PREFIX)
    if args.temperature is not None:
        env["BIOMNI_TEMPERATURE"] = str(args.temperature)
    return env


def build_jobs(args: argparse.Namespace, run_id: str) -> tuple[list[Job], dict[str, Path]]:
    root = PROJECT_ROOT / "experiments" / "deepseek_v4_bioagentbench_parallel" / run_id
    logs_dir = root / "logs"
    logs_dir.mkdir(parents=True, exist_ok=True)

    biomanus_root = root / "biomanus"
    biomni_root = root / "biomni_2000"
    biomanus_root.mkdir(parents=True, exist_ok=True)
    biomni_root.mkdir(parents=True, exist_ok=True)

    biomanus_runner = PROJECT_ROOT / "Biomanus" / "run_bioagent_bench.py"
    biomni_runner = (
        PROJECT_ROOT
        / "Biomni"
        / "experiments"
        / "bioagent_bench"
        / "scripts"
        / "run_bioagent_bench_with_biomni.py"
    )
    biomni_mcp = (
        PROJECT_ROOT / "Biomni" / "experiments" / "bioagent_bench" / "configs" / "mcp_scale_2000.yaml"
    )

    jobs: list[Job] = []
    for task in TASKS:
        if "biomanus" in args.methods:
            cmd = [
                str(PYTHON_BIN),
                str(biomanus_runner),
                "--task",
                task,
                "--output-root",
                str(biomanus_root),
                "--metadata",
                str(BIOAGENT_METADATA),
                "--dataset-root",
                str(BIOAGENT_DATASET_ROOT),
                "--execution-env-prefix",
                str(EXEC_ENV_PREFIX),
                "--timeout-seconds",
                str(args.timeout_seconds),
                "--mcp-server-top-k",
                "20",
                "--mcp-tool-top-k",
                "12",
                "--validation-retries",
                str(args.validation_retries),
                "--llm",
                args.model,
                "--source",
                "Custom",
                "--base-url",
                args.base_url or "https://api.deepseek.com/v1",
            ]
            jobs.append(Job("biomanus", task, cmd, logs_dir / f"biomanus_{task}.log", biomanus_root))
        if "biomni2000" in args.methods:
            cmd = [
                str(PYTHON_BIN),
                str(biomni_runner),
                "--task",
                task,
                "--output-root",
                str(biomni_root),
                "--metadata",
                str(BIOAGENT_METADATA),
                "--dataset-root",
                str(BIOAGENT_DATASET_ROOT),
                "--mcp-config",
                str(biomni_mcp),
                "--use-mcp",
                "--force-rerun",
                "--execution-env-prefix",
                str(EXEC_ENV_PREFIX),
                "--timeout-seconds",
                str(args.timeout_seconds),
                "--llm",
                args.model,
                "--source",
                "Custom",
                "--base-url",
                args.base_url or "https://api.deepseek.com/v1",
            ]
            jobs.append(Job("biomni2000", task, cmd, logs_dir / f"biomni2000_{task}.log", biomni_root))
    return jobs, {"root": root, "logs": logs_dir, "biomanus": biomanus_root, "biomni2000": biomni_root}


def redact_cmd(cmd: list[str]) -> str:
    return " ".join(shlex.quote(part) for part in cmd)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", default="deepseek-v4")
    parser.add_argument("--base-url", default=None)
    parser.add_argument("--temperature", type=float, default=None)
    parser.add_argument("--timeout-seconds", type=int, default=1200)
    parser.add_argument("--validation-retries", type=int, default=0)
    parser.add_argument("--max-jobs", type=int, default=3)
    parser.add_argument("--max-per-method", type=int, default=2)
    parser.add_argument(
        "--methods",
        nargs="+",
        choices=["biomanus", "biomni2000"],
        default=["biomanus", "biomni2000"],
    )
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    run_id = utc_stamp()
    env = build_env(args)
    jobs, paths = build_jobs(args, run_id)
    manifest_path = paths["root"] / "manifest.json"
    status_path = paths["root"] / "status.jsonl"

    manifest = {
        "run_id": run_id,
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "model": args.model,
        "base_url": env["DEEPSEEK_BASE_URL"],
        "temperature": env.get("BIOMNI_TEMPERATURE"),
        "timeout_seconds": args.timeout_seconds,
        "max_jobs": args.max_jobs,
        "max_per_method": args.max_per_method,
        "methods": args.methods,
        "tasks": TASKS,
        "paths": {key: str(value) for key, value in paths.items()},
        "jobs": [
            {
                "method": job.method,
                "task": job.task,
                "log_path": str(job.log_path),
                "output_root": str(job.output_root),
                "cmd": redact_cmd(job.cmd),
            }
            for job in jobs
        ],
    }
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"run_id={run_id}")
    print(f"root={paths['root']}")
    print(f"manifest={manifest_path}")
    print(f"jobs={len(jobs)} max_jobs={args.max_jobs} max_per_method={args.max_per_method}")

    if args.dry_run:
        return 0

    pending = jobs[:]
    running: list[RunningJob] = []
    failures = 0
    interrupted = False

    def terminate(signum, _frame):
        nonlocal interrupted
        interrupted = True
        pending.clear()
        print(f"received signal {signum}; terminating running jobs", flush=True)
        for item in running:
            item.process.terminate()

    signal.signal(signal.SIGTERM, terminate)
    signal.signal(signal.SIGINT, terminate)

    with status_path.open("a", encoding="utf-8") as status:
        while pending or running:
            method_counts: dict[str, int] = {}
            for item in running:
                method_counts[item.job.method] = method_counts.get(item.job.method, 0) + 1

            while pending and len(running) < args.max_jobs and not interrupted:
                next_index = None
                for idx, job in enumerate(pending):
                    if method_counts.get(job.method, 0) < args.max_per_method:
                        next_index = idx
                        break
                if next_index is None:
                    break
                job = pending.pop(next_index)
                log = job.log_path.open("w", encoding="utf-8")
                log.write(f"started_utc={datetime.now(timezone.utc).isoformat()}\n")
                log.write(f"method={job.method}\ntask={job.task}\n")
                log.write(f"cmd={redact_cmd(job.cmd)}\n\n")
                log.flush()
                process = subprocess.Popen(job.cmd, stdout=log, stderr=subprocess.STDOUT, env=env, cwd=str(PROJECT_ROOT))
                running.append(RunningJob(job, process, log, time.time()))
                method_counts[job.method] = method_counts.get(job.method, 0) + 1
                record = {
                    "event": "started",
                    "time_utc": datetime.now(timezone.utc).isoformat(),
                    "method": job.method,
                    "task": job.task,
                    "pid": process.pid,
                    "log_path": str(job.log_path),
                }
                status.write(json.dumps(record) + "\n")
                status.flush()
                print(f"START {job.method:10s} {job.task:22s} pid={process.pid} log={job.log_path}", flush=True)

            for item in running[:]:
                code = item.process.poll()
                if code is None:
                    continue
                elapsed = time.time() - item.started
                item.log_handle.write(f"\nfinished_utc={datetime.now(timezone.utc).isoformat()}\nexit_code={code}\n")
                item.log_handle.close()
                running.remove(item)
                if code != 0:
                    failures += 1
                record = {
                    "event": "finished",
                    "time_utc": datetime.now(timezone.utc).isoformat(),
                    "method": item.job.method,
                    "task": item.job.task,
                    "pid": item.process.pid,
                    "exit_code": code,
                    "elapsed_seconds": round(elapsed, 3),
                    "log_path": str(item.job.log_path),
                }
                status.write(json.dumps(record) + "\n")
                status.flush()
                print(
                    f"DONE  {item.job.method:10s} {item.job.task:22s} "
                    f"exit={code} elapsed_min={elapsed / 60:.1f}",
                    flush=True,
                )

            if interrupted and running:
                time.sleep(2)
            elif pending or running:
                time.sleep(15)

    print(f"finished run_id={run_id} failures={failures} status={status_path}")
    return 130 if interrupted else (1 if failures else 0)


if __name__ == "__main__":
    raise SystemExit(main())