File size: 12,930 Bytes
c8420ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""Set 5, phase 2 (pilot): SiT-B/2, JiT-B/16, MAE-B; NYU depth only, two noise levels, three blocks; plus the
pilot checks the protocol asks for.

  1. samples from SiT-B and JiT-B through the same loaders used for features (grids);
  2. prediction error vs s on 256 ImageNet val images (1 per class, classes 0-255), with the mapping used (t = 1 - s)
     and the opposite one (t = s): the used mapping must give an error that grows with s and is far below the
     opposite mapping at low s (confirms the time convention of the inputs fed to the probes);
  3. NYU depth (ridge, 3 seeds): SiT-B and JiT-B at s in {0.1, 0.5}, MAE-B on clean images; blocks 4, 8, 12;
  4. ImageNet classification, MoCo v3-B vs MAE-B (mean patch token at blocks 4, 8, 12; CLS at block 12 as reference).

Resumable: each unit writes out/pilot/<unit>.done (mirrored to Drive) and is skipped when present.
ImageNet train (gated) is prepared by a CPU subprocess that waits for the HF token file; GPU work does not wait for it
until step 4.
"""
from __future__ import annotations

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

import numpy as np
import torch
from PIL import Image

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_LOCAL, WORK, disk_free_gb, env_report, is_done, log, mark_done, sync_out, write_json  # noqa: E402

OUT = OUT_LOCAL / "pilot"
PER = OUT_LOCAL / "perimage" / "pilot"  # per-image metrics (derived from NYU / ImageNet): Drive only, never pushed to HF
OUT.mkdir(parents=True, exist_ok=True)
PER.mkdir(parents=True, exist_ok=True)
BLOCKS = [4, 8, 12]
S_PILOT = [0.1, 0.5]
S_CHECK = [0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9, 0.98]
GRID_CLASSES = [88, 207, 279, 291, 360, 387, 417, 812, 933, 963, 970, 980, 1, 130, 323, 954]
STEPS = {"sit_b": "800K steps (author, issue #42)", "jit_b": "600 ep (README)", "mae_b": "1600 ep",
         "mocov3_b": "300 ep"}


def save_grid(u8, path):  # [16, 3, H, W] or [16, H, W, 3] uint8
    a = u8.permute(0, 2, 3, 1).cpu().numpy() if u8.shape[1] == 3 else np.asarray(u8)
    rows = [np.concatenate(a[r * 4:(r + 1) * 4], 1) for r in range(4)]
    Image.fromarray(np.concatenate(rows, 0)).save(path)


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 check_rows(model, kind, s, mapping, err, ident=None, err_v=None):
    return dict(model=model, kind=kind, s=s, mapping=mapping, rel_err_x0=err, rel_err_identity=ident,
                rel_err_velocity=err_v)


def check_subset(ev):
    return np.arange(256) * D.EVAL_PER_CLASS  # inet_eval is class-major: first image of classes 0..255


# ----------------------------------------------------------------------------- denoisers
@torch.no_grad()
def unit_sit(nyu, ev, nyu_lat):
    rel = "pilot/sit_b.done"
    if is_done(rel):
        return
    t0 = time.time()
    src = M.SiTSource("B")
    vae = M.VAE()
    save_grid(src.sample_grid(vae, GRID_CLASSES), OUT / "sit_B_grid_sde250_nocfg.png")
    # time convention check (x0 estimate from the velocity: x0 = x_s + s * v)
    idx = check_subset(ev)
    x0 = vae.encode(ev["img"][idx])
    eps = torch.from_numpy(D.noise("inet_eval", idx, "lat")).cuda()
    del vae
    torch.cuda.empty_cache()
    var, chk = float(x0.var()), []
    for s in S_CHECK:
        xs = (1 - s) * x0 + s * eps
        ident = float(((xs - x0) ** 2).mean()) / var
        for mapping, t in (("t=1-s (used)", 1 - s), ("t=s (opposite)", s)):
            v = torch.cat([src.predict(xs[i:i + 64], t) for i in range(0, len(xs), 64)])
            x0h = xs + s * v
            chk.append(check_rows("sit_b", "latent velocity", s, mapping, float(((x0h - x0) ** 2).mean()) / var,
                                  ident, float(((v - (x0 - eps)) ** 2).mean() / ((x0 - eps) ** 2).mean())))
    write_json(OUT / "sit_b_time_check.json", chk)
    rows = depth_for(src, nyu, lambda idx, s: src.tokens(torch.from_numpy(nyu_lat[idx]).cuda(),
                                                         torch.from_numpy(D.noise("nyu", idx, "lat")).cuda(), s, BLOCKS))
    meta = dict(model="sit_b", method="denoise_latent", steps=STEPS["sit_b"], size="B", group="denoise_latent")
    write_rows(OUT / "sit_b_rows.csv", rows, meta)
    write_json(OUT / "sit_b_info.json", {"ckpt": src.ckpt, "seconds": round(time.time() - t0), "blocks": BLOCKS,
                                         "s": S_PILOT, "n_blocks": src.n_blocks})
    src.close()
    mark_done(rel)


@torch.no_grad()
def unit_jit(nyu, ev):
    rel = "pilot/jit_b.done"
    if is_done(rel):
        return
    t0 = time.time()
    src = M.JiTSource("B")
    for cfg in (1.0, M.JiTSource.CFG["B"]):
        save_grid(src.sample_grid(GRID_CLASSES, cfg), OUT / f"jit_B_grid_heun50_cfg{cfg}.png")
    idx = check_subset(ev)
    x = torch.from_numpy(np.ascontiguousarray(ev["img"][idx])).cuda().permute(0, 3, 1, 2).float() / 127.5 - 1
    eps = torch.from_numpy(D.noise("inet_eval", idx, "pix")).cuda()
    var, chk = float(x.var()), []
    for s in S_CHECK:
        z = (1 - s) * x + s * src.noise_scale * eps
        ident = float(((z - x) ** 2).mean()) / var
        for mapping, t in (("t=1-s (used)", 1 - s), ("t=s (opposite)", s)):
            xp = torch.cat([src.predict(z[i:i + 64], t) for i in range(0, len(z), 64)])
            chk.append(check_rows("jit_b", "pixel x-prediction", s, mapping, float(((xp - x) ** 2).mean()) / var, ident))
    write_json(OUT / "jit_b_time_check.json", chk)

    def feats(idx, s):
        xi = torch.from_numpy(np.ascontiguousarray(nyu["img"][idx])).cuda().permute(0, 3, 1, 2).float() / 127.5 - 1
        return src.tokens(xi, torch.from_numpy(D.noise("nyu", idx, "pix")).cuda(), s, BLOCKS)

    rows = depth_for(src, nyu, feats)
    meta = dict(model="jit_b", method="denoise_pixel", steps=STEPS["jit_b"], size="B", group="denoise_pixel")
    write_rows(OUT / "jit_b_rows.csv", rows, meta)
    write_json(OUT / "jit_b_info.json", {"ckpt": src.ckpt, "seconds": round(time.time() - t0), "blocks": BLOCKS,
                                         "s": S_PILOT, "n_blocks": src.n_blocks, "in_context": [src.ic_start, src.ic_len]})
    src.close()
    mark_done(rel)


def depth_for(src, nyu, feats_s):
    rows = []
    for s in S_PILOT:
        r, per, ch = PR.depth_probe(lambda idx: feats_s(idx, s), nyu, BLOCKS)
        for x in r:
            x.update(s=s, depth_rel=round(x["layer"] / src.n_blocks, 4))
        rows += r
        np.savez_compressed(PER / f"{src.name}_depth_s{s}.npz", **per)
        write_json(OUT / f"{src.name}_depth_s{s}_choices.json", ch)
        log(f"[{src.name}] depth s={s}: " + ", ".join(f"b{x['layer']} rmse {x['mean']:.3f}" for x in r
                                                     if x["metric"] == "rmse"))
    return rows


# ----------------------------------------------------------------------------- encoders
@torch.no_grad()
def unit_mae_depth(nyu):
    rel = "pilot/mae_b_depth.done"
    if is_done(rel):
        return
    t0 = time.time()
    src = M.EncoderSource("mae_b")
    rows, per, ch = PR.depth_probe(lambda idx: src.tokens(nyu["img"][idx], BLOCKS), nyu, BLOCKS)
    for x in rows:
        x.update(s="clean", depth_rel=round(x["layer"] / src.n_blocks, 4))
    np.savez_compressed(PER / "mae_b_depth_clean.npz", **per)
    write_json(OUT / "mae_b_depth_choices.json", ch)
    write_rows(OUT / "mae_b_depth_rows.csv", rows, dict(model="mae_b", method="masked", steps=STEPS["mae_b"], size="B",
                                                        group="masked"))
    write_json(OUT / "mae_b_info.json", {"ckpt": src.ckpt, "seconds": round(time.time() - t0)})
    log("[mae_b] depth: " + ", ".join(f"b{x['layer']} rmse {x['mean']:.3f}" for x in rows if x["metric"] == "rmse"))
    src.close()
    mark_done(rel)


@torch.no_grad()
def pooled(src, img, bs=250):
    L = len(BLOCKS) + 1
    X = torch.zeros(L, len(img), src.dim, device="cuda")
    for i in range(0, len(img), bs):
        patches, cls = src.tokens(img[i:i + bs], BLOCKS, with_cls=True)
        for l, p in enumerate(patches):
            X[l, i:i + bs] = p.mean(1)
        X[-1, i:i + bs] = cls[-1]
    return X


def unit_cls(name, ev):
    rel = f"pilot/cls_{name}.done"
    if is_done(rel):
        return
    tr = D.load("inet_train")
    t0 = time.time()
    src = M.EncoderSource(name)
    Xtr, Xte = pooled(src, tr["img"]), pooled(src, ev["img"])
    src.close()
    names = [f"b{b}_meanpatch" for b in BLOCKS] + [f"b{BLOCKS[-1]}_cls"]
    rows, per, 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)
    for x in rows:
        b = int(x["layer"].split("_")[0][1:])
        x.update(s="clean", depth_rel=round(b / 12, 4))
    np.savez_compressed(PER / f"{name}_cls.npz", correct=per)
    write_json(OUT / f"{name}_cls_choices.json", ch)
    write_rows(OUT / f"{name}_cls_rows.csv", rows, dict(model=name, method=src.group, steps=STEPS[name], size="B",
                                                         group=src.group))
    log(f"[{name}] cls: " + ", ".join(f"{x['layer']} {x['mean']:.4f}" for x in rows if x["metric"] == "top1"))
    mark_done(rel, {"seconds": round(time.time() - t0)})


# ----------------------------------------------------------------------------- summary
def summarise():
    rows = []
    for p in sorted(OUT.glob("*_rows.csv")):
        rows += list(csv.DictReader(open(p)))
    with open(OUT / "results_long.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=PR.FIELDS)
        w.writeheader()
        w.writerows(rows)
    out = {}
    for m in ("sit_b", "jit_b"):
        p = OUT / f"{m}_time_check.json"
        if not p.exists():
            continue
        chk = json.loads(p.read_text())
        used = [c for c in chk if c["mapping"].startswith("t=1-s")]
        opp = {c["s"]: c["rel_err_x0"] for c in chk if c["mapping"].startswith("t=s")}
        errs = [c["rel_err_x0"] for c in used]
        out[m] = dict(monotone=bool(all(b >= a - 1e-3 for a, b in zip(errs, errs[1:]))),
                      used_below_opposite_s_le_0_3=bool(all(c["rel_err_x0"] < opp[c["s"]] for c in used if c["s"] <= 0.3)),
                      used_err=dict(zip([c["s"] for c in used], errs)), opposite_err=opp)
    top1 = {(r["model"], r["layer"]): float(r["mean"]) for r in rows
            if r["task"] == "imagenet_cls" and r["metric"] == "top1"}
    if ("mocov3_b", "b12_meanpatch") in top1 and ("mae_b", "b12_meanpatch") in top1:
        out["cls_mocov3_gt_mae_b12"] = top1[("mocov3_b", "b12_meanpatch")] > top1[("mae_b", "b12_meanpatch")]
    out["top1"] = {f"{k[0]}:{k[1]}": v for k, v in top1.items()}
    write_json(OUT / "pilot_checks.json", out)
    log("[summary] " + json.dumps(out))


def main():
    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()})
    log(f"disk free {disk_free_gb():.0f} GB")
    logs = WORK / "logs"
    logs.mkdir(exist_ok=True)
    train_job = None
    if not (D.CACHE / "inet_train.done").exists():  # CPU-only download/decoding, overlaps the GPU units
        train_job = subprocess.Popen([sys.executable, str(CODE / "data5.py"), "train"],
                                     stdout=open(logs / "inet_train.log", "a"), stderr=subprocess.STDOUT)
    D.prepare_imagenet_val()
    ev = D.load("inet_eval")
    depth_units = ("pilot/sit_b.done", "pilot/jit_b.done", "pilot/mae_b_depth.done")
    if not all(is_done(u) for u in depth_units):  # a new VM after the depth units finished skips NYU entirely
        D.prepare_nyu()
        nyu = D.load("nyu")
        vae_holder = {}

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

        nyu_lat = M.latents("nyu", nyu["img"], get_vae, D.CACHE)
        vae_holder.clear()
        torch.cuda.empty_cache()
        for unit in (lambda: unit_sit(nyu, ev, nyu_lat), lambda: unit_jit(nyu, ev), lambda: unit_mae_depth(nyu)):
            unit()
            summarise()
            sync_out()
    else:
        log("depth units already done (Drive markers); skipping NYU")
    if train_job is not None and train_job.wait() != 0:
        raise RuntimeError("ImageNet train preparation failed (see logs/inet_train.log)")
    for name in ("mocov3_b", "mae_b"):
        unit_cls(name, ev)
        summarise()
        sync_out()
    log("PILOT FINISHED")


if __name__ == "__main__":
    main()