File size: 6,017 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 | #!/usr/bin/env python3
"""Full-path smoke train - TRACE-VLA v1.1 reference configuration.
Exercises the complete v1.1 path end to end: DELTA (label-free
temporal windows, signed multi-scale residuals) -> SYNC (global soft
attention over the demo memory) -> NEXUS -> FLUX + ECHO, trained with
the default objective L_total = L_flux + 0.1 * L_echo (spec 16.1).
Data: label-free support-query pairs from the frozen-feature cache
(scripts/build_feature_cache.py). The support episode is a different
episode of the same task and supplies only demo frame features,
timestamps, and validity (spec 14.2). The configuration is
video-only: no text embedding is given, so the model must use the
demonstration (spec 15). PULSE and the skill alignment loss stay off
(lambda = 0, spec 10.1 and 16.3).
Optimizer: AdamW, base LR 1e-4, weight decay 0.01, gradient clipping
1.0. Smoke schedule: 10-update linear warmup, then cosine decay to
1e-5 over the run (smoke-scale deviation from the full warmup,
recorded here as in the Stage 1 smoke).
Prints a JSON summary: FLUX and ECHO loss at the first and last 10
updates, steps/s, peak VRAM, NaN flag.
"""
import argparse
import json
import math
import time
from pathlib import Path
import torch
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from trace_vla.config import TraceConfig # noqa: E402
from trace_vla.data import SupportQueryData # noqa: E402
from trace_vla.model import TraceVLA # noqa: E402
def lr_at(update, total, warmup, base=1e-4, floor=1e-5):
if update < warmup:
return base * (update + 1) / warmup
t = (update - warmup) / max(1, total - warmup)
return floor + 0.5 * (base - floor) * (1 + math.cos(math.pi * t))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", required=True)
ap.add_argument("--updates", type=int, default=120)
ap.add_argument("--micro", type=int, default=8)
ap.add_argument("--accum", type=int, default=4)
ap.add_argument("--warmup", type=int, default=10)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--out", default="")
args = ap.parse_args()
torch.manual_seed(args.seed)
device = "cuda"
cache = torch.load(args.cache, weights_only=False)
data = SupportQueryData(cache)
print(f"samples: {len(data)} from {len(data.episodes)} episodes",
flush=True)
cfg = TraceConfig() # v1.1 reference defaults
assert cfg.lambda_echo == 0.1 and cfg.lambda_delta == 0.0 \
and cfg.lambda_pulse == 0.0 and cfg.use_echo_loss
model = TraceVLA(cfg, load_anchor=False).to(device)
model.train()
params = [p for p in model.parameters() if p.requires_grad]
n_train = sum(p.numel() for p in params)
print(f"trainable params: {n_train:,}", flush=True)
opt = torch.optim.AdamW(params, lr=1e-4, weight_decay=0.01)
gen = torch.Generator().manual_seed(args.seed)
pair_gen = torch.Generator().manual_seed(args.seed + 1)
flux_hist, echo_hist = [], []
nan_seen = False
t0 = time.time()
micro_done = 0
for update in range(args.updates):
lr = lr_at(update, args.updates, args.warmup)
for group in opt.param_groups:
group["lr"] = lr
opt.zero_grad(set_to_none=True)
upd_flux = upd_echo = 0.0
for _ in range(args.accum):
idx = torch.randint(len(data), (args.micro,), generator=gen)
batch = data.get_batch([int(i) for i in idx], device,
generator=pair_gen)
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model.forward_train(batch)
loss = out["total"]
if not torch.isfinite(loss) or not torch.isfinite(out["flux"]) \
or not torch.isfinite(out["echo"]):
nan_seen = True
print(f"NON-FINITE loss at update {update}", flush=True)
break
(loss / args.accum).backward()
upd_flux += float(out["flux"].item()) / args.accum
upd_echo += float(out["echo"].item()) / args.accum
micro_done += 1
if nan_seen:
break
torch.nn.utils.clip_grad_norm_(params, 1.0)
opt.step()
flux_hist.append(upd_flux)
echo_hist.append(upd_echo)
if (update + 1) % 10 == 0 or update == 0:
elapsed = time.time() - t0
print(f"update {update + 1}/{args.updates} "
f"flux10={sum(flux_hist[-10:]) / len(flux_hist[-10:]):.4f} "
f"echo10={sum(echo_hist[-10:]) / len(echo_hist[-10:]):.4f} "
f"lr={lr:.2e} micro/s={micro_done / elapsed:.2f} "
f"vram_peak={torch.cuda.max_memory_allocated() / 1e6:.0f}MB",
flush=True)
elapsed = time.time() - t0
def first_last(hist):
if not hist:
return None, None
return (sum(hist[:10]) / max(1, len(hist[:10])),
sum(hist[-10:]) / max(1, len(hist[-10:])))
ff, fl = first_last(flux_hist)
ef, el = first_last(echo_hist)
summary = {
"config": "trace-vla v1.1 full path (DELTA+SYNC+NEXUS+FLUX+ECHO), "
"video-only support-query",
"updates_done": len(flux_hist),
"micro_batch": args.micro,
"accum": args.accum,
"effective_batch": args.micro * args.accum,
"trainable_params": n_train,
"flux_first10": ff, "flux_last10": fl,
"echo_first10": ef, "echo_last10": el,
"elapsed_s": round(elapsed, 1),
"micro_steps_per_s": round(micro_done / elapsed, 3),
"opt_steps_per_s": round(len(flux_hist) / elapsed, 3),
"peak_vram_mb": round(torch.cuda.max_memory_allocated() / 1e6, 1),
"nan_seen": nan_seen,
}
print("SUMMARY " + json.dumps(summary), flush=True)
if args.out:
Path(args.out).write_text(json.dumps(summary, indent=1))
if __name__ == "__main__":
main()
|