Spaces:
Sleeping
Sleeping
File size: 5,816 Bytes
22938ed | 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 | """Train AutoSpriteNet on procedurally generated characters.
Every step draws fresh characters, hides a random subset of their poses, and asks the
network to reconstruct the hidden frames from the visible ones.
python train.py --steps 20000 --out weights/autosprite.pt
"""
from __future__ import annotations
import argparse
import math
import time
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from torch.utils.data import DataLoader, IterableDataset, get_worker_info
from autosprite import NUM_POSES
from autosprite.features import encode, labels_for
from autosprite.model import AutoSpriteNet
from autosprite.synth import random_sprite_set
IGNORE = -100
def sample_visible(rng: np.random.Generator) -> np.ndarray:
"""Which poses the user "provided"; skewed toward very few frames, usually including idle."""
count = int(rng.choice([1, 2, 3, 4], p=[0.4, 0.3, 0.18, 0.12]))
visible = np.zeros(NUM_POSES, bool)
if rng.random() < 0.7:
visible[0] = True
count -= 1
hidden = np.flatnonzero(~visible)
visible[rng.choice(hidden, size=count, replace=False)] = True
return visible
def make_example(rng: np.random.Generator) -> dict[str, np.ndarray]:
frames = random_sprite_set(rng)
visible = sample_visible(rng)
enc = encode([f if v else None for f, v in zip(frames, visible)])
labels = np.stack([labels_for(f, enc) for f in frames])
labels[visible] = IGNORE
return {
"x": enc.x,
"palmask": enc.palmask,
"palrgb": enc.palrgb,
"palvalid": enc.palvalid,
"labels": labels,
}
class SyntheticSprites(IterableDataset):
def __init__(self, seed: int):
self.seed = seed
def __iter__(self):
info = get_worker_info()
worker = info.id if info else 0
rng = np.random.default_rng([self.seed, worker, int(time.time() * 1000) % 2**31])
while True:
yield make_example(rng)
def fixed_batch(seed: int, n: int) -> dict[str, torch.Tensor]:
rng = np.random.default_rng(seed)
items = [make_example(rng) for _ in range(n)]
return {k: torch.from_numpy(np.stack([it[k] for it in items])) for k in items[0]}
def loss_and_metrics(model: AutoSpriteNet, batch: dict[str, torch.Tensor]):
logits = model(batch["x"], batch["palmask"], batch["palrgb"], batch["palvalid"])
labels = batch["labels"]
b, k, c, h, w = logits.shape
flat = logits.permute(0, 1, 3, 4, 2).reshape(-1, c)
target = labels.reshape(-1)
loss = F.cross_entropy(flat, target, ignore_index=IGNORE)
with torch.no_grad():
pred = flat.argmax(-1)
scored = target != IGNORE
fg = scored & (target > 0)
acc_fg = (pred[fg] == target[fg]).float().mean()
union = scored & ((target > 0) | (pred > 0))
acc_union = (pred[union] == target[union]).float().mean()
return loss, {"acc_fg": acc_fg.item(), "acc_union": acc_union.item()}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--steps", type=int, default=20000)
parser.add_argument("--batch", type=int, default=128)
parser.add_argument("--lr", type=float, default=2e-3)
parser.add_argument("--width", type=int, default=48)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--out", type=Path, default=Path("weights/autosprite.pt"))
parser.add_argument("--resume", type=Path)
args = parser.parse_args()
device = torch.device("mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu")
model = AutoSpriteNet(width=args.width).to(device)
if args.resume:
model.load_state_dict(torch.load(args.resume, map_location=device)["model"])
print(f"device={device} params={sum(p.numel() for p in model.parameters()) / 1e6:.2f}M", flush=True)
opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4)
warmup = 500
def lr_at(step: int) -> float:
if step < warmup:
return args.lr * (step + 1) / warmup
t = (step - warmup) / max(1, args.steps - warmup)
return args.lr * (0.02 + 0.98 * 0.5 * (1 + math.cos(math.pi * t)))
loader = DataLoader(
SyntheticSprites(seed=0),
batch_size=args.batch,
num_workers=args.workers,
persistent_workers=args.workers > 0,
prefetch_factor=4 if args.workers else None,
)
val = {k: v.to(device) for k, v in fixed_batch(12345, 512).items()}
args.out.parent.mkdir(parents=True, exist_ok=True)
start = time.time()
model.train()
for step, batch in enumerate(loader):
if step >= args.steps:
break
for group in opt.param_groups:
group["lr"] = lr_at(step)
batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
loss, metrics = loss_and_metrics(model, batch)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 250 == 0 or step == args.steps - 1:
model.eval()
with torch.no_grad():
val_loss, val_metrics = loss_and_metrics(model, val)
model.train()
print(
f"step {step:6d} loss {loss.item():.4f} fg {metrics['acc_fg']:.3f} | "
f"val loss {val_loss.item():.4f} fg {val_metrics['acc_fg']:.3f} "
f"union {val_metrics['acc_union']:.3f} | {time.time() - start:.0f}s",
flush=True,
)
if step % 2000 == 0 or step == args.steps - 1:
torch.save({"model": model.state_dict(), "width": args.width, "step": step}, args.out)
print("done", flush=True)
if __name__ == "__main__":
main()
|