File size: 10,739 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
"""Step 4: pretrain the PoP trunk and control head on the shards, on one or more GPUs of one node.

    torchrun --standalone --nproc_per_node=2 scripts/train.py --work $POPT_WORK --run-id pretrain-community-s0
    python scripts/train.py --work $POPT_WORK --run-id smoke --steps 20 --batch 4 --workers 2    # one process

Recipe = PoP's (scripts/train.py in the PoP repository) unless stated: AdamW (0.9, 0.95), weight decay 0.05 (none
on 1-D parameters), trunk lr 3e-5 and head lr 3e-4, 2,000 warmup steps then cosine to 10%, gradient clip 1.0, EMA
0.9995, bf16 autocast, agent-view crop 0.8, L1 loss on 16-action chunks. Default length = SmolVLA's pretraining
budget: 200k steps at a global batch of 256 (51.2M samples).

Writes <work>/runs/<run_id>/: config.json, train.log, ckpt/step_XXXXXX.pt (EMA weights, config, normalization
statistics), ckpt/resume.pt (weights, EMA, optimizer, step; overwritten), train_done.json at the end. A rerun with
the same run id resumes from resume.pt. --stop-after-hours saves and exits cleanly before a SLURM time limit.
"""
import argparse
import contextlib
import json
import math
import os
import resource
import sys
import time

import numpy as np
import torch
import torch.distributed as dist

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

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


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--work", default=os.environ.get("POPT_WORK"), required=os.environ.get("POPT_WORK") is None)
    p.add_argument("--run-id", required=True)
    p.add_argument("--action-mode", default="delta", choices=["delta", "abs"])
    p.add_argument("--crop-min", type=float, default=0.8)
    p.add_argument("--d", type=int, default=224)
    p.add_argument("--layers", type=int, default=4)
    p.add_argument("--heads", type=int, default=7)
    p.add_argument("--chunk", type=int, default=int(os.environ.get("CHUNK", 16)))
    p.add_argument("--batch", type=int, default=256, help="global batch over all GPUs")
    p.add_argument("--accum", type=int, default=1, help="gradient accumulation steps")
    p.add_argument("--steps", type=int, default=200000)
    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, help="kept checkpoints")
    p.add_argument("--resume-every", type=int, default=2000, help="overwritten resume state")
    p.add_argument("--log-every", type=int, default=100)
    p.add_argument("--workers", type=int, default=12, help="data loader workers per GPU")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--stop-after-hours", type=float, default=0, help="save resume state and exit after this long (0 = off)")
    a = p.parse_args()

    ddp = "WORLD_SIZE" in os.environ
    cuda = torch.cuda.is_available()
    if ddp:
        dist.init_process_group("nccl" if cuda else "gloo")
        rank, world, local = dist.get_rank(), dist.get_world_size(), int(os.environ.get("LOCAL_RANK", 0))
    else:
        rank, world, local = 0, 1, 0
    dev = torch.device(f"cuda:{local}" if cuda else "cpu")
    if cuda:
        torch.cuda.set_device(dev)
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
    soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)  # one memmap per shard and loader worker
    resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))

    D = work_dirs(a.work)
    run = os.path.join(D["runs"], a.run_id)
    ck = os.path.join(run, "ckpt")
    resume = os.path.join(ck, "resume.pt")
    if rank == 0:
        os.makedirs(ck, exist_ok=True)
    if ddp:
        dist.barrier(device_ids=[local] if cuda else None)
    assert a.batch % (world * a.accum) == 0, (a.batch, world, a.accum)
    micro = a.batch // (world * a.accum)
    log = open(os.path.join(run, "train.log"), "a") if rank == 0 else None

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

    version = open(os.path.join(ROOT, "VERSION")).read().strip() if os.path.exists(os.path.join(ROOT, "VERSION")) else "unknown"
    cfg = vars(a) | {"world_size": world, "micro_batch": micro, "code_version": version, "host": os.uname().nodename,
                     "gpu": torch.cuda.get_device_name(dev) if cuda else "cpu", "torch": torch.__version__,
                     "started": time.strftime("%Y-%m-%d %H:%M:%S")}
    if rank == 0 and not os.path.exists(resume):
        with open(os.path.join(run, "config.json"), "w") as f:
            json.dump(cfg, f, indent=1)

    torch.manual_seed(a.seed + rank); np.random.seed(a.seed + rank)
    ds = ShardDataset(D["shards"], a.chunk, a.action_mode)
    model = PopPretrain(a.d, a.layers, a.heads, a.chunk, dino_weights=D["dino"]).to(dev)
    counts = model.param_counts()
    say(f"run {a.run_id} code {version} | {world} process(es), micro-batch {micro}, accum {a.accum}, global batch "
        f"{a.batch} | frames {ds.N} in {len(ds.shards)} datasets | params " +
        " ".join(f"{k} {v / 1e6:.2f}M" for k, v in counts.items()))
    ema = None
    if rank == 0:
        ema = PopPretrain(a.d, a.layers, a.heads, a.chunk, dino_weights=None).to(dev)
        ema.load_state_dict(model.state_dict())
        ema.requires_grad_(False).eval()

    trunk_p = [q for q in model.trunk.parameters() if q.requires_grad]
    tid = {id(q) for q in model.trunk.parameters()}
    head_p = [q for q in model.parameters() if id(q) not in tid and q.requires_grad]
    groups = []
    for ps, lr in ((trunk_p, a.trunk_lr), (head_p, a.lr)):
        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"]); opt.load_state_dict(st["opt"])
        if rank == 0:
            ema.load_state_dict(st["ema"])
        step = st["step"]
        say(f"resumed at step {step}")
    net = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local] if cuda else None) if ddp else model

    g = torch.Generator(); g.manual_seed(a.seed * 1_000_003 + rank * 7919 + step)
    sampler = torch.utils.data.RandomSampler(ds, replacement=True, num_samples=10 ** 10, generator=g)
    dl = torch.utils.data.DataLoader(ds, batch_size=micro, 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 save(path, full=False):
        if rank != 0:
            return
        payload = {"ema": ema.state_dict(), "config": cfg, "step": step, "param_counts": counts,
                   "norm_stats": ds.norm_stats(), "action_mode": a.action_mode}
        if full:
            payload |= {"model": model.state_dict(), "opt": opt.state_dict()}
        torch.save(payload, path + ".tmp")
        os.replace(path + ".tmp", path)

    model.train()
    t_job, t0, tdata, n_seen = time.time(), time.time(), 0.0, 0
    loss_acc = torch.zeros((), device=dev)
    stop = False
    while step < a.steps and not stop:
        for gr in opt.param_groups:
            gr["lr"] = gr["base_lr"] * lr_at(step)
        opt.zero_grad(set_to_none=True)
        for m in range(a.accum):
            t_data = time.time()
            batch = next(it)
            tdata += time.time() - t_data
            agent, wrist, state, wv, act, mask = prepare(batch, a.crop_min, dev)
            last = m == a.accum - 1
            with (net.no_sync() if ddp and not last else contextlib.nullcontext()):
                with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=cuda):
                    pred = net(agent, wrist, state, wv)
                err = (pred.float() - act).abs().mean(-1)
                loss = (err * mask).sum() / mask.sum() / a.accum
                loss.backward()
            loss_acc += loss.detach()
        gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        step += 1
        n_seen += a.batch
        if rank == 0:
            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:
            # mean loss over the interval and all ranks; the time-limit decision is shared so all ranks stop together
            over = float(bool(a.stop_after_hours) and (time.time() - t_job) / 3600 > a.stop_after_hours)
            v = torch.stack([loss_acc / a.log_every, torch.tensor(over, device=dev)])
            if ddp:
                dist.all_reduce(v)
                v[0] /= world
            stop = bool(v[1].item() > 0)
            el = time.time() - t0
            mem = torch.cuda.max_memory_allocated(dev) / 2 ** 30 if cuda else 0
            say(f"step {step} loss {v[0].item():.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}% (rank 0) | mem {mem:.1f} GB")
            t0, tdata, n_seen = time.time(), 0.0, 0
            loss_acc.zero_()
        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 or stop:
            save(resume, full=True)
            say(f"saved step {step}" + (" (time limit; rerun to continue)" if stop and step < a.steps else ""))
    if rank == 0 and step >= a.steps:
        with open(os.path.join(run, "train_done.json"), "w") as f:
            json.dump({"step": step, "finished": time.strftime("%Y-%m-%d %H:%M:%S")}, f)
        say("done")
    if ddp:
        dist.barrier(device_ids=[local] if cuda else None)
        dist.destroy_process_group()


if __name__ == "__main__":
    main()