File size: 17,524 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""Fine-tune a pretraining checkpoint on the target robot's shards (scripts/convert_v3.py), one joint policy over
all datasets, on one GPU.

    python scripts/finetune.py --shards ~/pop/realworld/shards --init <pretraining step_200000.pt> \
        --iface sent --t5 ~/pop/realworld/weights/t5_efficient_tiny --instructions ~/pop/realworld/instructions.json \
        --runs ~/pop/realworld/runs --run-id 261121-so101-sent-s0

Recipe = the V2 cells of the simulation (PoP scripts/train.py, 40k steps x 64): AdamW (0.9, 0.95), weight decay
0.05 (none on 1-D parameters), lr 3e-4, 3e-5 for the pretrained trunk and for the text encoder, 2,000 warmup steps
then cosine to 10%, gradient clip 1.0, EMA 0.9995, bf16, agent-view crop 0.8, L1 on 16-action chunks.

Differences from pretraining, both for a joint policy over several tasks:
  - One normalization for every dataset (state, and action relative to the current state), pooled over the train
    split. Per-dataset statistics would tell the policy which task it is in through the normalized state.
  - Conditioning (--iface): "sent" = the task instruction through T5 (popt/model.py PopFinetune).
The validation split (5 episodes per dataset) gives the EMA model's L1 every --val-every steps, per dataset and
overall. It is reported only: the last checkpoint is the one used.

Writes <runs>/<run_id>/: config.json, train.log, ckpt/step_XXXXXX.pt (EMA weights, config, normalization,
instruction table), ckpt/resume.pt, train_done.json. A rerun with the same run id resumes.
"""
import argparse
import json
import math
import os
import sys
import time
from types import SimpleNamespace

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.data import ShardDataset  # noqa: E402
from popt.model import PopFinetune, prepare  # noqa: E402

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def pooled_stats(split_dir: str, chunk: int) -> dict:
    import scripts.preprocess as pre
    pre.A = SimpleNamespace(chunk=chunk)
    idx = json.load(open(os.path.join(split_dir, "index.json")))
    S, Ac, eps, off = [], [], [], 0
    for s in idx["shards"]:
        d = os.path.join(split_dir, s["dir"])
        z = np.load(os.path.join(d, "arrays.npz"))
        S.append(z["state"].astype(np.float64)); Ac.append(z["action"].astype(np.float64))
        for e in json.load(open(os.path.join(d, "episodes.json"))):
            eps.append(e | {"start": e["start"] + off})
        off += len(z["state"])
    return pre.norm_stats(np.concatenate(S), np.concatenate(Ac), eps)


def project_np(X: np.ndarray, cam: dict) -> np.ndarray:
    """Base-frame points (..., 3) -> pixels (..., 2) in the stored image (scripts/fit_camera.py camera)."""
    w = np.asarray(cam["rotvec"], np.float64)
    th = np.linalg.norm(w)
    k = w / max(th, 1e-12)
    K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
    R = np.eye(3) + math.sin(th) * K + (1 - math.cos(th)) * K @ K
    Y = X @ R.T + np.asarray(cam["t"])
    xy = Y[..., :2] / np.maximum(Y[..., 2:3], 1e-3)
    if "k1" in cam:
        r2 = (xy ** 2).sum(-1, keepdims=True)
        xy = xy * (1 + cam["k1"] * r2 + cam["k2"] * r2 ** 2)
    return xy * np.asarray(cam["f"]) + np.asarray(cam["c"])


class FTData(ShardDataset):
    """ShardDataset with one pooled normalization, the instruction index of every frame and, with ref=True, the
    referent labels (scripts/label_events.py) projected into the stored fixed view: 3D noise of noise_m metres on the
    object and destination points (as PoP's training), normalized coordinates (pixel centres at integers,
    [-1, 1] inside the image) of the points and of the gripper tip."""

    def __init__(self, split_dir: str, chunk: int, norm: dict, task_ids: dict, with_shard: bool = False,
                 ref: bool = False, noise_m: float = 0.0, need_labels: bool = False):
        super().__init__(split_dir, chunk, "delta")
        self.with_shard, self.ref, self.noise_m = with_shard, ref, noise_m
        oks, labs, cams = [], [], []
        if ref or need_labels:
            for s in self.shards:
                d = os.path.join(split_dir, s["dir"])
                z = dict(np.load(os.path.join(d, "ref.npz")))
                cj = json.load(open(os.path.join(d, "camera.json")))
                cam = dict(cj["camera"])
                if "distortion_k1_k2" in cj:
                    cam["k1"], cam["k2"] = cj["distortion_k1_k2"]
                oks.append(z["ok"]); labs.append(z); cams.append(cam)
            self.ok = np.concatenate(oks)
            self.lab = {k: np.concatenate([z[k] for z in labs]) for k in ("what", "where", "where_valid", "skill", "tip")}
            self.cams = cams
        else:
            self.ok = np.ones(self.N, bool)
        K = len(self.shards)
        self.mu_s = np.tile(np.array(norm["state_mean"], np.float32), (K, 1))
        self.sd_s = np.tile(np.array(norm["state_std"], np.float32), (K, 1))
        self.mu_a = np.tile(np.array(norm["delta_mean"], np.float32), (K, 1))
        self.sd_a = np.tile(np.array(norm["delta_std"], np.float32), (K, 1))
        task = []
        for s in self.shards:
            d = os.path.join(split_dir, s["dir"])
            ep = np.load(os.path.join(d, "arrays.npz"))["ep"]
            eps = json.load(open(os.path.join(d, "episodes.json")))
            per_ep = np.array([task_ids[e["task"]] for e in eps], np.int64)
            task.append(per_ep[ep])
        self.task = np.concatenate(task)

    def __getitem__(self, i):
        out = super().__getitem__(i)
        out["task"] = torch.tensor(self.task[i])
        if self.with_shard:
            out["shard"] = torch.tensor(int(self.sid[i]))
        if self.ref:
            cam = self.cams[int(self.sid[i])]
            L = self.lab
            X = np.stack([L["what"][i], L["where"][i]]).astype(np.float64)
            if self.noise_m > 0:
                X = X + np.random.randn(2, 3) * self.noise_m
            uv = project_np(np.concatenate([X, L["tip"][i][None].astype(np.float64)]), cam)
            xy = ((uv + 0.5) / self.res * 2 - 1).astype(np.float32)
            out["what_xy"], out["where_xy"], out["tip_xy"] = (torch.from_numpy(xy[k]) for k in range(3))
            out["where_valid"] = torch.tensor(bool(L["where_valid"][i]))
            out["skill"] = torch.tensor(int(L["skill"][i]))
        return out


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--shards", required=True, help="directory with train/ and val/ (scripts/convert_v3.py)")
    p.add_argument("--init", required=True, help="pretraining checkpoint (ckpt/step_XXXXXX.pt)")
    p.add_argument("--iface", default="sent", choices=["sent", "ref"])
    p.add_argument("--t5", default="", help="T5-Efficient-Tiny folder (config.json, pytorch_model.bin); iface sent")
    p.add_argument("--instructions", required=True, help="JSON with the tokenized instruction of every task")
    p.add_argument("--labelled-only", action="store_true",
                   help="train and validate only on frames with referent labels (ref.npz ok), for every iface")
    p.add_argument("--noise-m", type=float, default=0.01, help="iface ref: std of 3D pointer noise in training (m)")
    p.add_argument("--init-from-dino", default="", help="cell 2: DINOv2 weights file instead of --init (no pretraining)")
    p.add_argument("--runs", required=True)
    p.add_argument("--run-id", required=True)
    p.add_argument("--crop-min", type=float, default=0.8)
    p.add_argument("--batch", type=int, default=64)
    p.add_argument("--steps", type=int, default=40000)
    p.add_argument("--lr", type=float, default=3e-4)
    p.add_argument("--trunk-lr", type=float, default=3e-5)
    p.add_argument("--wd", type=float, default=0.05)
    p.add_argument("--warmup", type=int, default=2000)
    p.add_argument("--ema", type=float, default=0.9995)
    p.add_argument("--save-every", type=int, default=20000)
    p.add_argument("--resume-every", type=int, default=2000)
    p.add_argument("--val-every", type=int, default=2000)
    p.add_argument("--log-every", type=int, default=100)
    p.add_argument("--workers", type=int, default=8)
    p.add_argument("--seed", type=int, default=0)
    a = p.parse_args()

    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    cuda = dev.type == "cuda"
    if cuda:
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
    run = os.path.join(a.runs, a.run_id)
    ck = os.path.join(run, "ckpt")
    resume = os.path.join(ck, "resume.pt")
    os.makedirs(ck, exist_ok=True)
    log = open(os.path.join(run, "train.log"), "a")

    def say(s):
        print(s, flush=True)
        log.write(s + "\n"); log.flush()

    init = torch.load(a.init, map_location="cpu", weights_only=False)
    pc = init["config"]
    chunk = pc["chunk"]
    ins = json.load(open(a.instructions))
    table = ins["instructions"]
    task_ids = {r["text"]: k for k, r in enumerate(table)}
    L = max(len(r["ids"]) for r in table)
    ids = torch.zeros(len(table), L, dtype=torch.long)
    for k, r in enumerate(table):
        ids[k, :len(r["ids"])] = torch.tensor(r["ids"])
    ids, msk = ids.to(dev), (ids != 0).to(dev)

    norm = pooled_stats(os.path.join(a.shards, "train"), chunk)
    torch.manual_seed(a.seed); np.random.seed(a.seed)
    ref = a.iface == "ref"
    ds = FTData(os.path.join(a.shards, "train"), chunk, norm, task_ids, ref=ref, noise_m=a.noise_m,
                need_labels=a.labelled_only)
    vs = FTData(os.path.join(a.shards, "val"), chunk, norm, task_ids, with_shard=True, ref=ref,
                need_labels=a.labelled_only)
    if ref:
        assert a.labelled_only, "iface ref trains on labelled frames only: pass --labelled-only"
    version = open(os.path.join(ROOT, "VERSION")).read().strip() if os.path.exists(os.path.join(ROOT, "VERSION")) else "unknown"
    arch = {k: pc[k] for k in ("d", "layers", "heads", "chunk")}
    cfg = vars(a) | {"arch": arch, "init_step": init["step"], "init_config_run": pc.get("run_id"),
                     "code_version": version, "host": os.uname().nodename,
                     "gpu": torch.cuda.get_device_name(dev) if cuda else "cpu", "torch": torch.__version__,
                     "train_frames": int(ds.ok.sum()), "val_frames": int(vs.ok.sum()),
                     "datasets": [s["dataset"] for s in ds.shards],
                     "started": time.strftime("%Y-%m-%d %H:%M:%S")}
    if not os.path.exists(resume):
        json.dump(cfg, open(os.path.join(run, "config.json"), "w"), indent=1)

    def build(t5_pretrained, dino=None):
        return PopFinetune(iface=a.iface, t5_dir=a.t5 or None, t5_pretrained=t5_pretrained, d=arch["d"],
                           layers=arch["layers"], heads=arch["heads"], chunk=chunk, dino_weights=dino).to(dev)

    if a.init_from_dino:  # cell 2: DINOv2 trunk, everything else untrained (the architecture comes from --init)
        model = build(True, a.init_from_dino)
        loaded = {"loaded": 0, "missing": len(model.state_dict()), "dino": a.init_from_dino}
    else:
        model = build(True)
        loaded = model.load_pretrained(init["ema"])
    ema = build(False)
    ema.load_state_dict(model.state_dict())
    ema.requires_grad_(False).eval()
    counts = model.param_counts()
    say(f"run {a.run_id} code {version} | iface {a.iface} | init {a.init} step {init['step']} "
        f"({loaded['loaded']} tensors loaded, {loaded['missing']} new{', trunk from DINOv2 only' if a.init_from_dino else ''}) | "
        f"train {int(ds.ok.sum())} of {ds.N} frames in {len(ds.shards)} datasets, val {int(vs.ok.sum())} of {vs.N} | params " + " ".join(f"{k} {v / 1e6:.2f}M" for k, v in counts.items()))

    pre_p = list(model.trunk.parameters()) + (list(model.text.parameters()) if hasattr(model, "text") else [])
    pid = {id(q) for q in pre_p}
    rest = [q for q in model.parameters() if id(q) not in pid]
    groups = []
    for ps, lr in ((pre_p, a.trunk_lr), (rest, a.lr)):
        ps = [q for q in ps if q.requires_grad]
        groups.append({"params": [q for q in ps if q.ndim >= 2], "lr": lr, "base_lr": lr, "weight_decay": a.wd})
        groups.append({"params": [q for q in ps if q.ndim < 2], "lr": lr, "base_lr": lr, "weight_decay": 0.0})
    opt = torch.optim.AdamW(groups, betas=(0.9, 0.95), fused=cuda)
    step = 0
    if os.path.exists(resume):
        st = torch.load(resume, map_location=dev, weights_only=False)
        model.load_state_dict(st["model"]); ema.load_state_dict(st["ema"]); opt.load_state_dict(st["opt"])
        step = st["step"]
        say(f"resumed at step {step}")

    g = torch.Generator(); g.manual_seed(a.seed * 1_000_003 + step)
    # every frame equally likely, frames without labels never (all frames are labelled without --labelled-only)
    sampler = torch.utils.data.WeightedRandomSampler(torch.from_numpy(ds.ok.astype(np.float64)),
                                                     num_samples=(a.steps - step + 1) * a.batch, replacement=True,
                                                     generator=g)
    dl = torch.utils.data.DataLoader(ds, batch_size=a.batch, sampler=sampler, num_workers=a.workers, pin_memory=cuda,
                                     drop_last=True, persistent_workers=a.workers > 0,
                                     prefetch_factor=4 if a.workers > 0 else None)
    it = iter(dl)

    def lr_at(s):
        if s < a.warmup:
            return s / a.warmup
        q = (s - a.warmup) / max(1, a.steps - a.warmup)
        return 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * q))

    def loss_of(net, batch, crop):
        agent, wrist, state, wv, act, mask, aff = prepare(batch, crop, dev, return_aff=True)
        if ref:
            crop_xy = lambda xy: ((xy.to(dev) - aff[:, 1:3]) / aff[:, 0:1]).clamp(-2.0, 2.0)  # noqa: E731
            cond = {"what": crop_xy(batch["what_xy"]), "where": crop_xy(batch["where_xy"]),
                    "tip": crop_xy(batch["tip_xy"]), "where_valid": batch["where_valid"].to(dev),
                    "skill": batch["skill"].to(dev).long()}
        else:
            t = batch["task"].to(dev)
            cond = {"ids": ids[t], "mask": msk[t]}
        with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=cuda):
            pred = net(agent, wrist, state, wv, cond)
        err = (pred.float() - act).abs().mean(-1)
        return err, mask

    @torch.no_grad()
    def validate():
        vl = torch.utils.data.DataLoader(torch.utils.data.Subset(vs, np.nonzero(vs.ok)[0].tolist()), batch_size=128,
                                         shuffle=False, num_workers=4)
        tot = torch.zeros(len(vs.shards) + 1, 2, dtype=torch.float64)
        for b in vl:
            err, mask = loss_of(ema, b, 1.0)
            per = (err * mask).sum(1).double().cpu()
            n = mask.sum(1).double().cpu()
            tot[-1, 0] += per.sum(); tot[-1, 1] += n.sum()
            tot[:-1, 0].index_add_(0, b["shard"], per)
            tot[:-1, 1].index_add_(0, b["shard"], n)
        v = (tot[:, 0] / tot[:, 1]).tolist()
        return v[-1], {s["dataset"].split("/")[-1]: round(x, 4) for s, x in zip(vs.shards, v[:-1])}

    def save(path, full=False):
        payload = {"ema": ema.state_dict(), "config": cfg, "step": step, "param_counts": counts, "norm": norm,
                   "action_mode": "delta", "instructions": table, "init": a.init}
        if full:
            payload |= {"model": model.state_dict(), "opt": opt.state_dict()}
        torch.save(payload, path + ".tmp")
        os.replace(path + ".tmp", path)

    model.train()
    t0, tdata, n_seen = time.time(), 0.0, 0
    loss_acc = 0.0
    if step == 0:
        v, per = validate()
        say(f"val at step 0 (initial weights, interface untrained): L1 {v:.4f} {per}")
    while step < a.steps:
        for gr in opt.param_groups:
            gr["lr"] = gr["base_lr"] * lr_at(step)
        opt.zero_grad(set_to_none=True)
        t_data = time.time()
        batch = next(it)
        tdata += time.time() - t_data
        err, mask = loss_of(model, batch, a.crop_min)
        loss = (err * mask).sum() / mask.sum()
        loss.backward()
        gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        step += 1
        n_seen += a.batch
        loss_acc += loss.item()
        with torch.no_grad():
            dcy = min(a.ema, (1 + step) / (10 + step))
            for pe, pm in zip(ema.parameters(), model.parameters()):
                pe.lerp_(pm, 1 - dcy)
        if step % a.log_every == 0:
            el = time.time() - t0
            mem = torch.cuda.max_memory_allocated(dev) / 2 ** 30 if cuda else 0
            say(f"step {step} loss {loss_acc / a.log_every:.4f} gnorm {gn.item():.2f} lr {opt.param_groups[2]['lr']:.2e} | "
                f"{n_seen / el:.0f} samples/s, data wait {100 * tdata / el:.0f}% | mem {mem:.1f} GB")
            t0, tdata, n_seen, loss_acc = time.time(), 0.0, 0, 0.0
        if step % a.val_every == 0 or step == a.steps:
            v, per = validate()
            say(f"val step {step} L1 {v:.4f} {per}")
        if step % a.save_every == 0 or step == a.steps:
            save(os.path.join(ck, f"step_{step:06d}.pt"))
        if step % a.resume_every == 0 or step == a.steps:
            save(resume, full=True)
    json.dump({"step": step, "finished": time.strftime("%Y-%m-%d %H:%M:%S")}, open(os.path.join(run, "train_done.json"), "w"))
    say("done")


if __name__ == "__main__":
    main()