File size: 3,493 Bytes
e0b011e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sample efficiency: environment steps needed to reach a common target.

The paper claims ST-GFN "requires substantially fewer samples to reach target
performance across all tasks" (Sec 4.6, Table 1 'Steps' column). We define the
target as a fixed fraction of the best final score achieved by ANY method on
that environment/metric, then report the first logged point at which each method
reaches it (env steps and iterations), averaged over seeds.
"""
from __future__ import annotations

import argparse
import glob
import json
import os
from collections import defaultdict

import numpy as np

METRIC = {
    "hypergrid": ("modes_found", True),
    "bitsequence": ("mean_reward", True),
    "tictactoe": ("win_pct", True),
    "singlecell_proxy": ("mean_reward", True),
}
ORDER = ["stgfn", "tb", "fm", "subtb", "db", "eflownet", "stochastic_gfn",
         "tb_rnd", "tb_novelty", "tb_icm", "tb_cv"]
LABEL = {"stgfn": "ST-GFN (Ours)", "tb": "TB", "fm": "FM", "subtb": "SubTB", "db": "DB",
         "eflownet": "EFlowNet", "stochastic_gfn": "Stochastic-GFN", "tb_rnd": "TB+RND",
         "tb_novelty": "TB+Novelty", "tb_icm": "TB+ICM", "tb_cv": "TB+ControlVar"}


def load(out_dir):
    data = defaultdict(lambda: defaultdict(list))
    for p in glob.glob(os.path.join(out_dir, "*.json")):
        with open(p) as f:
            r = json.load(f)
        data[r["env"]][r["method"]].append(r)
    return data


def steps_to(run, metric, thresh):
    for c in run["curve"]:
        v = c.get(metric)
        if v is not None and v >= thresh:
            return c.get("env_steps"), c.get("iter")
    return None, None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="../outputs/main")
    ap.add_argument("--frac", type=float, default=0.9)
    ap.add_argument("--save", default="../outputs/sample_efficiency.json")
    args = ap.parse_args()

    data = load(args.out)
    result = {}
    for env, (metric, _) in METRIC.items():
        if env not in data:
            continue
        best = max(
            np.mean([r["final"].get(metric, 0) or 0 for r in runs])
            for runs in data[env].values()
        )
        thresh = args.frac * best
        print(f"\n{'='*76}\n{env.upper()}  metric={metric}  "
              f"target={args.frac:.0%} of best final ({best:.3f}) = {thresh:.3f}\n{'='*76}")
        print(f"{'Method':22s} {'env steps to target':>22s} {'iters':>10s} {'reached':>9s}")
        result[env] = {"metric": metric, "target": thresh, "methods": {}}
        for m in ORDER:
            if m not in data[env]:
                continue
            steps, iters, hit = [], [], 0
            for r in data[env][m]:
                s, i = steps_to(r, metric, thresh)
                if s is not None:
                    steps.append(s); iters.append(i); hit += 1
            n = len(data[env][m])
            if steps:
                txt = f"{np.mean(steps):22,.0f} {np.mean(iters):10,.0f} {hit}/{n:>7d}"
            else:
                txt = f"{'never':>22s} {'-':>10s} {0}/{n:>7d}"
            print(f"{LABEL.get(m,m):22s} {txt}")
            result[env]["methods"][m] = {
                "mean_env_steps": float(np.mean(steps)) if steps else None,
                "mean_iters": float(np.mean(iters)) if iters else None,
                "n_reached": hit, "n_seeds": n,
            }
    with open(args.save, "w") as f:
        json.dump(result, f, indent=2)
    print(f"\nwrote {args.save}")


if __name__ == "__main__":
    main()