File size: 4,080 Bytes
695c811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproduce TCOD's ScienceWorld split byte-for-byte, then emit a portable variant.

The only change in the portable variant is jar_path: "" instead of a machine-local
absolute path. ScienceWorldEnv.__init__ does `serverPath = serverPath or JAR_PATH`,
so an empty string falls back to the jar shipped inside the installed scienceworld
package. TCOD's _create_scienceworld_env already does
`task_config.get("jar_path", "")`, so nothing downstream needs patching.

Everything else -- task-type membership, variation ranges, shuffle order -- is
produced by importing TCOD's own get_sciworld_data.py, not by re-implementing it.
"""
import json
import os
import random
import sys

TCOD_SCRIPT = (
    "/work/hdd/bhnn/haojinw2/continual_learning/TCOD/TCOD_examples/scienceworld/"
    "get_sciworld_data.py"
)
OUT = os.path.dirname(os.path.abspath(__file__))

# Pull task_variations + create_dataset_files out of TCOD's script without running
# its __main__ block (which hardcodes a placeholder jar path and would raise).
src = open(TCOD_SCRIPT).read().split('if __name__ == "__main__":')[0]
mod = {}
exec(compile(src, TCOD_SCRIPT, "exec"), mod)
task_variations = mod["task_variations"]
create_dataset_files = mod["create_dataset_files"]

# Verbatim from get_sciworld_data.py __main__.
TRAIN_TASKS = [
    "boil",
    "melt",
    "change-the-state-of-matter-of",
    "use-thermometer",
    "measure-melting-point-known-substance",
    "power-component",
    "test-conductivity",
    "find-living-thing",
    "find-plant",
    "grow-plant",
    "chemistry-mix",
    "chemistry-mix-paint-secondary-color",
    "lifespan-shortest-lived",
    "identify-life-stages-2",
    "inclined-plane-determine-angle",
    "inclined-plane-friction-named-surfaces",
    "mendelian-genetics-known-plant",
]
TEST_TASKS = list(task_variations.keys() - set(TRAIN_TASKS))
PERCENTAGE = 0.5

LOCAL_JAR = (
    "/u/haojinw2/envs/opd-mt/lib/python3.11/site-packages/scienceworld/scienceworld.jar"
)


def build(jar_path, out_dir):
    # create_dataset_files seeds off the module-level random.seed(42) in TCOD's
    # script, so reset it before each build to keep shuffle order identical.
    random.seed(42)
    create_dataset_files(out_dir, TRAIN_TASKS, TEST_TASKS, jar_path, percentage=PERCENTAGE)
    rows = {}
    for split in ("train", "test"):
        with open(os.path.join(out_dir, f"{split}.jsonl")) as f:
            rows[split] = [json.loads(line) for line in f]
    return rows


def keyed(rows):
    """Identity of a row is (task_name, var_num) -- jar_path is environment, not data."""
    out = []
    for r in rows:
        d = json.loads(r["task_desc"])
        out.append((d["task_name"], d["var_num"]))
    return out


if __name__ == "__main__":
    if not os.path.exists(LOCAL_JAR):
        sys.exit(f"local jar missing: {LOCAL_JAR}")

    ref = build(LOCAL_JAR, os.path.join(OUT, "_reference"))
    port = build("", os.path.join(OUT, "portable"))

    print(f"{len(task_variations)} task types | train {len(TRAIN_TASKS)} | test {len(TEST_TASKS)}")
    for split in ("train", "test"):
        print(f"  {split:5s} {len(ref[split]):5d} rows")

    # The portable build must differ from the reference in jar_path and nothing else.
    for split in ("train", "test"):
        assert keyed(ref[split]) == keyed(port[split]), f"{split}: row order/content drift"
        assert all(json.loads(r["task_desc"])["jar_path"] == "" for r in port[split])
        assert all(r["targe"] == "" for r in port[split])
    print("identical to TCOD reference on (task_name, var_num, order); jar_path blanked")

    # Task types must not cross splits, and var_num must stay inside the declared count.
    tr = {t for t, _ in keyed(ref["train"])}
    te = {t for t, _ in keyed(ref["test"])}
    assert not (tr & te), f"task-type leak: {tr & te}"
    for split in ("train", "test"):
        for t, v in keyed(ref[split]):
            assert 0 <= v < int(task_variations[t] * PERCENTAGE), f"{t} var {v} out of range"
    print(f"no task-type overlap ({len(tr)} train types, {len(te)} test types); var_num in range")