File size: 6,517 Bytes
4ceb5b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Concurrent driver for the neural-baseline jobs (CDSplit + R2CCP).

Runs ORCA_WORKERS concurrent subprocesses of run_full.py, each doing ONE
run (--seed0 = run id), then merges the parts (rewriting run_id), prints
the summary and uploads the merged CSV. Concurrency only changes wall
time: every run is an independent seeded process, so results are identical
to sequential execution. run_full.py is fetched from the pinned Hub commit
if absent (hf_jobs materializes only the driver script)."""

import os
import subprocess
import sys
import urllib.request

import pandas as pd
from concurrent.futures import ThreadPoolExecutor

RUN_FULL_URL = ("https://huggingface.co/datasets/Devya27/orca-table3-repro/"
                "resolve/b381fcaf81f2b2e46a4937cfb49de995a26dc935/code/run_full.py")
BASE_MODULE_URL = ("https://huggingface.co/datasets/Devya27/orca-table3-repro/"
                   "resolve/f1afb40c7ba22b5b93b3b84219c9bbfdf88e7360/"
                   "code/run_realdata.py")


def main():
    if os.environ.get("ORCA_ARGS"):
        sys.argv += os.environ["ORCA_ARGS"].split()
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--dataset", required=True)
    ap.add_argument("--runs", type=int, default=30)
    ap.add_argument("--preproc", default="raw")
    ap.add_argument("--out", required=True)
    ap.add_argument("--seed0", type=int, default=0)
    args = ap.parse_args()

    if not os.path.exists("run_full.py"):
        print(f"[driver] fetching run_full.py from {RUN_FULL_URL}", flush=True)
        with open("run_full.py", "wb") as f:
            f.write(urllib.request.urlopen(RUN_FULL_URL, timeout=120).read())
    # pre-fetch the base-pipeline module ONCE: run_full.py's own bootstrap
    # writes it into the shared CWD, and concurrent workers racing on that
    # write truncate the module (observed: ImportError: cannot import name
    # 'ALPHA') -- serialize it here, before the pool
    if not os.path.exists("run_realdata_v30.py"):
        with open("run_realdata_v30.py", "wb") as f:
            f.write(urllib.request.urlopen(BASE_MODULE_URL, timeout=120).read())
        print("[driver] fetched base pipeline module", flush=True)

    workers = int(os.environ.get("ORCA_WORKERS", "8"))
    env = os.environ.copy()
    env["ORCA_SKIP"] = os.environ.get(
        "ORCA_SKIP",
        "orca,pcp,cqr,chr,dcp-cqr,distsplit,"
        "crd-ellipse,crd-convexhull,crd-hyperrectangle")
    env["ORCA_UPLOAD_REPO"] = ""   # parts are merged and uploaded here
    # prefetch: download/extract the dataset ONCE before the pool, otherwise
    # concurrent workers race on ensure_blog/ensure_fb and a worker can read
    # an empty CSV mid-extraction (observed: blogData_train.csv empty ->
    # loadtxt IndexError on run 0). --runs 0 loads the data and exits.
    e0 = env.copy()
    e0["ORCA_ARGS"] = (f"--dataset {args.dataset} --runs 0 "
                       f"--preproc {args.preproc} --out /tmp/prefetch.csv")
    r0 = subprocess.run([sys.executable, "run_full.py"], env=e0,
                        capture_output=True, text=True)
    print(f"[driver] prefetch rc={r0.returncode}", flush=True)

    def run_one(rid):
        e = env.copy()
        e["ORCA_ARGS"] = (f"--dataset {args.dataset} --runs 1 "
                          f"--preproc {args.preproc} "
                          f"--out /tmp/part_{rid}.csv "
                          f"--seed0 {args.seed0 + rid}")
        e["OMP_NUM_THREADS"] = "1"
        e["MKL_NUM_THREADS"] = "1"
        r = subprocess.run([sys.executable, "run_full.py"], env=e,
                           capture_output=True, text=True)
        with open(f"/tmp/part_{rid}.log", "w") as f:
            f.write(r.stdout[-4000:] + "\n===STDERR===\n" + r.stderr[-8000:])
        if r.returncode != 0:
            print(f"[driver] run {rid} FAILED rc={r.returncode}; "
                  f"stderr tail:\n{r.stderr[-2500:]}", flush=True)
        return rid, r.returncode

    rids = list(range(args.runs))
    with ThreadPoolExecutor(max_workers=workers) as ex:
        results = list(ex.map(run_one, rids))
    fails = [rid for rid, rc in results if rc != 0]
    print(f"[driver] runs ok: {len(results) - len(fails)}/{len(results)}; "
          f"failed: {fails}", flush=True)

    parts = []
    for rid in rids:
        p = f"/tmp/part_{rid}.csv"
        if not os.path.exists(p):
            continue
        df = pd.read_csv(p)
        df["seed0_abs"] = args.seed0 + rid
        df["run_id"] = args.seed0 + rid
        df["status"] = "failed" if rid in fails else "ok"
        parts.append(df)
    if not parts:
        raise RuntimeError("no part CSVs produced")
    new = pd.concat(parts, ignore_index=True)
    new["run_id"] = new["seed0_abs"]
    # merge-aware: replace same-run_id rows in the existing remote CSV, so a
    # top-up job only adds the runs it actually (re)ran
    try:
        import urllib.request as _u
        remote_url = (f"https://huggingface.co/datasets/Devya27/orca-table3-repro/"
                      f"resolve/main/results/full_neural_{args.preproc}_{args.dataset}.csv")
        existing = pd.read_csv(_u.urlopen(remote_url, timeout=120))
        kept = existing[~existing.run_id.isin(new.run_id.unique())]
        out = pd.concat([kept, new], ignore_index=True)
        out = out.sort_values(["method_config", "run_id"]).reset_index(drop=True)
        print(f"[driver] merged with existing remote CSV: kept {len(kept)} rows, "
              f"new {len(new)} rows", flush=True)
    except Exception as exc:  # noqa: BLE001
        print(f"[driver] no existing remote CSV merged ({exc}); using new parts", flush=True)
        out = new
    out.to_csv(args.out, index=False)
    print("[driver] summary (mean +- SE per method_config):", flush=True)
    for mc, gg in out.groupby("method_config"):
        print(f"{mc:30s} {gg['coverage'].mean():.4f} +- "
              f"{gg['coverage'].sem():.4f} {gg['eff'].mean():.4f} +- "
              f"{gg['eff'].sem():.4f}", flush=True)
    if os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"):
        from huggingface_hub import HfApi
        HfApi().upload_file(
            path_or_fileobj=args.out,
            path_in_repo=f"results/full_neural_{args.preproc}_{args.dataset}.csv",
            repo_id=os.environ.get("ORCA_UPLOAD_REPO",
                                   "Devya27/orca-table3-repro"),
            repo_type="dataset")
        print("[driver] upload ok", flush=True)


if __name__ == "__main__":
    main()