File size: 15,477 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""R6 200k run, PHASE 1 (30k -> 100k): vision top unfrozen.

Continues R6 from runs/r6_30k/ckpt_30000.pt with the ladder recipe
(micro 8 x accum 4, AdamW fresh, EMA 0.999, modality pattern
[text, video, hybrid, video], seed 0) on the cache_df_r2 pool, but
pooled features are recomputed every step through the vision tower:
frozen bottom (blocks 0-7) + trainable top (blocks 8-11 + final
norm). Policy LR follows the recipe lr_at(step, 200000); vision LR
is a separate cosine 1e-5 -> 1e-6 over 30k..100k with LLRD 0.75 per
block (block 11 + norm factor 1.0). Checkpoints keep the ladder keys
(model/ema) and add vision_top / vision_top_ema.
"""
import argparse
import json
import math
import sys
import time
from collections import Counter
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.config import TraceConfig                      # noqa: E402
from trace_vla.anchor import TipsAnchor                       # noqa: E402
from trace_vla.flux import flux_loss                          # noqa: E402
from df_data_raw import RawData, VisionPipe, VisionTop        # noqa: E402
from df_train_arms import Ema, grounding_losses_v3, lr_at, split_cache  # noqa: E402
from v2_dash import merge_item                                # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
DEVICE = "cuda"
MICRO, ACCUM = 8, 4
LAM_MATCH, LAM_TARGET, LAM_ROLE = 1.0, 1.0, 0.5
LAM_PROG, LAM_SDE = 0.1, 0.1
TOTAL_LR = 200000
PHASE_END = 100000
LLRD = {0: 0.75 ** 3, 1: 0.75 ** 2, 2: 0.75, 3: 1.0, "norm": 1.0}


def vision_lr(step, start=30000):
    p = min(1.0, max(0.0, (step - start) / (PHASE_END - start)))
    return 1e-6 + 0.5 * (1e-5 - 1e-6) * (1 + math.cos(math.pi * p))


@torch.no_grad()
def eval_flux_raw(policy, data, gen_seed, n_batches=25):
    gen = torch.Generator().manual_seed(gen_seed)
    vals = []
    policy.eval()
    for _ in range(n_batches):
        idx = torch.randint(0, len(data), (MICRO,),
                            generator=gen).tolist()
        batch = data.get_batch(idx, DEVICE, gen)
        with torch.autocast("cuda", dtype=torch.bfloat16):
            losses = policy.forward_train(batch)
        vals.append(float(losses["flux"]))
    policy.train()
    return float(np.mean(vals))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--steps", type=int, default=100000)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=None)
    ap.add_argument("--init", required=True)
    ap.add_argument("--start-step", type=int, required=True)
    ap.add_argument("--ckpt-steps", default=None)
    ap.add_argument("--smoke", type=int, default=0,
                    help="run only N steps then stop (no ckpt save "
                         "except grad verification output)")
    args = ap.parse_args()
    ckpt_set = set(int(x) for x in args.ckpt_steps.split(",")) \
        if args.ckpt_steps else set()
    dash_key = "data_factory.train.r6_200k"

    torch.manual_seed(args.seed)
    cfg = TraceConfig(delta_use_residuals=False, use_echo_loss=False)
    out_dir = Path(args.out) if args.out else \
        EXP / "data_factory" / "runs" / "r6_200k"
    out_dir.mkdir(parents=True, exist_ok=True)
    cache = torch.load(EXP / "data_factory" / "cache_df_r2.pt",
                       weights_only=True, mmap=True)
    train_c = split_cache(cache, "train")
    val_c = split_cache(cache, "val")
    pool = Counter(ep.get("source", "D0") for ep in train_c["episodes"])
    print("train pool episodes by source:", dict(pool), flush=True)

    from trace_vla.model_v4 import TraceVLA4
    anchor = TipsAnchor(cfg.backbone_id).to(DEVICE)
    pipe = VisionPipe(anchor)
    model = TraceVLA4(cfg, load_anchor=False).to(DEVICE)
    policy = model.v1
    text_data = RawData(train_c, cfg, pipe, want_grad=True)
    sq_data = text_data
    text_val = RawData(val_c, cfg, pipe, want_grad=False)
    sq_val = text_val
    text_emb = cache["text_emb"]

    resume_ck = torch.load(args.init, weights_only=False)
    assert int(resume_ck["step"]) == args.start_step
    assert resume_ck.get("arm") == "r6"
    _keys = sorted(model.state_dict().keys())
    _probe = [_keys[0], _keys[len(_keys) // 2], _keys[-1]]
    model.load_state_dict(resume_ck["model"], strict=True)
    _sd2 = model.state_dict()
    for _k in _probe:
        _d = (_sd2[_k].float()
              - resume_ck["model"][_k].float()).abs().max().item()
        print(f"RESUME VERIFY model[{_k}] max|loaded-ckpt| = {_d}",
              flush=True)
        assert _d == 0.0
    if "vision_top" in resume_ck:
        pipe.top.load_named_state(resume_ck["vision_top"])
        print("vision_top loaded from init ckpt", flush=True)
    else:
        print("vision_top = pretrained anchor weights (vision was "
              "frozen in all previous runs)", flush=True)
    print(f"RESUME init={args.init} step={resume_ck['step']}",
          flush=True)
    ema = Ema(model)
    ema.shadow = {k: v.detach().clone().float()
                  for k, v in resume_ck["ema"].items()}
    ema_vision = Ema(pipe.top)
    if "vision_top_ema" in resume_ck:
        ema_vision.shadow = {k: v.detach().clone().float() for k, v
                             in resume_ck["vision_top_ema"].items()}

    # ---- optimizer: policy group + LLRD vision groups -------------
    groups = [{"params": list(model.parameters()), "lr": 1e-4,
               "name": "policy"}]
    for i, blk in enumerate(pipe.top.blocks):
        groups.append({"params": list(blk.parameters()), "lr": 1e-5,
                       "name": f"vision_block{8 + i}",
                       "factor": LLRD[i]})
    groups.append({"params": list(pipe.top.norm.parameters()),
                   "lr": 1e-5, "name": "vision_norm",
                   "factor": LLRD["norm"]})
    opt = torch.optim.AdamW(groups, lr=1e-4, weight_decay=0.01)
    n_vis = sum(p.numel() for g in groups[1:] for p in g["params"])
    print(f"vision trainable params: {n_vis}", flush=True)

    gen = torch.Generator().manual_seed(1000 + args.seed)
    modes = ["text", "video", "hybrid", "video"]
    log_path = out_dir / "train_log.jsonl"
    end_step = args.start_step + args.smoke if args.smoke else args.steps
    summary = {"arm": "r6", "phase": "p1_vision_open",
               "steps": args.steps, "init": args.init,
               "start_step": args.start_step,
               "pool_by_source": dict(pool), "checkpoints": {}}
    t0 = time.time()
    recent = []
    model.train()
    merge_item(dash_key, {"status": "running", "pct": 0,
                          "step": f"{args.start_step}/200000",
                          "metrics": {"Pha": "1/2 · vision MỞ "
                                      "(blocks 8-11 + norm)"}})
    grad_checked = False
    for step in range(args.start_step + 1, end_step + 1):
        for pg in opt.param_groups:
            if pg.get("name") == "policy":
                pg["lr"] = lr_at(step - 1, TOTAL_LR)
            else:
                pg["lr"] = vision_lr(step - 1) * pg["factor"]
        opt.zero_grad()
        comp = {}
        for micro_i in range(ACCUM):
            mode = modes[micro_i % len(modes)]
            idx = torch.randint(0, len(sq_data), (MICRO,),
                                generator=gen).tolist()
            if mode == "text":
                batch = sq_data.get_batch(idx, DEVICE, text=True)
            else:
                batch = sq_data.get_batch(idx, DEVICE, gen)
                if mode == "hybrid":
                    tasks = [sq_data.episodes[int(e)]["task_index"]
                             for e in batch["query_episode"]]
                    batch["text_emb"] = torch.stack(
                        [text_emb[t] for t in tasks]).float().to(DEVICE)
            with torch.autocast("cuda", dtype=torch.bfloat16):
                if mode != "text":
                    ctx_kwargs = dict(
                        demo_pooled=batch["demo_pooled"],
                        frame_mask=batch["frame_mask"],
                        frame_times=batch["frame_times"],
                        cand_mask=batch["cand_mask"],
                        cand_valid=batch["cand_valid"])
                    context, aux = model.compute_context_v4(
                        batch["pooled_live"], batch.get("text_emb"),
                        batch["state_norm"], batch["history"],
                        **ctx_kwargs)
                    target = batch["action_target"]
                    b = target.shape[0]
                    tau = torch.rand(b, device=DEVICE)
                    eps = torch.randn_like(target)
                    a_tau = (1.0 - tau).view(b, 1, 1) * eps \
                        + tau.view(b, 1, 1) * target
                    velocity, eff_feat = model._velocity_v4(
                        context, a_tau, tau)
                    losses = {"flux": flux_loss(
                        velocity, target - eps, batch["action_mask"])}
                    losses["total"] = losses["flux"]
                    gl = grounding_losses_v3(model, aux, batch)
                    if gl is not None:
                        l_match, l_target, l_role = gl
                        losses["match"] = l_match
                        losses["target"] = l_target
                        losses["role"] = l_role
                        losses["total"] = losses["total"] \
                            + LAM_MATCH * l_match \
                            + LAM_TARGET * l_target \
                            + LAM_ROLE * l_role
                    losses["prog"] = F.mse_loss(
                        aux["p_live"], batch["query_progress"])
                    losses["sde"] = aux["sde_loss"]
                    losses["total"] = losses["total"] \
                        + LAM_PROG * losses["prog"] \
                        + LAM_SDE * losses["sde"]
                    if batch.get("echo_target") is not None:
                        from trace_vla.echo import echo_loss
                        pred = model.echo2(eff_feat, target)
                        tgt = model.echo2.project_target(
                            batch["echo_target"])
                        losses["echo"] = echo_loss(
                            pred, tgt, tau, batch["echo_valid"],
                            huber_delta=cfg.huber_delta,
                            tau_min=cfg.echo_tau_min)
                        losses["total"] = losses["total"] \
                            + cfg.lambda_echo * losses["echo"]
                else:
                    losses = policy.forward_train(batch)
            (losses["total"] / ACCUM).backward()
            if not grad_checked and micro_i == 0:
                ve = pipe.ve
                print("GRAD VERIFY (first micro-batch backward):",
                      flush=True)
                norms = {}
                for bi, blk in enumerate(ve.blocks):
                    gn = None
                    for p in blk.parameters():
                        if p.grad is not None:
                            gn = (gn or 0.0) + float(p.grad.norm()) ** 2
                    gn = None if gn is None else gn ** 0.5
                    norms[bi] = gn
                    print(f"  tower block {bi}: grad norm = {gn}",
                          flush=True)
                gn = sum(float(p.grad.norm()) ** 2
                         for p in ve.norm.parameters()
                         if p.grad is not None) ** 0.5
                print(f"  tower norm: grad norm = {gn}", flush=True)
                tp = next(anchor.tips.text_encoder.parameters())
                print(f"  text encoder sample param grad: {tp.grad}",
                      flush=True)
                assert all(norms[bi] is None for bi in range(8)), \
                    f"frozen blocks 0-7 received grads: {norms}"
                assert all(norms[bi] is not None and norms[bi] > 0
                           for bi in range(8, 12)), \
                    f"open blocks 8-11 missing grads: {norms}"
                assert gn > 0, "final norm received no grad"
                assert tp.grad is None, "text encoder received grad"
                print("GRAD VERIFY PASS: grads flow into blocks "
                      "8-11 + norm only", flush=True)
                grad_checked = True
            for k, v in losses.items():
                if v is not None:
                    comp[k] = comp.get(k, 0.0) + float(v) / ACCUM
        torch.nn.utils.clip_grad_norm_(
            [p for g in opt.param_groups for p in g["params"]], 1.0)
        opt.step()
        ema.update(model)
        ema_vision.update(pipe.top)
        recent.append(comp)
        if args.smoke and step == args.start_step + 1:
            print(f"FIRST STEP LOSSES: "
                  f"{ {k: round(v, 4) for k, v in comp.items()} }",
                  flush=True)
            assert 0.01 < comp["total"] < 2.0, \
                f"first-step total loss out of range: {comp['total']}"
        if step % 50 == 0:
            avg = {k: round(float(np.mean([r[k] for r in recent
                                            if k in r])), 4)
                   for k in recent[0]}
            recent = []
            with open(log_path, "a") as f:
                f.write(json.dumps({"step": step, **avg}) + "\n")
            sps = (time.time() - t0) / max(1, step - args.start_step)
            print(f"[r6-200k p1] step {step} {avg} ({sps:.2f} s/step)",
                  flush=True)
            merge_item(dash_key, {
                "status": "running",
                "pct": round(100.0 * step / TOTAL_LR, 1),
                "step": f"{step}/{TOTAL_LR}",
                "loss": avg.get("total"),
                "metrics": {"Pha": "1/2 · vision MỞ (blocks 8-11)",
                            "LR vision (top)": f"{vision_lr(step):.2e}",
                            "s/step": f"{sps:.2f}",
                            **{k: str(v) for k, v in avg.items()}}})
        if step in ckpt_set:
            entry = {}
            entry["val_flux_text"] = round(
                eval_flux_raw(policy, text_val, 777), 4)
            entry["val_flux_video"] = round(
                eval_flux_raw(policy, sq_val, 778), 4)
            named = pipe.top.named_state()
            named_ema = {}
            es = ema_vision.state_dict()
            for i in range(4):
                named_ema[f"blocks.{8 + i}"] = {
                    k[len(f"blocks.{i}."):]: v for k, v in es.items()
                    if k.startswith(f"blocks.{i}.")}
            named_ema["norm"] = es["norm"]
            ck = {"model": model.state_dict(),
                  "ema": ema.state_dict(), "step": step, "arm": "r6",
                  "phase": "p1",
                  "vision_top": named,
                  "vision_top_ema": named_ema}
            torch.save(ck, out_dir / f"ckpt_{step:05d}.pt")
            summary["checkpoints"][str(step)] = entry
            print(f"[r6-200k p1] ckpt {step}: {entry}", flush=True)
    summary["wall_seconds"] = round(time.time() - t0, 1)
    (out_dir / "summary.json").write_text(json.dumps(summary, indent=1))
    merge_item(dash_key, {"status": "done" if not args.smoke
                          else "smoke-done",
                          "pct": round(100.0 * end_step / TOTAL_LR, 1)})
    print(json.dumps(summary, indent=1))


if __name__ == "__main__":
    main()