f7a262ac9a
Build & push images / images (push) Successful in 6m31s
apps/trainer (parking-trainer): inspect / train / evaluate / publish. Reads the wash collector's SQLite + crops read-only off its volume; time split (validation = newest slice); thin classes dropped; damped class weights; `features` mode (frozen ImageNet backbone, on-disk feature cache, seconds to retrain) and `finetune` mode (light augmentation). CPU-only torch from PyTorch's wheel index. ONNX export checked against the torch model; NO model file below the validation floor (exit 3, report still written); exit 2 = not enough labels. `evaluate` scores a shipped model on labels reviewed after training + the unlabelled pile; `publish` PUTs a version folder to a Gitea generic package. Light core deps; the `train` extra is heavy — CI syncs without it, torch tests skip. apps/vision: BodyTypeClassifier (bodytype.onnx + sidecar = the preprocessing contract: crop margin, input size, RGB 0-255, normalisation inside the graph) and RefinedVehicleDetector over YOLOX — refines only `car` or a class the classifier trained on, min-confidence, `detector_class` on the result; path set but no file = phase B off without an error; a broken file is a health detail. models/bodytype.version (tracked, empty) pins the published version the Dockerfile fetches at build (BuildKit secret; a pin that cannot be fetched fails the build). Verified: a trainer model gives identical probabilities inside the vision service; both images built and smoke-tested. Delivery: parking-trainer image in build-images.yml, the `trainer` compose profile on the collector stack (CPU, read-only data, TRAINER_OUT), commented TRAINER_OUT/PUBLISH_TOKEN in the wash-collector stack, .dockerignore for both Python contexts, trainer deps synced in CI. Wiki: bodytype-classifier-training rewritten as built (+ one fleet model not per site, secrets/access, where the crops live), opencv-anpr-service §Phase B, vision-review-outbox, vision-service-packaging, fleet-deployment-komodo, index, log. Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
306 lines
11 KiB
Python
306 lines
11 KiB
Python
"""The network and the two ways of training it. Imports torch — only `train` reaches here;
|
||
everything else in the package stays torch-free (the `train` extra is heavy).
|
||
|
||
Backbone: a small ImageNet-pretrained torchvision model (BSD-3, weights included), used as
|
||
a feature extractor; head: one linear layer over its pooled features.
|
||
|
||
- "features" mode: the backbone is FROZEN. Every crop goes through it once, the vectors
|
||
are cached on disk (keyed by item id), and only the head is trained — minutes for a few
|
||
thousand crops, seconds to retrain when new labels arrive. Expected to carry most of
|
||
the accuracy on frontal gate views.
|
||
- "finetune" mode: warm-starts the head the same way, then unfreezes everything and trains
|
||
end to end with light augmentation. Roughly an hour on four Xeon cores for a few
|
||
thousand crops with a mobile-sized backbone; the step when the cheap mode plateaus.
|
||
|
||
The exported ONNX graph takes raw RGB 0–255 float pixels and normalises INSIDE
|
||
(see preprocess.py), so the vision service cannot get the constants wrong.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from .data import Sample
|
||
from .preprocess import IMAGENET_MEAN, IMAGENET_STD, load_input
|
||
|
||
BACKBONES: dict[str, int] = {"resnet18": 512, "mobilenet_v3_small": 576, "efficientnet_b0": 1280}
|
||
|
||
|
||
def _torch() -> Any:
|
||
import torch
|
||
|
||
torch.set_num_threads(max(1, os.cpu_count() or 1))
|
||
return torch
|
||
|
||
|
||
def build_backbone(name: str, pretrained: bool = True) -> Any:
|
||
"""torchvision model with its classifier removed → pooled feature vector."""
|
||
torch = _torch()
|
||
import torchvision.models as tvm
|
||
|
||
if name not in BACKBONES:
|
||
raise ValueError(f"unknown backbone {name!r} (choose from {', '.join(BACKBONES)})")
|
||
if name == "resnet18":
|
||
m = tvm.resnet18(weights=tvm.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None)
|
||
m.fc = torch.nn.Identity()
|
||
elif name == "mobilenet_v3_small":
|
||
m = tvm.mobilenet_v3_small(
|
||
weights=tvm.MobileNet_V3_Small_Weights.IMAGENET1K_V1 if pretrained else None
|
||
)
|
||
m.classifier = torch.nn.Identity()
|
||
else:
|
||
m = tvm.efficientnet_b0(weights=tvm.EfficientNet_B0_Weights.IMAGENET1K_V1 if pretrained else None)
|
||
m.classifier = torch.nn.Identity()
|
||
return m
|
||
|
||
|
||
class Classifier: # a factory, not a Module subclass at import time (torch is lazy)
|
||
@staticmethod
|
||
def make(backbone: Any, head: Any) -> Any:
|
||
torch = _torch()
|
||
|
||
class _Net(torch.nn.Module): # type: ignore[misc,name-defined]
|
||
def __init__(self) -> None:
|
||
super().__init__()
|
||
self.backbone = backbone
|
||
self.head = head
|
||
self.register_buffer("mean", torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1))
|
||
self.register_buffer("std", torch.tensor(IMAGENET_STD).view(1, 3, 1, 1))
|
||
|
||
def forward(self, x: Any) -> Any:
|
||
x = (x / 255.0 - self.mean) / self.std
|
||
return self.head(self.backbone(x))
|
||
|
||
return _Net()
|
||
|
||
|
||
# ----------------------------------------------------------------------------------
|
||
# Images in memory (uint8 — a few thousand 224² crops is a few hundred MB; float32 would
|
||
# be four times that)
|
||
# ----------------------------------------------------------------------------------
|
||
|
||
|
||
def load_images(samples: list[Sample], input_size: int) -> tuple[Any, list[Sample]]:
|
||
"""Decode + resize every crop once. Returns (uint8 [N,3,S,S], the samples that decoded)."""
|
||
import numpy as np
|
||
|
||
xs, kept = [], []
|
||
for s in samples:
|
||
x = load_input(s.path, input_size)
|
||
if x is None:
|
||
continue
|
||
xs.append(x.astype(np.uint8))
|
||
kept.append(s)
|
||
if not xs:
|
||
return np.zeros((0, 3, input_size, input_size), np.uint8), []
|
||
return np.stack(xs), kept
|
||
|
||
|
||
def _batches(n: int, batch: int) -> list[slice]:
|
||
return [slice(i, min(n, i + batch)) for i in range(0, n, batch)]
|
||
|
||
|
||
# ----------------------------------------------------------------------------------
|
||
# Feature extraction (+ on-disk cache) and the head
|
||
# ----------------------------------------------------------------------------------
|
||
|
||
|
||
@dataclass
|
||
class FeatureCache:
|
||
"""`<cache_dir>/features-<backbone>-<size>.npz`: item ids + vectors. Retraining the head
|
||
after new labels arrive only runs the backbone on the NEW crops."""
|
||
|
||
path: Path
|
||
|
||
def load(self) -> dict[str, Any]:
|
||
import numpy as np
|
||
|
||
if not self.path.exists():
|
||
return {}
|
||
z = np.load(self.path, allow_pickle=False)
|
||
return dict(zip(z["ids"].tolist(), z["feats"], strict=True))
|
||
|
||
def save(self, table: dict[str, Any]) -> None:
|
||
import numpy as np
|
||
|
||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||
ids = np.array(list(table), dtype=str)
|
||
feats = np.stack(list(table.values())) if table else np.zeros((0, 0), np.float32)
|
||
np.savez(self.path, ids=ids, feats=feats)
|
||
|
||
|
||
def extract_features(backbone: Any, x_u8: Any, batch: int = 64) -> Any:
|
||
"""Frozen forward pass → [N,D] float32 (normalisation applied here, as in the graph)."""
|
||
torch = _torch()
|
||
import numpy as np
|
||
|
||
net = Classifier.make(backbone, torch.nn.Identity()).eval()
|
||
out = []
|
||
with torch.no_grad():
|
||
for sl in _batches(len(x_u8), batch):
|
||
xb = torch.from_numpy(x_u8[sl]).float()
|
||
out.append(net(xb).numpy())
|
||
return np.concatenate(out, axis=0) if out else np.zeros((0, 0), np.float32)
|
||
|
||
|
||
def features_for(
|
||
backbone: Any, samples: list[Sample], x_u8: Any, cache: FeatureCache | None, batch: int = 64
|
||
) -> Any:
|
||
"""Feature vectors for `samples` (aligned with x_u8), from the cache where present."""
|
||
import numpy as np
|
||
|
||
table = cache.load() if cache else {}
|
||
todo = [i for i, s in enumerate(samples) if s.item not in table]
|
||
if todo:
|
||
fresh = extract_features(backbone, x_u8[todo], batch)
|
||
for i, f in zip(todo, fresh, strict=True):
|
||
table[samples[i].item] = f.astype(np.float32)
|
||
if cache:
|
||
cache.save(table)
|
||
return np.stack([table[s.item] for s in samples]) if samples else np.zeros((0, 0), np.float32)
|
||
|
||
|
||
def train_head(
|
||
feats: Any,
|
||
y: list[int],
|
||
n_classes: int,
|
||
weights: list[float],
|
||
epochs: int,
|
||
lr: float = 1e-3,
|
||
seed: int = 7,
|
||
) -> Any:
|
||
"""Multinomial logistic regression on cached features (full batch, Adam, weighted CE)."""
|
||
torch = _torch()
|
||
torch.manual_seed(seed)
|
||
f = torch.from_numpy(feats).float()
|
||
t = torch.tensor(y, dtype=torch.long)
|
||
head = torch.nn.Linear(f.shape[1], n_classes)
|
||
opt = torch.optim.Adam(head.parameters(), lr=lr, weight_decay=1e-4)
|
||
loss_fn = torch.nn.CrossEntropyLoss(weight=torch.tensor(weights, dtype=torch.float32))
|
||
head.train()
|
||
for _ in range(epochs):
|
||
opt.zero_grad()
|
||
loss = loss_fn(head(f), t)
|
||
loss.backward()
|
||
opt.step()
|
||
return head.eval()
|
||
|
||
|
||
# ----------------------------------------------------------------------------------
|
||
# Full fine-tune
|
||
# ----------------------------------------------------------------------------------
|
||
|
||
|
||
def _augment(xb: Any) -> Any:
|
||
"""Light, label-preserving augmentation on a float batch [B,3,S,S] (0–255): horizontal
|
||
flip (a gate view mirrored is still the same body type), a mild random zoom, and
|
||
brightness/contrast jitter (dusk, headlights, wet tarmac)."""
|
||
torch = _torch()
|
||
b, _, s, _ = xb.shape
|
||
flip = torch.rand(b) < 0.5
|
||
xb = torch.where(flip.view(b, 1, 1, 1), xb.flip(-1), xb)
|
||
# zoom: crop a random 85–100 % window and resize back
|
||
out = torch.empty_like(xb)
|
||
for i in range(b):
|
||
frac = float(torch.empty(1).uniform_(0.85, 1.0))
|
||
w = max(8, int(s * frac))
|
||
x0 = int(torch.randint(0, s - w + 1, (1,)))
|
||
y0 = int(torch.randint(0, s - w + 1, (1,)))
|
||
crop = xb[i : i + 1, :, y0 : y0 + w, x0 : x0 + w]
|
||
out[i : i + 1] = torch.nn.functional.interpolate(
|
||
crop, size=(s, s), mode="bilinear", align_corners=False
|
||
)
|
||
bright = torch.empty(b, 1, 1, 1).uniform_(-25, 25)
|
||
contrast = torch.empty(b, 1, 1, 1).uniform_(0.8, 1.2)
|
||
mean = out.mean(dim=(1, 2, 3), keepdim=True)
|
||
out = (out - mean) * contrast + mean + bright
|
||
return out.clamp_(0, 255)
|
||
|
||
|
||
def finetune(
|
||
model: Any,
|
||
x_u8: Any,
|
||
y: list[int],
|
||
weights: list[float],
|
||
epochs: int,
|
||
batch: int = 32,
|
||
lr: float = 1e-4,
|
||
seed: int = 7,
|
||
log: Any = None,
|
||
) -> Any:
|
||
torch = _torch()
|
||
import numpy as np
|
||
|
||
torch.manual_seed(seed)
|
||
rng = np.random.default_rng(seed)
|
||
t = torch.tensor(y, dtype=torch.long)
|
||
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)
|
||
steps = epochs * max(1, (len(y) + batch - 1) // batch)
|
||
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=max(1, steps), pct_start=0.15)
|
||
loss_fn = torch.nn.CrossEntropyLoss(weight=torch.tensor(weights, dtype=torch.float32))
|
||
for epoch in range(epochs):
|
||
model.train()
|
||
order = rng.permutation(len(y))
|
||
total = 0.0
|
||
for sl in _batches(len(y), batch):
|
||
idx = order[sl]
|
||
xb = _augment(torch.from_numpy(x_u8[idx]).float())
|
||
opt.zero_grad()
|
||
loss = loss_fn(model(xb), t[idx])
|
||
loss.backward()
|
||
opt.step()
|
||
sched.step()
|
||
total += float(loss.detach()) * len(idx)
|
||
if log:
|
||
log(f"epoch {epoch + 1}/{epochs} loss {total / max(1, len(y)):.4f}")
|
||
return model.eval()
|
||
|
||
|
||
def predict_logits(model: Any, x_u8: Any, batch: int = 64) -> Any:
|
||
torch = _torch()
|
||
import numpy as np
|
||
|
||
model.eval()
|
||
out = []
|
||
with torch.no_grad():
|
||
for sl in _batches(len(x_u8), batch):
|
||
out.append(model(torch.from_numpy(x_u8[sl]).float()).numpy())
|
||
return np.concatenate(out, axis=0) if out else np.zeros((0, 0), np.float32)
|
||
|
||
|
||
def export_onnx(model: Any, input_size: int, path: Path) -> None:
|
||
"""Export with the current (torch.export-based) exporter; fall back to the legacy
|
||
TorchScript one where the new path is unavailable or trips over an op. Whichever wrote
|
||
the graph, the job then checks it against the torch model (onnx_agreement) before the
|
||
file is kept."""
|
||
torch = _torch()
|
||
|
||
model.eval()
|
||
dummy = torch.zeros(1, 3, input_size, input_size)
|
||
names: dict[str, Any] = dict(input_names=["image"], output_names=["logits"])
|
||
try:
|
||
torch.onnx.export(
|
||
model,
|
||
(dummy,),
|
||
str(path),
|
||
dynamo=True,
|
||
dynamic_shapes={"x": {0: "batch"}},
|
||
opset_version=18,
|
||
external_data=False, # ONE file: the vision image bakes bodytype.onnx + .json, nothing else
|
||
verbose=False,
|
||
**names,
|
||
)
|
||
except Exception: # noqa: BLE001 - any failure → the legacy exporter
|
||
torch.onnx.export(
|
||
model,
|
||
dummy,
|
||
str(path),
|
||
dynamo=False,
|
||
dynamic_axes={"image": {0: "batch"}, "logits": {0: "batch"}},
|
||
opset_version=17,
|
||
**names,
|
||
)
|