Download drb.py from xiaojie06/DrugResearchBench: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/xiaojie06/DrugResearchBench/resolve/main/drb.py
- Command line
-
hf download hf://xiaojie06/DrugResearchBench/drb.py
-
curl -L -o drb.py https://huggingface.co/xiaojie06/DrugResearchBench/resolve/main/drb.py
14.5 kB
| """Portable DrugResearchBench release utilities. Requires Python >=3.9.""" | |
| import argparse | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tarfile | |
| import tempfile | |
| import urllib.request | |
| import contextlib | |
| ROOT = Path(__file__).resolve().parent | |
| CONDITIONS = ("g61_R1", "g61_R2", "g6_R1", "g6_R2", "luna_R1", "luna_R2") | |
| def require(value, explanation): | |
| if not value: | |
| raise ValueError(explanation) | |
| def load(path): | |
| with Path(path).open(encoding="utf-8") as handle: | |
| return json.load(handle) | |
| def sha(path): | |
| result = hashlib.sha256() | |
| with Path(path).open("rb") as handle: | |
| for block in iter(lambda: handle.read(2**20), b""): | |
| result.update(block) | |
| return result.hexdigest() | |
| def allow_sandbox_read(path, existing=False): | |
| """Let the unprivileged runner read a staged file when an administrator unpacked it.""" | |
| if os.name != "posix" or os.geteuid() != 0: | |
| return | |
| uid = int(os.environ.get("SUDO_UID", 65534)) | |
| gid = int(os.environ.get("SUDO_GID", 65534)) | |
| info = path.stat() | |
| readable = (info.st_mode & 0o004 or | |
| info.st_uid == uid and info.st_mode & 0o400 or | |
| info.st_gid == gid and info.st_mode & 0o040) | |
| if readable or gid <= 0: | |
| return | |
| if existing: | |
| # Replacing the workspace copy leaves an original hard-linked archive untouched. | |
| with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as h: | |
| temporary = Path(h.name) | |
| try: | |
| shutil.copyfile(path, temporary) | |
| allow_sandbox_read(temporary) | |
| os.replace(temporary, path) | |
| finally: | |
| temporary.unlink(missing_ok=True) | |
| return | |
| os.chown(path, -1, gid) | |
| path.chmod((info.st_mode & 0o777) | 0o040) | |
| def relative(value): | |
| path = PurePosixPath(value) | |
| require(path.parts and not path.is_absolute() and ".." not in path.parts and "\\" not in value, "Unsafe path") | |
| return path | |
| def within(base, name): | |
| path = (base / relative(name)).resolve() | |
| require(base.resolve() in path.parents, "Path escapes task") | |
| return path | |
| def task(pid): | |
| require(pid and pid.isalnum(), "Invalid task ID") | |
| result = ROOT / "tasks" / pid | |
| require((result / "task.json").is_file(), "Unknown task. See registry.json") | |
| return result | |
| def unpack(folder, section=None): | |
| for entry in load(folder / "bundles.json"): | |
| if section=="formal" and not entry["file"].startswith("trajectories/runs-"):continue | |
| if section and section!="formal" and not entry["file"].startswith(section+"/"):continue | |
| with contextlib.ExitStack() as stack: | |
| if entry.get("parts"): | |
| stream=stack.enter_context(tempfile.TemporaryFile()) | |
| digest=hashlib.sha256() | |
| for item in entry["parts"]: | |
| part=folder/relative(item["file"]) | |
| require(part.stat().st_size==item["bytes"] and sha(part)==item["sha256"],"Sharded transfer integrity failure") | |
| with part.open("rb") as f: | |
| for block in iter(lambda:f.read(2**20),b""): | |
| digest.update(block);stream.write(block) | |
| require(stream.tell()==entry["bytes"] and digest.hexdigest()==entry["sha256"],"Reassembled archive mismatch") | |
| stream.seek(0) | |
| source=stack.enter_context(tarfile.open(fileobj=stream,mode="r:gz")) | |
| else: | |
| archive = folder / entry["file"] | |
| require(archive.stat().st_size == entry["bytes"] and sha(archive) == entry["sha256"], "Archive integrity failure") | |
| source=stack.enter_context(tarfile.open(archive, "r:gz")) | |
| seen = set() | |
| for item in source: | |
| dest = within(folder, item.name) | |
| require(item.isfile() and item.name not in seen, "Expected distinct regular files") | |
| seen.add(item.name) | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.NamedTemporaryFile(dir=dest.parent, delete=False) as h: | |
| tmp = Path(h.name) | |
| try: | |
| with source.extractfile(item) as stream: | |
| shutil.copyfileobj(stream, h) | |
| except BaseException: | |
| tmp.unlink(missing_ok=True) | |
| raise | |
| if dest.exists(): | |
| require(sha(tmp) == sha(dest), "Existing unpacked file differs: " + item.name) | |
| tmp.unlink() | |
| allow_sandbox_read(dest, existing=True) | |
| else: | |
| allow_sandbox_read(tmp) | |
| os.replace(tmp, dest) | |
| for prefix in ("inputs","oracle","trajectories","implementation"): | |
| if section and prefix!=("trajectories" if section=="formal" else section):continue | |
| alias_file=folder/prefix/"identical_members.json" | |
| for item in (load(alias_file) if alias_file.exists() else []): | |
| if section=="formal" and item["path"].startswith("trajectories/history/"):continue | |
| src=within(folder,item["canonical"]) | |
| dst=within(folder,item["path"]) | |
| require(sha(src)==item["sha256"],"Alias digest mismatch") | |
| dst.parent.mkdir(parents=True,exist_ok=True) | |
| if dst.exists(): | |
| require(sha(dst)==item["sha256"],"Existing expanded file differs") | |
| allow_sandbox_read(dst, existing=True) | |
| else: | |
| shutil.copyfile(src,dst) | |
| allow_sandbox_read(dst) | |
| return {"task": folder.name, "unpacked": True} | |
| def verify_inputs(folder, source=None, fetch=False, mode="original"): | |
| items = load(folder / ("inputs/manifest.json" if mode=="original" else "tests/changed_manifest.json"))["assets"] | |
| require(items, "Empty input inventory") | |
| missing = [] | |
| for item in items: | |
| dst = within(folder / ("workspace/input" if mode=="original" else "tests/changed"), item["path"]) | |
| def good(p): | |
| return p.is_file() and p.stat().st_size == item["bytes"] and sha(p) == item["sha256"] | |
| if good(dst): | |
| allow_sandbox_read(dst, existing=True) | |
| continue | |
| local = within(source, item["path"]) if source else None | |
| if mode=="hidden" and item.get("distribution")=="reuse_original": | |
| original=within(folder/"workspace/input",item["path"]) | |
| if good(original):local=original | |
| direct = item.get("download_url") | |
| if not ((local and good(local)) or (fetch and direct)): | |
| missing.append(item["path"]) | |
| continue | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.NamedTemporaryFile(dir=dst.parent, delete=False) as h: | |
| tmp = Path(h.name) | |
| try: | |
| if local and good(local): | |
| shutil.copyfile(local, tmp) | |
| else: | |
| require(direct.startswith("https://"), "HTTPS source required") | |
| with urllib.request.urlopen(direct, timeout=90) as stream, tmp.open("wb") as out: | |
| shutil.copyfileobj(stream, out) | |
| require(good(tmp), "Upstream byte identity differs: " + item["path"]) | |
| allow_sandbox_read(tmp) | |
| os.replace(tmp, dst) | |
| finally: | |
| tmp.unlink(missing_ok=True) | |
| return {"required": len(items), "verified": len(items)-len(missing), "missing": missing} | |
| def index_unique(rows): | |
| out = {r["id"]: r for r in rows} | |
| require(len(out) == len(rows), "Duplicate claim ID") | |
| return out | |
| def replay(folder, condition): | |
| run = folder / "trajectories" / condition | |
| ledger = load(run / "release_bindings.json") | |
| for name, digest in ledger["replay_files"].items(): | |
| require(sha(within(run, name)) == digest, "Replay file digest mismatch: " + name) | |
| final = load(run / "evaluation/final_score.json") | |
| rubric = folder / "rubric" / ledger["rubric_file"] | |
| require(sha(rubric) == ledger["rubric_sha256"], "Rubric digest mismatch") | |
| rub = index_unique(load(rubric)["claims"]) | |
| rows = index_unique(final["claims"]) | |
| require(set(rows) == set(rub), "Claim set mismatch") | |
| caps_path = run / "evaluation/caps.json" | |
| caps = index_unique(load(caps_path)["claims"]) if caps_path.exists() else {} | |
| totals = {"original_results": 0.0, "method_rules": 0.0} | |
| for cid, row in rows.items(): | |
| rule = rub[cid] | |
| w = float(rule.get("weight", rule.get("max_points"))) | |
| f = float(row["verified_fraction"]) | |
| require(math.isfinite(f) and 0 <= f <= 1, cid + " invalid fraction") | |
| p = w * f | |
| require(math.isclose(p, float(row["points"]), abs_tol=1e-6), cid + " inconsistent points") | |
| if caps and cid in caps and "verified_fraction_cap" in caps[cid]: | |
| require(f <= float(caps[cid]["verified_fraction_cap"])+1e-6, cid + " exceeds execution cap") | |
| totals[rule["category"]] += p | |
| total = sum(totals.values()) | |
| require(math.isclose(total, float(final["final_score"]), abs_tol=1e-6), "Final total mismatch") | |
| for key, category in [("own_method_result_points", "original_results"), ("method_rule_points", "method_rules")]: | |
| require(math.isclose(totals[category], float(final[key]), abs_tol=1e-6), "Subtotal mismatch") | |
| return {"paper": folder.name, "condition": condition, **totals, "final_score": total, "claims": len(rows)} | |
| def run_solver(folder, program, image, venv, destination, timeout, mode): | |
| from isolate import invoke | |
| program=program.resolve() | |
| destination=destination.resolve() | |
| require(program.is_file() and not destination.exists(), "Provide solver and fresh output directory") | |
| check=verify_inputs(folder,mode=mode) | |
| require(not check["missing"], "Provision exact scientific inputs: "+str(check["missing"][:5])) | |
| data=folder/("workspace/input" if mode=="original" else "tests/changed") | |
| destination.mkdir(parents=True) | |
| c=load(folder/"environment/runtime.json") | |
| invoke([(data,"/input"),(program,"/solution/reproduce.py")],[(destination,"/work/output")], | |
| ["/solution/reproduce.py","--input-dir","/input","--output-dir","/work/output"], | |
| image,venv,c["science_cores"],c["memory_gib"],timeout) | |
| receipt={"paper_id":folder.name,"source_sha256":sha(program),"input_mode":mode, | |
| "artifacts":{str(f.relative_to(destination)):sha(f) for f in sorted(destination.rglob("*")) if f.is_file() and not f.is_symlink()}} | |
| require(not any(f.is_symlink() for f in destination.rglob("*")),"Candidate symlinks rejected") | |
| with destination.with_name(destination.name+".run.json").open("x") as f:json.dump(receipt,f) | |
| return {"output":str(destination),**receipt} | |
| def scientific_check(folder, outputs, inputs, mode, image, venv, trusted_private=None): | |
| from isolate import invoke | |
| require(outputs.is_dir() and inputs.is_dir(), "Provide separate output and input directories") | |
| require(not any(x.is_symlink() for x in outputs.rglob("*")), "Symlinks in candidate outputs") | |
| expected=load(folder/("inputs/manifest.json" if mode=="original" else "tests/changed_manifest.json"))["assets"] | |
| actual={str(x.relative_to(inputs)):x for x in inputs.rglob("*") if x.is_file()} | |
| require(set(actual)=={r["path"] for r in expected} and all(sha(actual[r["path"]])==r["sha256"] for r in expected),"Incorrect oracle input view") | |
| private=trusted_private or folder/"oracle/private" | |
| c=load(folder/"environment/runtime.json") | |
| with tempfile.TemporaryDirectory() as temp: | |
| output=Path(temp) | |
| invoke([(private,"/verifier"),(ROOT/"oracle_worker.py","/runner/check.py"), | |
| (inputs,"/input"),(outputs,"/submission")],[(output,"/results")], | |
| ["/runner/check.py",mode],image,venv,c["science_cores"],c["memory_gib"],7200) | |
| val=load(output/"checks.json") | |
| require(set(val)>={"original_checks","method_checks"},"Missing verifier outputs") | |
| return {"bindings":{"paper_id":folder.name,"input_mode":mode,"reference_sha256":sha(private/"reference.py"), | |
| "artifacts":{str(f.relative_to(outputs)):sha(f) for f in sorted(outputs.rglob("*")) if f.is_file()}},"evaluation":val} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| subs = parser.add_subparsers(dest="command", required=True) | |
| for op in ("unpack","inputs","replay","run","oracle"): | |
| a = subs.add_parser(op) | |
| a.add_argument("paper") | |
| if op == "replay": | |
| a.add_argument("--condition", choices=CONDITIONS) | |
| if op == "inputs": | |
| a.add_argument("--source", type=Path) | |
| a.add_argument("--fetch", action="store_true") | |
| a.add_argument("--mode",choices=("original","hidden"),default="original") | |
| if op == "run": | |
| a.add_argument("--solver", type=Path, required=True) | |
| a.add_argument("--mode",choices=("original","hidden"),default="original") | |
| a.add_argument("--output", type=Path, required=True) | |
| a.add_argument("--timeout", type=int, default=7200) | |
| if op == "oracle": | |
| a.add_argument("--outputs", type=Path, required=True) | |
| a.add_argument("--inputs", type=Path, required=True) | |
| a.add_argument("--mode", choices=("original","hidden"), required=True) | |
| if op in ("run","oracle"): | |
| engine=a.add_mutually_exclusive_group(required=True) | |
| engine.add_argument("--image",help="Provisioned container image") | |
| engine.add_argument("--venv",type=Path,help="Provisioned Linux venv for Bubblewrap") | |
| a = parser.parse_args() | |
| d = task(a.paper) | |
| if a.command == "unpack": result = unpack(d) | |
| elif a.command == "inputs": result = verify_inputs(d, a.source, a.fetch,a.mode) | |
| elif a.command == "replay": | |
| if not (d/"trajectories/g61_R1/release_bindings.json").is_file():unpack(d,"formal") | |
| result = [replay(d, x) for x in ([a.condition] if a.condition else CONDITIONS)] | |
| elif a.command == "run": result = run_solver(d, a.solver, a.image,a.venv, a.output, a.timeout,a.mode) | |
| else: result = scientific_check(d, a.outputs, a.inputs, a.mode,a.image,a.venv) | |
| print(json.dumps(result, ensure_ascii=False, indent=2, default=str, allow_nan=False)) | |
| return 2 if a.command == "inputs" and result["missing"] else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |