File size: 15,868 Bytes
ce7fc72 | 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 | #!/usr/bin/env python3
# Copyright (c) 2026 Eoin Jordan
# SPDX-License-Identifier: Apache-2.0
"""Train PoseMicro on the COCO person crops of train/pose_data.py.
Each step takes a batch of 112 x 112 crops, turns, scales, shifts and mirrors
them into 96 x 96 pictures, and asks the network for the heat and offset maps
described in pose_model.py. The weights that are kept are a running average
of the trained ones, which is steadier than the last step of a short run.
Scores, on the held-out val2017 crops (one person a crop, framed by the
person's own box, so this is not COCO's keypoint AP, which also has to find
the people):
PCK@0.2, PCK@0.1 labelled keypoints placed within 20% / 10% of the longer
side of the person's box
OKS COCO's object keypoint similarity, averaged over the
crops, and the share of crops that reach 0.5
python train/pose_data.py --split val && python train/pose_data.py --split train
python train/train_pose.py --epochs 60 # the full run
python train/train_pose.py --minutes 60 # as far as an hour goes
python train/train_pose.py --resume # carry on from train/out/pose_micro_last.pt
"""
import argparse
import copy
import json
import math
import pathlib
import sys
import time
import numpy as np
import torch
import torch.nn.functional as F
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from pose_model import (GRID, MIRROR, NUM_KEYPOINTS, OFFSET_SPAN, SIDE, STRIDE, KEYPOINTS, # noqa: E402
PoseMicro, decode, multiply_adds)
REPO = pathlib.Path(__file__).resolve().parents[1]
DATA = REPO / "train" / "data"
OUT = REPO / "train" / "out"
STATE = OUT / "pose_micro.pt"
LAST = OUT / "pose_micro_last.pt"
LOG = OUT / "pose_micro_train.json"
CROP = 112 # side of the stored crops (pose_data.py)
MARGIN = 1.25 # crop side over the longer side of the person's box
SIGMA = 0.7 # of the heat target, in cells
NHWC = torch.channels_last
# COCO's per-keypoint constants for the object keypoint similarity.
OKS_SIGMAS = np.array([.026, .025, .025, .035, .035, .079, .079, .072, .072, .062, .062,
.107, .107, .087, .087, .089, .089], np.float32)
def load(split: str, limit: int = 0, data: pathlib.Path = DATA):
"""(crops uint8 memmap [n][112][112][3], keypoints float32 [n][17][3], meta list)."""
meta_path = data / f"pose_{split}_meta.json"
if not meta_path.exists():
sys.exit(f"{meta_path} not found: run train/pose_data.py --split {split} first")
meta = json.loads(meta_path.read_text())
n = meta["count"]
crops = np.memmap(data / f"pose_{split}.u8", np.uint8, "r", shape=(n, CROP, CROP, 3))
kpts = np.load(data / f"pose_{split}_kpts.npy")
if limit and limit < n:
crops, kpts, meta["crops"] = crops[:limit], kpts[:limit], meta["crops"][:limit]
return crops, kpts, meta["crops"]
def views(crops_u8: np.ndarray, kpts: np.ndarray, train: bool, gen: torch.Generator | None = None):
"""A batch of crops as the network sees them.
Returns (pictures float [b][3][96][96] in 0..1, keypoints [b][17][3]: x and y in
picture pixels, and v). In training the crop is turned up to 30 degrees, scaled
by 0.75 to 1.3, shifted by up to 5% and mirrored half the time; otherwise it
is only reduced from 112 to 96.
"""
b = len(crops_u8)
src = torch.from_numpy(np.array(crops_u8)).permute(0, 3, 1, 2).float() / 255.0 # a copy: the store is read-only
k = torch.from_numpy(np.ascontiguousarray(kpts)).clone()
if train:
def rand(lo, hi):
return lo + (hi - lo) * torch.rand(b, generator=gen)
zoom = torch.exp(rand(math.log(0.75), math.log(1.3)))
angle = rand(-math.pi / 6, math.pi / 6)
shift = torch.stack([rand(-0.1, 0.1), rand(-0.1, 0.1)], dim=1)
mirror = torch.rand(b, generator=gen) < 0.5
else:
zoom, angle = torch.ones(b), torch.zeros(b)
shift, mirror = torch.zeros(b, 2), torch.zeros(b, dtype=torch.bool)
# Where each picture pixel comes from in the crop, both in -1..1: s = M p + shift.
cos, sin = torch.cos(angle) / zoom, torch.sin(angle) / zoom
m = torch.stack([torch.stack([cos, -sin], dim=1), torch.stack([sin, cos], dim=1)], dim=1)
m[:, :, 0] = torch.where(mirror[:, None], -m[:, :, 0], m[:, :, 0])
theta = torch.cat([m, shift[:, :, None]], dim=2)
grid = F.affine_grid(theta, (b, 3, SIDE, SIDE), align_corners=False)
x = F.grid_sample(src, grid, mode="bilinear", padding_mode="zeros", align_corners=False)
# The keypoints go the other way: p = M^-1 (s - shift).
s = k[:, :, :2] / CROP * 2 - 1
p = torch.einsum("bij,bkj->bki", torch.linalg.inv(m), s - shift[:, None, :])
k[:, :, :2] = (p + 1) / 2 * SIDE
if mirror.any():
k[mirror] = k[mirror][:, list(MIRROR)]
k[k[:, :, 2] == 0, :2] = 0
if train: # light and colour: a camera on a board is not a photographer
gain = rand(0.7, 1.3)[:, None, None, None] * (0.9 + 0.2 * torch.rand(b, 3, 1, 1, generator=gen))
contrast = rand(0.75, 1.25)[:, None, None, None]
mean = x.mean(dim=(1, 2, 3), keepdim=True)
x = ((x - mean) * contrast + mean) * gain
grey = torch.rand(b, generator=gen) < 0.1
if grey.any():
x[grey] = x[grey].mean(dim=1, keepdim=True).expand(-1, 3, -1, -1)
x = x.clamp_(0, 1)
return x, k
def targets(k: torch.Tensor):
"""What the network should answer for keypoints `k` ([b][17][3] in picture pixels).
Returns (heat [b][17][12][12], offsets [b][34][12][12], heat mask [b][17][1][1],
offset mask [b][17][12][12]). An unlabelled keypoint is left out of the loss;
a labelled one that the view has pushed out of the picture has heat 0 everywhere.
"""
b = len(k)
labelled = k[:, :, 2] > 0
gx, gy = k[:, :, 0] / STRIDE, k[:, :, 1] / STRIDE # in cells
inside = labelled & (gx >= 0) & (gx < GRID) & (gy >= 0) & (gy < GRID)
centre = torch.arange(GRID, dtype=torch.float32) + 0.5
cx = centre.view(1, 1, 1, GRID)
cy = centre.view(1, 1, GRID, 1)
px = (torch.floor(gx) + 0.5).view(b, -1, 1, 1) # centre of the keypoint's cell
py = (torch.floor(gy) + 0.5).view(b, -1, 1, 1)
heat = torch.exp(-((cx - px) ** 2 + (cy - py) ** 2) / (2 * SIGMA ** 2)) * inside.view(b, -1, 1, 1)
dx = (gx.view(b, -1, 1, 1) - cx).expand(-1, -1, GRID, -1) / OFFSET_SPAN
dy = (gy.view(b, -1, 1, 1) - cy).expand(-1, -1, -1, GRID) / OFFSET_SPAN
return heat, torch.cat([dx, dy], dim=1), labelled.view(b, -1, 1, 1).float(), (heat >= 0.3).float()
class Average:
"""A running average of a model's weights and batch-norm statistics."""
def __init__(self, model: torch.nn.Module, decay: float = 0.998) -> None:
self.module = copy.deepcopy(model).eval()
self.decay = decay
self.updates = 0
for q in self.module.parameters():
q.requires_grad_(False)
@torch.no_grad()
def update(self, model: torch.nn.Module) -> None:
self.updates += 1
d = min(self.decay, (1 + self.updates) / (10 + self.updates)) # follow closely at first
new = model.state_dict()
for name, value in self.module.state_dict().items():
if value.dtype.is_floating_point:
value.mul_(d).add_(new[name].detach(), alpha=1 - d)
else:
value.copy_(new[name])
def loss_of(out: torch.Tensor, k: torch.Tensor):
heat, offsets, heat_mask, offset_mask = targets(k)
n = NUM_KEYPOINTS
# The one cell in 144 that holds the keypoint weighs nine times a background cell.
heat_loss = ((out[:, :n] - heat) ** 2 * (1 + 8 * heat) * heat_mask).sum() / (heat_mask.sum() * GRID * GRID).clamp(min=1)
both = torch.cat([offset_mask, offset_mask], dim=1)
offset_loss = (F.smooth_l1_loss(out[:, n:], offsets, beta=0.05, reduction="none") * both).sum() / both.sum().clamp(min=1)
return 4 * heat_loss + offset_loss, heat_loss.item(), offset_loss.item()
@torch.no_grad()
def predict(model, crops_u8: np.ndarray, batch: int = 256, nhwc: bool = True) -> np.ndarray:
"""Network output [n][51][12][12] for crops framed as in scoring."""
out = []
for i in range(0, len(crops_u8), batch):
x, _ = views(crops_u8[i:i + batch], np.zeros((len(crops_u8[i:i + batch]), NUM_KEYPOINTS, 3), np.float32), False)
out.append(model(x.to(memory_format=NHWC) if nhwc else x).float().numpy())
return np.concatenate(out)
def score(outputs: np.ndarray, kpts: np.ndarray, meta: list) -> dict:
"""PCK and OKS of network outputs against the crops' keypoints (see the module text)."""
n = len(outputs)
pred = np.stack([decode(o) for o in outputs]) # [n][17][3], x y as fractions
truth = kpts[:n, :, :2] * (SIDE / CROP)
labelled = kpts[:n, :, 2] > 0
d = np.linalg.norm(pred[:, :, :2] * SIDE - truth, axis=2) # picture pixels
box = SIDE / MARGIN # longer side of the person's box, in picture pixels
scale = np.array([m["scale"] for m in meta[:n]], np.float32)
area = np.array([m["area"] for m in meta[:n]], np.float32)
d_original = d * (CROP / SIDE) / scale[:, None] # pixels of the COCO picture
e = d_original ** 2 / (2 * area[:, None] * (2 * OKS_SIGMAS[None]) ** 2)
oks = (np.exp(-e) * labelled).sum(1) / labelled.sum(1).clip(min=1)
per = {name: float((d[:, j] <= 0.2 * box)[labelled[:, j]].mean()) for j, name in enumerate(KEYPOINTS)}
return {
"crops": int(n),
"pck_0.2": float((d <= 0.2 * box)[labelled].mean()),
"pck_0.1": float((d <= 0.1 * box)[labelled].mean()),
"oks": float(oks.mean()),
"oks_0.5": float((oks >= 0.5).mean()),
"mean_error_px": float(d[labelled].mean()),
"pck_0.2_by_keypoint": per,
}
def report(s: dict) -> str:
return (f"PCK@0.2 {100 * s['pck_0.2']:.1f}% PCK@0.1 {100 * s['pck_0.1']:.1f}% "
f"OKS {s['oks']:.3f} OKS>=0.5 {100 * s['oks_0.5']:.1f}% mean error {s['mean_error_px']:.1f} px of 96")
def main() -> None:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--epochs", type=float, default=60)
p.add_argument("--minutes", type=float, default=0, help="stop after this long; the learning rate runs down in that time")
p.add_argument("--batch", type=int, default=128)
p.add_argument("--lr", type=float, default=4e-3)
p.add_argument("--width", type=int, default=32)
p.add_argument("--rounds", type=int, default=6)
p.add_argument("--limit", type=int, default=0, help="use only this many training crops (smoke test)")
p.add_argument("--val-limit", type=int, default=0)
p.add_argument("--threads", type=int, default=0)
p.add_argument("--seed", type=int, default=0)
p.add_argument("--resume", action="store_true", help="carry on from the last checkpoint")
p.add_argument("--state-dict", type=pathlib.Path, default=STATE)
p.add_argument("--data", type=pathlib.Path, default=DATA, help="folder written by pose_data.py")
args = p.parse_args()
if args.threads:
torch.set_num_threads(args.threads)
torch.manual_seed(args.seed)
gen = torch.Generator().manual_seed(args.seed)
rng = np.random.default_rng(args.seed)
train_x, train_k, _ = load("train", args.limit, args.data)
val_x, val_k, val_meta = load("val", args.val_limit, args.data)
model = PoseMicro(args.width, args.rounds).to(memory_format=NHWC)
average = Average(model)
decay = [q for n_, q in model.named_parameters() if q.ndim > 1]
plain = [q for n_, q in model.named_parameters() if q.ndim <= 1]
opt = torch.optim.AdamW([{"params": decay, "weight_decay": 1e-4}, {"params": plain, "weight_decay": 0}], lr=args.lr)
steps_per_epoch = len(train_x) // args.batch
total_steps = max(1, int(args.epochs * steps_per_epoch))
step, history, spent = 0, [], 0.0
if args.resume and LAST.exists():
saved = torch.load(LAST, map_location="cpu")
model.load_state_dict(saved["model"])
average.module.load_state_dict(saved["average"])
average.updates = saved["step"]
opt.load_state_dict(saved["opt"])
step, history, spent = saved["step"], saved["history"], saved["seconds"]
print(f"resumed at step {step} of {total_steps} ({spent / 60:.0f} min so far)")
print(f"PoseMicro width {args.width}, rounds {args.rounds}: "
f"{sum(q.numel() for q in model.parameters()):,} parameters, {multiply_adds(model) / 1e6:.2f}M multiply-adds")
print(f"{len(train_x)} training crops, {len(val_x)} validation crops, {steps_per_epoch} steps an epoch")
def progress() -> float:
"""How far through the run, 0..1: by steps, or by the clock when --minutes is given."""
by_steps = step / total_steps
return max(by_steps, (spent + time.time() - started) / (60 * args.minutes)) if args.minutes else by_steps
def save(final_scores=None) -> None:
OUT.mkdir(parents=True, exist_ok=True)
torch.save({"model": model.state_dict(), "average": average.module.state_dict(), "opt": opt.state_dict(),
"step": step, "history": history, "seconds": spent + time.time() - started}, LAST)
torch.save(average.module.state_dict(), args.state_dict)
LOG.write_text(json.dumps({
"width": args.width, "rounds": args.rounds, "batch": args.batch, "lr": args.lr,
"training_crops": len(train_x), "steps": step, "epochs": step / steps_per_epoch,
"minutes": (spent + time.time() - started) / 60, "threads": torch.get_num_threads(),
"history": history, "final": final_scores,
}, indent=1))
started = time.time()
warm = 300
running, seen, shown = [0.0, 0.0, 0.0], 0, time.time()
order = rng.permutation(len(train_x))
model.train()
while progress() < 1.0:
at = (step % steps_per_epoch) * args.batch
if at == 0 and step:
order = rng.permutation(len(train_x))
idx = np.sort(order[at:at + args.batch])
x, k = views(train_x[idx], train_k[idx], True, gen)
for g in opt.param_groups:
g["lr"] = args.lr * min(1.0, (step + 1) / warm) * (0.02 + 0.98 * 0.5 * (1 + math.cos(math.pi * min(progress(), 1.0))))
out = model(x.to(memory_format=NHWC))
loss, heat_loss, offset_loss = loss_of(out, k)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
average.update(model)
step += 1
running = [running[0] + loss.item(), running[1] + heat_loss, running[2] + offset_loss]
seen += 1
if time.time() - shown > 60:
took = time.time() - shown
print(f" step {step} ({step / steps_per_epoch:.2f} epochs, {100 * progress():.0f}%): loss {running[0] / seen:.4f} "
f"(heat {running[1] / seen:.5f}, offset {running[2] / seen:.4f}), {seen * args.batch / took:.0f} crops/s", flush=True)
running, seen, shown = [0.0, 0.0, 0.0], 0, time.time()
if step % steps_per_epoch == 0 or progress() >= 1.0:
average.module.eval()
s = score(predict(average.module, val_x), val_k, val_meta)
history.append({"step": step, "epoch": step / steps_per_epoch,
"minutes": (spent + time.time() - started) / 60, **{k_: v for k_, v in s.items() if k_ != "pck_0.2_by_keypoint"}})
print(f"epoch {step / steps_per_epoch:.2f} ({history[-1]['minutes']:.0f} min): {report(s)}", flush=True)
save(s if progress() >= 1.0 else None)
shown = time.time()
print(f"wrote {args.state_dict}")
if __name__ == "__main__":
main()
|