yxma commited on
Commit
4839201
·
verified ·
1 Parent(s): 668612d

toolbox: publish splits.py

Browse files
Files changed (1) hide show
  1. toolbox/splits.py +153 -0
toolbox/splits.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Held-out INTERVALS carved from inside episodes, with a leak-proof guard.
2
+
3
+ WHY NOT HOLD OUT WHOLE EPISODES
4
+
5
+ There are 32 motherboard episodes and 194,445 frames. Holding out episodes
6
+ spends the scarce resource — episodes, and with them board layouts and lighting
7
+ — to buy independence that a short-horizon world model does not need: what it
8
+ must generalise over is dynamics within a scene, not scenes.
9
+
10
+ So the split is at INTERVAL level. Each episode contributes a few held-out
11
+ windows from its middle; the rest of that episode trains.
12
+
13
+ THE PART THAT LEAKS IF YOU GET IT WRONG
14
+
15
+ A training window starting shortly BEFORE a held-out interval still contains
16
+ its frames. Excluding only the interval is not enough. A window of span S
17
+ starting at s covers [s, s+S-1], so starts in [a-(S-1), b] must be rejected,
18
+ not just [a, b].
19
+
20
+ `guard_frames` is therefore `max_train_window - 1`, and it is RECORDED. A
21
+ loader using a longer window must FAIL rather than silently leak — see
22
+ `assert_window_fits`. That failure mode leaves no trace in any metric until
23
+ the numbers are suspiciously good.
24
+
25
+ Cost, measured over this release with a 64-frame training window:
26
+ test 12.2% guard 9.5% train 78.4% over 146 held-out intervals
27
+ The guard is what independence costs; naming it makes the price visible.
28
+
29
+ EPISODES TOO SHORT TO CARVE go entirely to test rather than being dropped,
30
+ which also yields a few wholly-unseen episodes for free.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+
39
+ FORMAT = "react-splits/1.0"
40
+ TEST_INTERVAL_FRAMES = 160 # 128-frame probe horizon + 4 context + slack
41
+ MAX_TRAIN_WINDOW = 64 # frames; guard = this - 1
42
+ TARGET_TEST_FRACTION = 0.12
43
+
44
+
45
+ def _bad_mask(entry: dict, T: int) -> np.ndarray:
46
+ m = np.zeros(T, bool)
47
+ for k in ("intensity_spikes", "pose_teleports_L", "pose_teleports_R",
48
+ "ot_loss_L", "ot_loss_R"):
49
+ for a, b in entry.get(k, []):
50
+ m[max(0, a):min(T, b + 1)] = True
51
+ return m
52
+
53
+
54
+ def build_splits(episodes, bad=None, seed: int = 0,
55
+ test_len: int = TEST_INTERVAL_FRAMES,
56
+ max_train_window: int = MAX_TRAIN_WINDOW,
57
+ target: float = TARGET_TEST_FRACTION) -> dict:
58
+ """Carve held-out intervals. Deterministic given `episodes` and `seed`.
59
+
60
+ `bad` is the `bad_frames.json` episodes dict, so an interval is never
61
+ placed on a stretch of dropouts — a test window full of tracking loss
62
+ measures the rig, not the model.
63
+ """
64
+ guard = int(max_train_window) - 1
65
+ rng = np.random.default_rng(seed)
66
+ need = 2 * test_len + 2 * guard
67
+ out, n_test, n_guard, n_tot = {}, 0, 0, 0
68
+
69
+ for e in sorted(episodes, key=lambda x: x["episode"]):
70
+ key, N = e["episode"], int(e["n_frames"])
71
+ n_tot += N
72
+ if N < need:
73
+ out[key] = {"n_frames": N, "whole": "test",
74
+ "test": [[0, N - 1]], "guard": []}
75
+ n_test += N
76
+ continue
77
+ k = max(1, int(round(N * target / test_len)))
78
+ k = min(k, max(1, (N - test_len) // (test_len + 2 * guard)))
79
+ bm = _bad_mask(bad.get(key, {}) if bad else {}, N)
80
+ lo, hi = guard, N - test_len - guard
81
+ iv = []
82
+ for c in np.linspace(lo, hi, k + 2)[1:-1]:
83
+ a0 = int(np.clip(round(c + rng.integers(-test_len // 2, test_len // 2 + 1)),
84
+ lo, hi))
85
+ for shift in (0, *[s for d in range(1, test_len + 1) for s in (d, -d)]):
86
+ s = int(np.clip(a0 + shift, lo, hi))
87
+ b = s + test_len - 1
88
+ if bm[s:b + 1].any():
89
+ continue
90
+ if any(not (b + guard < p or s - guard > q) for p, q in iv):
91
+ continue
92
+ iv.append([s, b])
93
+ break
94
+ iv.sort()
95
+ out[key] = {"n_frames": N, "whole": None, "test": iv,
96
+ "guard": [[max(0, s - guard), min(N - 1, b + guard)]
97
+ for s, b in iv]}
98
+ n_test += sum(b - a + 1 for a, b in iv)
99
+ n_guard += 2 * guard * len(iv)
100
+
101
+ return {
102
+ "format": FORMAT, "seed": int(seed), "policy": "interval",
103
+ "test_interval_frames": int(test_len),
104
+ "max_train_window": int(max_train_window), "guard_frames": guard,
105
+ "guard_note": ("a training window of span S starting at s covers "
106
+ "[s, s+S-1], so starts in [a-(S-1), b] must be rejected, "
107
+ "not just [a, b]. guard_frames = max_train_window - 1; a "
108
+ "loader using a longer window must rebuild the split."),
109
+ "episodes": out,
110
+ "stats": {"n_episodes": len(out), "n_frames": n_tot,
111
+ "n_test_frames": n_test, "n_guard_frames": n_guard,
112
+ "test_fraction": round(n_test / n_tot, 4),
113
+ "guard_fraction": round(n_guard / n_tot, 4),
114
+ "n_test_intervals": sum(len(v["test"]) for v in out.values()),
115
+ "n_whole_test_episodes": sum(1 for v in out.values() if v["whole"])},
116
+ }
117
+
118
+
119
+ def load_splits(path) -> dict:
120
+ d = json.loads(Path(path).read_text())
121
+ if d.get("format") != FORMAT:
122
+ raise ValueError(f"expected {FORMAT}, got {d.get('format')!r}")
123
+ return d
124
+
125
+
126
+ def assert_window_fits(splits: dict, window_span: int) -> None:
127
+ """Refuse a training window the guard cannot cover."""
128
+ if window_span - 1 > splits["guard_frames"]:
129
+ raise ValueError(
130
+ f"training window spans {window_span} frames but the split has "
131
+ f"guard_frames={splits['guard_frames']} "
132
+ f"(max_train_window={splits['max_train_window']}). A window this "
133
+ f"long would overlap held-out intervals. Rebuild the split with "
134
+ f"max_train_window >= {window_span}.")
135
+
136
+
137
+ def forbidden_starts(splits: dict, ep_key: str, window_span: int):
138
+ """[(lo, hi)] inclusive start indices a TRAIN window may not begin at."""
139
+ e = splits["episodes"].get(ep_key)
140
+ if e is None:
141
+ return []
142
+ if e["whole"] == "test":
143
+ return [(0, e["n_frames"] - 1)]
144
+ return [(max(0, a - (window_span - 1)), b) for a, b in e["test"]]
145
+
146
+
147
+ def test_starts(splits: dict, ep_key: str, window_span: int):
148
+ """[(lo, hi)] start indices whose whole window lies inside a test interval."""
149
+ e = splits["episodes"].get(ep_key)
150
+ if e is None:
151
+ return []
152
+ return [(a, b - window_span + 1) for a, b in e["test"]
153
+ if b - a + 1 >= window_span]