ConsDrive / train_stream_petr.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
10.8 kB
"""Stage 2 (v2): train the StreamPETR-style streaming detector (models/stream_petr.py) on SimLingo clips.
torchrun --nproc_per_node=N train_stream_petr.py --out outputs/stream_petr/<name> [--init outputs/detector/det_v1/last.pt]
Each step processes --batch clips of --clip-len consecutive 4 Hz frames per GPU; the query memory is
reset at the start of each clip, carried (detached) across its frames, and the loss is summed over the
frames before one backward pass.
"""
import argparse
import json
import math
import os
import time
from pathlib import Path
import numpy as np
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, DistributedSampler, Subset
from dataloader.detection_clips import DetectionClipDataset
from dataloader.detection_data import route_fold
from models.detector_metrics import DetectionMetrics, format_summary
from models.stream_petr import StreamPETR, decode_stream, stream_petr_loss
from train_detector import DistributedWeightedSampler, to_device
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--init", default="outputs/detector/det_v1/last.pt",
help="train_detector.py .pt (backbone + FPN), FastVLM dir or driving-model .ckpt")
ap.add_argument("--freeze-backbone", action="store_true")
ap.add_argument("--batch", type=int, default=8, help="clips per GPU")
ap.add_argument("--clip-len", type=int, default=4)
ap.add_argument("--val-clip-len", type=int, default=8)
ap.add_argument("--workers", type=int, default=10)
ap.add_argument("--steps", type=int, default=30000)
ap.add_argument("--warmup", type=int, default=500)
ap.add_argument("--lr", type=float, default=2e-4, help="decoder / heads / neck")
ap.add_argument("--backbone-lr", type=float, default=2e-5)
ap.add_argument("--weight-decay", type=float, default=0.01)
ap.add_argument("--grad-clip", type=float, default=10.0)
ap.add_argument("--num-queries", type=int, default=400)
ap.add_argument("--num-propagated", type=int, default=128)
ap.add_argument("--memory-frames", type=int, default=4)
ap.add_argument("--layers", type=int, default=6)
ap.add_argument("--dn-groups", type=int, default=3)
ap.add_argument("--walker-weight", type=float, default=5.0)
ap.add_argument("--val-every", type=int, default=2000)
ap.add_argument("--val-samples", type=int, default=800, help="validation clips")
ap.add_argument("--log-every", type=int, default=50)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--holdout-fold", default=None, help="K/N: train without the routes of fold K")
ap.add_argument("--resume", default=None, help="checkpoint to continue from (model + optimizer + step)")
return ap.parse_args()
def build_model(args):
return StreamPETR(init=args.init, num_queries=args.num_queries, num_propagated=args.num_propagated,
memory_frames=args.memory_frames, layers=args.layers, dn_groups=args.dn_groups,
freeze_backbone=args.freeze_backbone)
@torch.no_grad()
def validate(model, val_set, device, rank, world, num_clips, score_threshold=0.2):
"""Detection metrics over frames 1.. of evenly spaced validation clips (frame 0 has an empty memory)."""
model.eval()
metrics = DetectionMetrics()
first = DetectionMetrics()
idx = np.linspace(0, len(val_set) - 1, num=min(len(val_set), num_clips), dtype=np.int64)[rank::world]
loader = DataLoader(Subset(val_set, idx.tolist()), batch_size=4, num_workers=6)
order = iter(idx.tolist())
for batch in loader:
batch = to_device(batch, device)
b, t_len = batch["image"].shape[:2]
clip_ids = [next(order) for _ in range(b)]
model.reset_memory()
for t in range(t_len):
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model(batch["image"][:, t], batch["pose"][:, t], batch["time"][:, t])
for i, det in enumerate(decode_stream(out, score_threshold)):
(first if t == 0 else metrics).add(val_set.gt_rows(clip_ids[i], t), det)
gathered = [None] * world
dist.all_gather_object(gathered, [(m.frames, m.gt, m.fp, m.errors) for m in (metrics, first)])
model.reset_memory()
model.train()
if rank != 0:
return None
totals = []
for j in range(2):
total = DetectionMetrics()
for parts in gathered:
frames, gt, fp, errors = parts[j]
total.frames += frames
total.gt += gt
total.errors += errors
for t in total.fp:
total.fp[t] += fp[t]
totals.append(total.summary())
summary = totals[0]
summary["first_frame"] = totals[1]
return summary
def main():
args = parse_args()
dist.init_process_group("nccl")
rank, world = dist.get_rank(), dist.get_world_size()
local_rank = int(os.environ.get("LOCAL_RANK", 0))
torch.cuda.set_device(local_rank)
device = torch.device("cuda", local_rank)
torch.manual_seed(args.seed + rank)
out_dir = Path(args.out)
if rank == 0:
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "args.json").write_text(json.dumps(vars(args), indent=2))
route_filter = None
if args.holdout_fold:
fold, num_folds = (int(v) for v in args.holdout_fold.split("/"))
route_filter = lambda rel: route_fold(rel, num_folds) != fold # noqa: E731
train_set = DetectionClipDataset(split="train", clip_len=args.clip_len, route_filter=route_filter)
val_set = DetectionClipDataset(split="val", clip_len=args.val_clip_len, clip_stride=args.val_clip_len)
if rank == 0:
print(f"train {len(train_set)} clips / {len(train_set.routes)} routes, "
f"val {len(val_set)} clips / {len(val_set.routes)} routes", flush=True)
if args.walker_weight != 1.0:
sampler = DistributedWeightedSampler(train_set.sample_weights(args.walker_weight, 1.0),
len(train_set) // world, args.seed, rank)
else:
sampler = DistributedSampler(train_set, shuffle=True, seed=args.seed, drop_last=True)
loader = DataLoader(train_set, batch_size=args.batch, sampler=sampler, num_workers=args.workers,
pin_memory=True, drop_last=True, persistent_workers=True, prefetch_factor=4)
model = build_model(args).to(device)
groups = [
dict(params=[p for n, p in model.named_parameters() if p.requires_grad and n.startswith("backbone.")],
lr=args.backbone_lr),
dict(params=[p for n, p in model.named_parameters() if p.requires_grad and not n.startswith("backbone.")],
lr=args.lr),
]
groups = [g for g in groups if g["params"]]
optimizer = torch.optim.AdamW(groups, weight_decay=args.weight_decay, betas=(0.9, 0.999))
base_lrs = [g["lr"] for g in groups]
step = 0
if args.resume:
ckpt = torch.load(args.resume, map_location="cpu", weights_only=False)
model.load_state_dict(ckpt["model"])
if "optimizer" in ckpt:
optimizer.load_state_dict(ckpt["optimizer"])
step = int(ckpt.get("step", 0))
# broadcast_buffers=False: with several forwards per backward, DDP's per-forward buffer broadcast would
# overwrite the BatchNorm running statistics the earlier frames' graphs still reference
ddp = DistributedDataParallel(model, device_ids=[local_rank], find_unused_parameters=False,
broadcast_buffers=False)
epoch, t0 = step // max(len(loader), 1), time.time()
running = {}
log = open(out_dir / "log.jsonl", "a") if rank == 0 else None
while step < args.steps:
sampler.set_epoch(epoch)
for batch in loader:
if step >= args.steps:
break
scale = min(1.0, (step + 1) / args.warmup) * 0.5 * (1 + math.cos(math.pi * min(1.0, step / args.steps)))
for g, lr in zip(optimizer.param_groups, base_lrs):
g["lr"] = lr * max(scale, 0.02)
batch = to_device(batch, device)
t_len = batch["image"].shape[1]
model.reset_memory()
total = None
frame_losses = {}
for t in range(t_len):
with torch.autocast("cuda", dtype=torch.bfloat16):
out = ddp(batch["image"][:, t], batch["pose"][:, t], batch["time"][:, t],
batch["rows"][:, t], batch["count"][:, t])
losses = stream_petr_loss(out, batch["rows"][:, t], batch["count"][:, t])
total = losses["total"] if total is None else total + losses["total"]
for k, v in losses.items():
frame_losses[k] = frame_losses.get(k, 0.0) + float(v.detach()) / t_len
total = total / t_len
optimizer.zero_grad(set_to_none=True)
total.backward()
gnorm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
optimizer.step()
model.reset_memory()
step += 1
for k, v in frame_losses.items():
running[k] = running.get(k, 0.0) + v
running["gnorm"] = running.get("gnorm", 0.0) + float(gnorm)
if step % args.log_every == 0 and rank == 0:
rec = {k: v / args.log_every for k, v in running.items()}
rec.update(step=step, epoch=epoch, lr=optimizer.param_groups[-1]["lr"],
clips_per_s=args.log_every * args.batch * world / (time.time() - t0))
print(json.dumps({k: float(f"{v:.4g}") if isinstance(v, float) else v for k, v in rec.items()}),
flush=True)
log.write(json.dumps(rec) + "\n")
log.flush()
running, t0 = {}, time.time()
if step % args.val_every == 0 or step == args.steps:
summary = validate(model, val_set, device, rank, world, args.val_samples)
if rank == 0:
print(f"=== validation @ step {step} (frames with memory)\n{format_summary(summary)}", flush=True)
print(f"--- first frames (empty memory)\n{format_summary(summary['first_frame'])}", flush=True)
(out_dir / f"val_{step:06d}.json").write_text(json.dumps(summary, indent=1))
torch.save(dict(model=model.state_dict(), optimizer=optimizer.state_dict(), step=step,
args=vars(args)), out_dir / "last.pt")
t0 = time.time()
epoch += 1
dist.destroy_process_group()
if __name__ == "__main__":
main()