"""make_bundle.py - split the metric_depth hand-over package into what the agent, the self-check side-car and the final verifier of the task see (bench/), and keep the secrets (noise salts, unit id maps) in secrets/. env/ref39/bin/python build/make_bundle.py (numpy 1.22.4: the noise stream depends on it) bench/agent/ -> agent /data (read-only) controlled/ truedepth/ (train + val only) optics/ splits/ (train, val) baseline/dump_val/ shift_proxy// val scenes re-composited at shifted depths from controlled renders (approximate, noise-free like every other agent root; for a development estimate of gamma) selfcheck/ test + test depth-shift units, noise ALREADY ADDED with a secret salt, ids anonymised, no gt/ bench/weights/ -> /weights: ckpt/ (DAv2-Small + the 4 heads x 3 seeds) bench/evaluator/ -> self-check side-car only: gt/ + units.json of the self-check units bench/verifier/inputs/ -> final verifier, readable by the runner: test + shift + VHSD with a second secret salt and fresh ids (one merged root, run.sh is called once) bench/verifier/hidden/ -> final verifier, root only: gt/ + units.json Noise of the hidden units: x = clip(meas + (sigma * peak) * eps, 0) in float32, eps from a salt that never leaves secrets/; the method then only normalises (dump.py --sigma 0), which is bit-identical to the reference path. Bm0 of the depth shift is the unshifted test render, so the test units of illuminants A / D65 / D50 / ID65 double as m = 0 of both arms. """ import csv import hashlib import json import os import secrets as pysecrets import shutil import sys import numpy as np SRC = "/data/a792144/metric_depth/extract/metric_depth" OUT = "/data/a792144/metric_depth/bench" SECRETS = "/data/a792144/metric_depth/secrets" SIGMA = 0.005 STAMP = 1767225600 # 2026-01-01 00:00 UTC, mtime of every hidden input SHIFT_ROOTS = ("Bm1", "Bm2", "Bm3", "Bm4", "Am1", "Am2", "Am3") # The 8 test scenes, split 4 + 4: the self-check scores the first 4 (per scene, as often as the agent likes); the # final grade uses only the other 4 (never in the agent container: the brief's held-out set) plus VHSD. Balanced on # the hand-over's baseline AbsRel (.0519 / .0666); scene85, the one shifted farther, is in the self-check so that the # agent can see that case. SELFCHECK_SCENES = ["scene41", "scene48", "scene52", "scene85"] HELDOUT_SCENES = ["scene39", "scene50", "scene53", "scene66"] ARMS = {"B": ("Bm0", "Bm1", "Bm2", "Bm3", "Bm4"), "A": ("Bm0", "Am1", "Am2", "Am3")} D = os.path.join(SRC, "data") def jload(p): with open(p, encoding="utf-8") as f: return json.load(f) def jsave(p, obj): os.makedirs(os.path.dirname(p), exist_ok=True) with open(p, "w", encoding="utf-8") as f: json.dump(obj, f, indent=1) def link(src, dst): """Hard link (same Lustre file system, no extra space); files stay read-only for everyone.""" os.makedirs(os.path.dirname(dst), exist_ok=True) if os.path.lexists(dst): os.remove(dst) os.link(src, dst) def link_tree(src, dst): for dp, _, fs in os.walk(src): for f in fs: link(os.path.join(dp, f), os.path.join(dst, os.path.relpath(os.path.join(dp, f), src))) def split_list(name): with open(os.path.join(D, "splits", f"{name}_list_custom_v2.txt"), encoding="utf-8") as f: return sorted({ln.split("_")[0] for ln in f if ln.strip()}) def read_stats(root): with open(os.path.join(root, "clear_stats.csv"), encoding="utf-8") as f: rows = list(csv.reader(f)) return rows[0], {(r[0], r[1]): r for r in rows[1:] if r} def write_stats(path, head, rows): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8", newline="") as f: w = csv.writer(f) w.writerow(head) w.writerows(rows) def peak(stats, scene, illum): head, rows = stats return float(rows[(scene, illum)][head.index("p995_all")]) # ------------------------------------------------------------------ agent data def agent_truedepth(train, val): src, dst = os.path.join(D, "truedepth"), os.path.join(OUT, "agent", "truedepth") man = jload(os.path.join(src, "manifest.json")) keep = set(train) | set(val) head, rows = read_stats(src) write_stats(os.path.join(dst, "clear_stats.csv"), head, [r for (s, _), r in sorted(rows.items()) if s in keep]) for s in sorted(keep): for il in man["illums"]: link(os.path.join(src, f"{s}_{il}.npy"), os.path.join(dst, f"{s}_{il}.npy")) for k in man["layout"]["gt_kinds"]: link(os.path.join(src, "gt", f"{s}_{k}.npy"), os.path.join(dst, "gt", f"{s}_{k}.npy")) man["scenes"] = [s for s in man["scenes"] if s in keep] man["files"] = [f for f in man["files"] if f.split("_")[0] in keep] man["note"] = ("Train (33) and val (6) scenes. The 8 test scenes are not here: their noisy inputs (no ground truth) " "are in /data/selfcheck, scored by the self-check tool; the final grade uses them again.") jsave(os.path.join(dst, "manifest.json"), man) def agent_splits(): for n in ("train", "val"): link(os.path.join(D, "splits", f"{n}_list_custom_v2.txt"), os.path.join(OUT, "agent", "splits", f"{n}_list_custom_v2.txt")) def proxy_shift(val): """Val scenes at shifted depths, composited per pixel from the constant-depth renders of data/controlled. Same warp as data/shift of the hand-over (arm B: u -> u + sign m delta; arm A: z -> alpha z with alpha = u_bar / (u_bar + sign m delta); u_bar = mean inverse depth of the foreground; sign = +1 (nearer) unless the scene would leave the near end, u clamped at the far end) applied to the true-depth map; each pixel takes the controlled render of its nearest K9 bin. No occlusion compositing, so pixels near depth edges are approximate. """ ctl = os.path.join(D, "controlled") cman = jload(os.path.join(ctl, "manifest.json")) z = np.asarray(cman["depth_list"], dtype=np.float64) ug = 1.0 / z # descending delta = float(ug[0] - ug[1]) stats = read_stats(ctl) tdg = os.path.join(D, "truedepth", "gt") roots = sorted({d for ds in ARMS.values() for d in ds}) warp = {d: {"arm": "B" if d.startswith("B") else "A", "m": int(d[2]), "delta": delta, "u_bar": {}, "sign": {}, "alpha": {}, "clamp_u_min": float(ug[-1])} for d in roots} for s in val: dep = np.load(os.path.join(tdg, f"{s}_depth.npy")).astype(np.float64) fg = np.load(os.path.join(tdg, f"{s}_mask.npy")) > 0.5 valid = dep > 1e-6 u = np.where(valid, 1.0 / np.where(valid, dep, 1.0), ug[-1]) bord = np.zeros(fg.shape, dtype=bool) bord[128:-128, 128:-128] = True ubar = float(u[bord & fg & valid].mean()) # as data/shift: the evaluation region of the foreground sign = 1 if ubar + 4 * delta <= ug[0] else -1 imgs = {il: [np.load(os.path.join(ctl, cman["layout"]["meas"].format(scene=s, illum=il, k=k)), mmap_mode="r") for k in range(len(z))] for il in cman["illums"]} for d in roots: m = int(d[2]) if d.startswith("B"): u2 = u + sign * m * delta else: alpha = ubar / (ubar + sign * m * delta) warp[d]["alpha"][s] = alpha u2 = u / alpha if sign < 0: u2 = np.maximum(u2, ug[-1]) # shifted farther: clamp at the far end of the grid dep2 = np.where(valid, 1.0 / u2, 0.0).astype(np.float32) # true depth, not clipped (K6) # render bin = nearest K9 node in z, as gt/depth_bin of the hand-over (beyond 1.383 m: the last bin) b2 = np.abs(dep2[..., None].astype(np.float64) - z[None, None, :]).argmin(-1).astype(np.uint8) warp[d]["u_bar"][s], warp[d]["sign"][s] = ubar, sign out = os.path.join(OUT, "agent", "shift_proxy", d) os.makedirs(os.path.join(out, "gt"), exist_ok=True) np.save(os.path.join(out, "gt", f"{s}_depth.npy"), dep2) np.save(os.path.join(out, "gt", f"{s}_depth_bin.npy"), b2) link(os.path.join(tdg, f"{s}_mask.npy"), os.path.join(out, "gt", f"{s}_mask.npy")) for il, stack in imgs.items(): comp = np.empty(stack[0].shape, dtype=stack[0].dtype) for k in range(len(z)): sel = b2 == k if sel.any(): comp[:, sel] = np.asarray(stack[k][:, sel]) np.save(os.path.join(out, f"{s}_{il}.npy"), comp) print(f"[proxy] {s}: u_bar {ubar:.4f} sign {sign:+d}", flush=True) head, rows = stats for d in roots: out = os.path.join(OUT, "agent", "shift_proxy", d) write_stats(os.path.join(out, "clear_stats.csv"), head, [rows[(s, il)] for s in val for il in cman["illums"]]) jsave(os.path.join(out, "manifest.json"), { "kind": "shift_proxy", "depth_grid_name": "K9", "layout": {"meas": "{scene}_{illum}.npy", "gt": "gt/{scene}_{kind}.npy", "gt_kinds": ["depth", "mask", "depth_bin"]}, "scenes": list(val), "illums": list(cman["illums"]), "store_dtype": "float16", "warp": warp[d], "note": ("APPROXIMATE depth-shift roots of the 6 val scenes, built by build/make_bundle.py: every pixel takes the " "data/controlled render of the K9 bin nearest to its shifted depth (no occlusion compositing, so pixels " "near depth edges differ from a true render). Noise-free like data/truedepth; add noise as usual. " "Use them to estimate gamma during development; the self-check tool measures gamma on the real " "depth-shift renders of the test scenes."), "conventions": cman["conventions"]}) # ------------------------------------------------------------------ hidden units def noisy(meas, pk, salt, uid, illum): seed = int.from_bytes(hashlib.sha256(f"{salt}|{uid}|{illum}".encode()).digest()[:8], "little") eps = np.random.default_rng(seed).standard_normal(meas.shape, dtype=np.float32) x = np.asarray(meas, dtype=np.float32) x = x + (SIGMA * float(pk)) * eps # as scene_eval_io.add_noise_and_normalize return np.clip(x, 0.0, None).astype(np.float32, copy=False) def hidden_set(name, sources, salt, inputs_dir, gt_dir): """sources: list of (set, root_name, root_dir, scene, illums). Writes one merged root + its ground truth.""" ids, units, seen = {}, [], set() rng = pysecrets.SystemRandom() order = list(sources) rng.shuffle(order) used = set() for (st, rname, rdir, s, illums) in order: key = ("test", "Bm0", s) if rname == "Bm0" else (st, rname, s) if key not in ids: while True: uid = "u" + pysecrets.token_hex(4) if uid not in used: break used.add(uid) ids[key] = uid # every unit once, written in a random order (file mtimes and inode numbers must not follow the source order) work, scenes, all_illums, seen = [], [], [], set() for (st, rname, rdir, s, illums) in sources: uid = ids[("test", "Bm0", s) if rname == "Bm0" else (st, rname, s)] man = jload(os.path.join(rdir, "manifest.json")) if uid not in scenes: scenes.append(uid) for k in ("depth", "mask"): link(os.path.join(rdir, man["layout"]["gt"]).format(scene=s, kind=k), os.path.join(gt_dir, f"{uid}_{k}.npy")) for il in illums: if (uid, il) not in seen: seen.add((uid, il)) work.append((uid, il, st, rname, rdir, s, man["layout"]["meas"])) if il not in all_illums: all_illums.append(il) rng.shuffle(work) stats_cache, stats_rows = {}, [] for n, (uid, il, st, rname, rdir, s, meas_t) in enumerate(work): stats = stats_cache.setdefault(rdir, read_stats(rdir)) pk = peak(stats, s, il) meas = np.load(os.path.join(rdir, meas_t.format(scene=s, illum=il))) np.save(os.path.join(inputs_dir, f"{uid}_{il}.npy"), noisy(meas, pk, salt, uid, il)) stats_rows.append([uid, il, "", f"{pk!r}"]) units.append({"id": uid, "illum": il, "set": st, "root": rname, "scene": s}) if n % 50 == 0: print(f"[{name}] {n}/{len(work)} units", flush=True) perm = list(range(len(scenes))) rng.shuffle(perm) scenes = [scenes[i] for i in perm] stats_rows.sort() write_stats(os.path.join(inputs_dir, "clear_stats.csv"), ["scene", "illum", "amax_all", "p995_all"], stats_rows) jsave(os.path.join(inputs_dir, "manifest.json"), { "layout": {"meas": "{scene}_{illum}.npy"}, "scenes": scenes, "illums": all_illums, "store_dtype": "float32", "units": sorted([[u["id"], u["illum"]] for u in units]), "note": ("Hidden units, one merged root. Sensor noise is ALREADY ADDED (sigma 0.005 x peak, then clipped at 0) " "and stored as float32 raw DN: only normalise by the peak of clear_stats.csv (dump.py --sigma 0). " "Not every (scene, illum) pair exists: the units are listed in 'units'.")}) for f in os.listdir(inputs_dir): # one timestamp for every file of the root os.utime(os.path.join(inputs_dir, f), (STAMP, STAMP)) jsave(os.path.join(gt_dir, "..", "units.json"), {"units": units, "arms": ARMS}) return units def fix_perms(): """Hard links keep the archives' modes (some 0640): the agent (uid 1000) and the runner (uid 1001) must read everything they are given. The ground truth stays as it is (read by root only).""" for root in (os.path.join(OUT, "agent"), os.path.join(OUT, "weights"), os.path.join(OUT, "verifier", "inputs")): for dp, dns, fns in os.walk(root): os.chmod(dp, 0o755) for f in fns: q = os.path.join(dp, f) os.chmod(q, os.stat(q).st_mode | 0o444) print("permissions: a+rX on agent/, weights/, verifier/inputs/") def main(): """No argument: build everything (bench/ must not exist). --only proxy,hidden,perms: rebuild those parts.""" np_ver = np.__version__ if np_ver != "1.22.4": sys.exit(f"numpy {np_ver}: run with env/ref39 (numpy 1.22.4)") only = set(sys.argv[2].split(",")) if len(sys.argv) > 2 and sys.argv[1] == "--only" else None if only is None and os.path.exists(OUT): sys.exit(f"{OUT} exists; remove it first, or use --only proxy,hidden,perms") os.makedirs(SECRETS, mode=0o700, exist_ok=True) train, val, test = split_list("train"), split_list("val"), split_list("test") print(f"train {len(train)} val {len(val)} test {len(test)}") if only is None: link_tree(os.path.join(D, "controlled"), os.path.join(OUT, "agent", "controlled")) link_tree(os.path.join(D, "optics"), os.path.join(OUT, "agent", "optics")) link_tree(os.path.join(SRC, "baseline", "dump_val"), os.path.join(OUT, "agent", "baseline", "dump_val")) agent_truedepth(train, val) agent_splits() link_tree(os.path.join(SRC, "ckpt"), os.path.join(OUT, "weights", "ckpt")) if only is None or "weights" in only: # the optics also under /weights: run.sh can read them at grading time, where /data is absent link_tree(os.path.join(D, "optics"), os.path.join(OUT, "weights", "optics")) if only is None or "proxy" in only: shutil.rmtree(os.path.join(OUT, "agent", "shift_proxy"), ignore_errors=True) proxy_shift(val) if only is None or "hidden" in only: # self-check (test + shift) and final (test + shift + VHSD): separate salts and ids for d in (os.path.join(OUT, "agent", "selfcheck"), os.path.join(OUT, "evaluator"), os.path.join(OUT, "verifier")): shutil.rmtree(d, ignore_errors=True) td, vh = os.path.join(D, "truedepth"), os.path.join(D, "vhsd") tillums = jload(os.path.join(td, "manifest.json"))["illums"] def test_sources(scenes): out = [("test", "Bm0", td, s, tillums) for s in scenes] for d in SHIFT_ROOTS: rd = os.path.join(D, "shift", d) out += [("shift", d, rd, s, jload(os.path.join(rd, "manifest.json"))["illums"]) for s in scenes] return out assert sorted(SELFCHECK_SCENES + HELDOUT_SCENES) == test, "the 4 + 4 split must cover the test scenes" vsrc = [("vhsd", "vhsd", vh, s, ["D65"]) for s in jload(os.path.join(vh, "manifest.json"))["scenes"]] salts = {"selfcheck": pysecrets.token_hex(32), "final": pysecrets.token_hex(32)} with open(os.path.join(SECRETS, "salts.json"), "w") as f: json.dump(salts, f) os.chmod(os.path.join(SECRETS, "salts.json"), 0o600) sc_in = os.path.join(OUT, "agent", "selfcheck") os.makedirs(sc_in) hidden_set("selfcheck", test_sources(SELFCHECK_SCENES), salts["selfcheck"], sc_in, os.path.join(OUT, "evaluator", "gt")) fi_in = os.path.join(OUT, "verifier", "inputs") os.makedirs(fi_in) hidden_set("final", test_sources(HELDOUT_SCENES) + vsrc, salts["final"], fi_in, os.path.join(OUT, "verifier", "hidden", "gt")) fix_perms() print("bundle written to", OUT) if __name__ == "__main__": main()