File size: 11,892 Bytes
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
 
 
d65fc2e
 
 
 
 
 
f9ace88
 
 
 
 
 
 
 
 
 
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
 
 
 
 
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
f9ace88
 
 
 
 
 
 
 
 
 
 
 
 
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
d65fc2e
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""Set 5, phase 3: every B-size model and lower baseline, every main probe, all blocks, the full noise grid.

Sources: SiT-B/2 (latent denoiser), JiT-B/16 (pixel denoiser), MAE-B, MoCo v3-B, DINO-B, iBOT-B, DeiT III-B, DINOv2-B
(external-data reference), and the protocol's lower baselines (noisy VAE-latent patches, noisy pixel patches, clean pixel
patches).  Denoisers and noisy baselines at s in {0.05, 0.1, 0.3, 0.5, 0.7}; encoders on clean images.
Probes (frozen features, 3 seeds = 3 validation folds): NYU depth and normals (ridge, one feature pass), ADE20K linear
segmentation (soft-label CE per token), ImageNet classification (mean patch token; encoders also CLS, reference only).

Units are (source, s, task-group) with a done marker under out/p3/ mirrored to Drive; a rerun skips finished units and a
source whose units are all done is not even loaded.  results_long.csv is rebuilt from the per-unit CSVs on the VM and on
Drive (a new VM only holds its own units).  Checkpoints are deleted once all units of their source are done.
"""
from __future__ import annotations

import csv
import json
import os
import subprocess
import sys
import time
from pathlib import Path

import numpy as np
import torch

CODE = Path(__file__).resolve().parent
sys.path.insert(0, str(CODE))
import data5 as D  # noqa: E402
import models5 as M  # noqa: E402
import probes5 as PR  # noqa: E402
from common5 import (OUT_DRIVE, OUT_LOCAL, WORK, disk_free_gb, drive_ok, env_report, is_done, log, mark_done,  # noqa: E402
                     sync_out, write_json)

SIZE = os.environ.get("SET5_SIZE", "B")              # B -> phase 3 (out/p3); L -> phase 4 (out/p4)
PHASE_DIR = "p3" if SIZE == "B" else "p4"
OUT = OUT_LOCAL / PHASE_DIR
PER = OUT_LOCAL / "perimage" / PHASE_DIR
OUT.mkdir(parents=True, exist_ok=True)
PER.mkdir(parents=True, exist_ok=True)
S_GRID = [0.05, 0.1, 0.3, 0.5, 0.7]
TASKS = ("nyu", "seg", "cls")
STEPS = {"sit_b": "800K steps (author, issue #42)", "jit_b": "600 ep (README)", "mae_b": "1600 ep", "mocov3_b": "300 ep",
         "dino_b": "400 ep", "ibot_b": "400 ep", "deit3_b": "800+20 ep", "dinov2_b": "LVD-142M (external)",
         "base_latent": "", "base_pixel": "", "base_pixel_clean": "",
         "sit_l": "800K steps (author, issue #42)", "jit_l": "600 ep (README)", "mae_l": "1600 ep",
         "mocov3_l": "300 ep (third-party reproduction)", "ibot_l": "250 ep", "deit3_l": "800+20 ep"}
SOURCES_L = [  # protocol: no DINO v1-L; baselines are size independent (phase 3); DINOv2 reference is B only
    ("sit_l", lambda: M.SiTSource("L"), S_GRID),
    ("jit_l", lambda: M.JiTSource("L"), S_GRID),
    ("mae_l", lambda: M.EncoderSource("mae_l"), [None]),
    ("mocov3_l", lambda: M.EncoderSource("mocov3_l"), [None]),
    ("ibot_l", lambda: M.EncoderSource("ibot_l"), [None]),
    ("deit3_l", lambda: M.EncoderSource("deit3_l"), [None]),
]
SOURCES = [
    ("sit_b", lambda: M.SiTSource("B"), S_GRID),
    ("jit_b", lambda: M.JiTSource("B"), S_GRID),
    ("mae_b", lambda: M.EncoderSource("mae_b"), [None]),
    ("mocov3_b", lambda: M.EncoderSource("mocov3_b"), [None]),
    ("dino_b", lambda: M.EncoderSource("dino_b"), [None]),
    ("ibot_b", lambda: M.EncoderSource("ibot_b"), [None]),
    ("deit3_b", lambda: M.EncoderSource("deit3_b"), [None]),
    ("dinov2_b", lambda: M.EncoderSource("dinov2_b"), [None]),
    ("base_latent", lambda: M.PatchBaseline("latent"), S_GRID),
    ("base_pixel", lambda: M.PatchBaseline("pixel"), S_GRID),
    ("base_pixel_clean", lambda: M.PatchBaseline("pixel_clean"), [None]),
]


def s_label(s):
    return "clean" if s is None else s


def unit_rel(name, s, task):
    return f"{PHASE_DIR}/{name}_s{s_label(s)}_{task}.done"


def blocks_of(src):
    """B: every block (12); L: every second block (12 points), as the protocol asks."""
    n = src.n_blocks
    return list(range(1, n + 1)) if n <= 12 else list(range(2, n + 1, 2))


def make_fn(src, split, data, s, blocks, lat):
    if src.kind == "latent":
        def fn(idx):
            return src.tokens(torch.from_numpy(lat[idx]).cuda(), torch.from_numpy(D.noise(split, idx, "lat")).cuda(),
                              s, blocks)
    elif src.kind == "pixel":
        def fn(idx):
            x = torch.from_numpy(np.ascontiguousarray(data["img"][idx])).cuda().permute(0, 3, 1, 2).float() / 127.5 - 1
            return src.tokens(x, torch.from_numpy(D.noise(split, idx, "pix")).cuda(), s, blocks)
    else:
        def fn(idx):
            return src.tokens(data["img"][idx], blocks)
    return fn


@torch.no_grad()
def pooled(src, fn, data, blocks, bs=250):
    """Mean patch token per block [+ CLS per block for encoders with a CLS token]: [L(+L), N, D] on GPU."""
    n = len(data["img"])
    with_cls = src.kind == "image" and getattr(src, "prefix", 0) > 0
    L = len(blocks)
    X = torch.zeros(L * (2 if with_cls else 1), n, src.dim, device="cuda")
    for i0 in range(0, n, bs):
        idx = np.arange(i0, min(n, i0 + bs))
        if with_cls:
            patches, cls = src.tokens(data["img"][idx], blocks, with_cls=True)
            for l, c in enumerate(cls):
                X[L + l, i0:i0 + len(idx)] = c
        else:
            patches = fn(idx)
        for l, p in enumerate(patches):
            X[l, i0:i0 + len(idx)] = p.mean(1)
    return X, with_cls


def write_rows(path, rows, meta):
    with open(path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=PR.FIELDS)
        w.writeheader()
        for r in rows:
            w.writerow({**{k: "" for k in PR.FIELDS}, **meta, **r})


def run_unit(name, src, s, task, ctx):
    blocks = blocks_of(src)
    t0 = time.time()
    if task == "nyu":
        fn = make_fn(src, "nyu", ctx["nyu"], s, blocks, ctx["lat"].get("nyu"))
        rows, per, ch = PR.nyu_probe(fn, ctx["nyu"], ctx["design"], blocks)
    elif task == "seg":
        ftr = make_fn(src, "ade_train", ctx["ade_train"], s, blocks, ctx["lat"].get("ade_train"))
        fte = make_fn(src, "ade_val", ctx["ade_val"], s, blocks, ctx["lat"].get("ade_val"))
        # ADE train features of all chosen blocks are held in CPU RAM (bf16); split into passes when they would not fit
        n_pass = 2 if len(blocks) * src.dim > 12 * 768 else 1
        chunks = [blocks[i::n_pass] for i in range(n_pass)]
        rows, per, ch = [], None, []
        for cb in chunks:
            r_, p_, c_ = PR.seg_probe(make_fn(src, "ade_train", ctx["ade_train"], s, cb, ctx["lat"].get("ade_train")),
                                      make_fn(src, "ade_val", ctx["ade_val"], s, cb, ctx["lat"].get("ade_val")),
                                      ctx["ade_train"], ctx["ade_val"], cb)
            rows += r_
            ch += c_
            if per is None:
                per = {"ade_counts": np.zeros((len(blocks),) + p_["ade_counts"].shape[1:], np.int32)}
            for j, b in enumerate(cb):
                per["ade_counts"][blocks.index(b)] = p_["ade_counts"][j]
    else:
        tr, ev = ctx["inet_train"], ctx["inet_eval"]
        Xtr, with_cls = pooled(src, make_fn(src, "inet_train", tr, s, blocks, ctx["lat"].get("inet_train")), tr, blocks)
        Xte, _ = pooled(src, make_fn(src, "inet_eval", ev, s, blocks, ctx["lat"].get("inet_eval")), ev, blocks)
        names = [f"b{b}" for b in blocks] + ([f"b{b}_cls" for b in blocks] if with_cls else [])
        rows, per_c, ch = PR.cls_probe(Xtr, torch.from_numpy(tr["lbl"]).cuda(), torch.from_numpy(tr["fold"]).cuda(),
                                       Xte, torch.from_numpy(ev["lbl"]).cuda(), names)
        del Xtr, Xte
        for r in rows:
            nm = r["layer"]
            r["layer"] = int(nm.split("_")[0][1:])
            if nm.endswith("_cls"):
                r["metric"] = r["metric"].replace("top1", "top1_cls")
        per = {"correct": per_c.astype(np.int8)}
    nb = src.n_blocks
    for r in rows:
        r.update(s=s_label(s), depth_rel=0.0 if name.startswith("base_") else round(r["layer"] / nb, 4))
    tag = f"{name}_s{s_label(s)}_{task}"
    group = getattr(src, "group", "")
    write_rows(OUT / f"{tag}_rows.csv", rows, dict(model=name, method=group, steps=STEPS.get(name, ""), size=SIZE,
                                                    group=group))
    np.savez_compressed(PER / f"{tag}.npz", **per)
    write_json(OUT / f"{tag}_choices.json", ch)
    key = {"nyu": ("nyu_depth", "rmse"), "seg": ("ade_seg", "miou"), "cls": ("imagenet_cls", "top1")}[task]
    best = [(r["layer"], round(r["mean"], 4)) for r in rows if (r["task"], r["metric"]) == key]
    log(f"[{tag}] {time.time() - t0:.0f}s; {key[1]} by block: {best}")
    torch.cuda.empty_cache()
    mark_done(unit_rel(name, s, task), {"seconds": round(time.time() - t0), "ckpt": getattr(src, "ckpt", None)})


def summarise():
    """results_long.csv from every per-unit CSV, on the VM or on Drive (VM copy wins)."""
    files = {}
    if drive_ok() and (OUT_DRIVE / PHASE_DIR).is_dir():
        files.update({p.name: p for p in (OUT_DRIVE / PHASE_DIR).glob("*_rows.csv")})
    files.update({p.name: p for p in OUT.glob("*_rows.csv")})
    rows = []
    for nm in sorted(files):
        with open(files[nm]) as f:
            rows += list(csv.DictReader(f))
    with open(OUT / "results_long.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=PR.FIELDS)
        w.writeheader()
        w.writerows(rows)
    log(f"[summary] {len(rows)} rows from {len(files)} unit files")


def prepare(ctx):
    logs = WORK / "logs"
    logs.mkdir(exist_ok=True)
    jobs = []
    if not (D.CACHE / "inet_train.done").exists():   # CPU download/decoding runs beside the NYU/ADE preparation
        jobs.append(subprocess.Popen([sys.executable, str(CODE / "data5.py"), "val,train"],
                                     stdout=open(logs / "inet_prep.log", "a"), stderr=subprocess.STDOUT))
    D.prepare_nyu()
    D.prepare_normals()
    D.prepare_ade()
    for j in jobs:
        if j.wait() != 0:
            raise RuntimeError("ImageNet preparation failed (logs/inet_prep.log)")
    for sp in ("nyu", "ade_train", "ade_val", "inet_train", "inet_eval"):
        ctx[sp] = D.load(sp)
    vae = {}

    def get_vae():
        vae.setdefault("v", M.VAE())
        return vae["v"]

    ctx["lat"] = {sp: M.latents(sp, ctx[sp]["img"], get_vae, D.CACHE) for sp in
                  ("nyu", "ade_train", "ade_val", "inet_train", "inet_eval")}
    vae.clear()
    torch.cuda.empty_cache()
    dp = D.CACHE / "nyu_designs.pt"
    if not dp.exists():
        tr = np.flatnonzero(ctx["nyu"]["split"] == 0)
        torch.save(PR.nyu_designs(ctx["nyu"], tr), dp)
    ctx["design"] = torch.load(dp)


def main():
    only = sys.argv[1].split(",") if len(sys.argv) > 1 else None
    M.no_tf32()
    smi, df = env_report()
    print(smi, df, flush=True)
    write_json(OUT / "env.json", {"nvidia_smi": smi, "df": df, "disk_free_gb": round(disk_free_gb(), 1),
                                  "torch": torch.__version__, "gpu": torch.cuda.get_device_name()})
    ctx = {}
    prepare(ctx)
    summarise()
    sync_out()
    for name, ctor, svals in (SOURCES if SIZE == "B" else SOURCES_L):
        if only and name not in only:
            continue
        todo = [(s, t) for s in svals for t in TASKS if not is_done(unit_rel(name, s, t))]
        if not todo:
            continue
        src = ctor()
        log(f"[{name}] loaded; {len(todo)} units to run")
        for s, t in todo:
            run_unit(name, src, s, t, ctx)
            summarise()
            sync_out()
        path = getattr(src, "path", None)
        src.close()
        del src
        torch.cuda.empty_cache()
        if path and Path(path).exists() and Path(path).is_file():
            os.remove(path)  # protocol: delete a checkpoint once its model is probed
            log(f"[{name}] checkpoint deleted")
    summarise()
    sync_out()
    log(f"PHASE3 FINISHED (size {SIZE})")


if __name__ == "__main__":
    main()