File size: 6,824 Bytes
58a3849 | 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 | """Training script: 3D ResNet-101 on air-writing videos.
- model selection uses the VALIDATION set only (macro-F1); the test set is never touched here
- resumable (last.pt), best checkpoint (best.pt), AMP, gradient accumulation, cosine LR
"""
import argparse
import json
import math
import os
import random
import time
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import f1_score
from torch.utils.data import DataLoader
from tqdm import tqdm
from airwriting_common import AirDataset, build_model, class_names, collect_logits
def set_seed(s):
random.seed(s)
np.random.seed(s)
torch.manual_seed(s)
torch.cuda.manual_seed_all(s)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--train-csv", required=True)
ap.add_argument("--val-csv", required=True)
ap.add_argument("--video-dir", required=True)
ap.add_argument("--out-dir", default="runs/exp1")
ap.add_argument("--depth", type=int, default=101)
ap.add_argument("--frames", type=int, default=16)
ap.add_argument("--size", type=int, default=224)
ap.add_argument("--epochs", type=int, default=30)
ap.add_argument("--batch-size", type=int, default=4)
ap.add_argument("--accum-steps", type=int, default=4, help="effective batch = batch-size * accum-steps")
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--weight-decay", type=float, default=1e-2)
ap.add_argument("--label-smoothing", type=float, default=0.1)
ap.add_argument("--warmup-epochs", type=float, default=1.0)
ap.add_argument("--patience", type=int, default=6, help="early stop after N epochs without val F1 gain")
ap.add_argument("--num-workers", type=int, default=4)
ap.add_argument("--separate-contrast", action="store_true", help="38 classes instead of 37")
ap.add_argument("--max-train-samples", type=int, default=None, help="smoke test")
ap.add_argument("--max-val-samples", type=int, default=None)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--no-resume", action="store_true")
a = ap.parse_args()
set_seed(a.seed)
os.makedirs(a.out_dir, exist_ok=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
use_amp = device.type == "cuda"
names = class_names(a.separate_contrast)
print(f"device={device} amp={use_amp} classes={len(names)} frames={a.frames} size={a.size}")
tr = AirDataset(a.train_csv, a.video_dir, a.frames, a.size, True, a.separate_contrast,
"resample", a.max_train_samples)
va = AirDataset(a.val_csv, a.video_dir, a.frames, a.size, False, a.separate_contrast,
"raise", a.max_val_samples)
kw = dict(num_workers=a.num_workers, pin_memory=device.type == "cuda",
persistent_workers=a.num_workers > 0)
tl = DataLoader(tr, batch_size=a.batch_size, shuffle=True, drop_last=True, **kw)
vl = DataLoader(va, batch_size=a.batch_size, shuffle=False, **kw)
model = build_model(len(names), a.depth, a.frames, a.size).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=a.weight_decay)
steps_per_epoch = math.ceil(len(tl) / a.accum_steps)
total, warm = steps_per_epoch * a.epochs, int(steps_per_epoch * a.warmup_epochs)
lr_fn = lambda s: min(1.0, (s + 1) / max(1, warm)) * max(0.01, 0.5 * (1 + math.cos(math.pi * min(1.0, s / total))))
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_fn)
scaler = torch.amp.GradScaler("cuda", enabled=use_amp) if hasattr(torch, "amp") and hasattr(torch.amp, "GradScaler") \
else torch.cuda.amp.GradScaler(enabled=use_amp)
crit = nn.CrossEntropyLoss(label_smoothing=a.label_smoothing)
cfg = dict(depth=a.depth, frames=a.frames, size=a.size, separate_contrast=a.separate_contrast,
classes=names, args=vars(a))
json.dump(cfg, open(os.path.join(a.out_dir, "config.json"), "w"), indent=2)
start, best, bad, hist = 0, -1.0, 0, []
last = os.path.join(a.out_dir, "last.pt")
if os.path.exists(last) and not a.no_resume:
ck = torch.load(last, map_location=device)
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]); sched.load_state_dict(ck["sched"])
scaler.load_state_dict(ck["scaler"])
start, best, bad, hist = ck["epoch"], ck["best"], ck["bad"], ck["hist"]
print(f"Resumed at epoch {start} (best val macro-F1 {best:.4f})")
for epoch in range(start, a.epochs):
model.train()
opt.zero_grad(set_to_none=True)
run_loss, correct, seen, t0 = 0.0, 0, 0, time.time()
for i, (x, y) in enumerate(tqdm(tl, desc=f"epoch {epoch + 1}/{a.epochs}")):
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=use_amp):
out = model(x)
loss = crit(out, y)
scaler.scale(loss / a.accum_steps).backward()
if (i + 1) % a.accum_steps == 0 or (i + 1) == len(tl):
scaler.unscale_(opt)
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt); scaler.update()
opt.zero_grad(set_to_none=True)
sched.step()
run_loss += loss.item() * y.size(0)
correct += (out.argmax(1) == y).sum().item()
seen += y.size(0)
logits, labels = collect_logits(model, vl, device, use_amp)
pred = logits.argmax(1)
present = sorted(set(labels.tolist()))
val_acc = float((pred == labels).mean())
val_f1 = float(f1_score(labels, pred, labels=present, average="macro", zero_division=0))
row = dict(epoch=epoch + 1, train_loss=run_loss / seen, train_acc=correct / seen,
val_acc=val_acc, val_macro_f1=val_f1, lr=sched.get_last_lr()[0],
minutes=(time.time() - t0) / 60)
hist.append(row)
print(json.dumps(row))
if val_f1 > best:
best, bad = val_f1, 0
torch.save(dict(model=model.state_dict(), config=cfg, epoch=epoch + 1, val_macro_f1=val_f1),
os.path.join(a.out_dir, "best.pt"))
else:
bad += 1
torch.save(dict(model=model.state_dict(), opt=opt.state_dict(), sched=sched.state_dict(),
scaler=scaler.state_dict(), epoch=epoch + 1, best=best, bad=bad, hist=hist), last)
json.dump(hist, open(os.path.join(a.out_dir, "history.json"), "w"), indent=2)
if bad >= a.patience:
print(f"Early stop: no val macro-F1 gain for {a.patience} epochs.")
break
print(f"Done. Best val macro-F1 = {best:.4f}. Now run test.py on {os.path.join(a.out_dir, 'best.pt')}")
if __name__ == "__main__":
main()
|