BioOcto / scripts /run_bioagentbench_deepseek_v4_parallel.py
czty's picture
BioOcto code and data release (snapshot 2026-11-27, sanitized) (part 45)
7fcf0b3 verified
Raw History Blame Contribute Delete
12.2 kB
#!/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())