Coverage for collectra/tasks/image_classifier/training.py: 83.96%
293 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Shared preparation of labelled classifier inputs."""
3import csv
4import json
5import math
6import os
7from collections.abc import Mapping
8from concurrent.futures import ThreadPoolExecutor, as_completed
9from pydantic import BaseModel
11from collectra.commons import PositionalFields
12from pathlib import Path
13from rich.console import Console
14from rich.progress import (
15 BarColumn,
16 MofNCompleteColumn,
17 Progress,
18 SpinnerColumn,
19 TextColumn,
20 TimeElapsedColumn,
21 TimeRemainingColumn,
22)
24from collectra.logger import get_logger
25from ..base import Task
26from ..machine_learning.class_names import write_class_names
27from ..machine_learning.training import print_distribution_table
28from collectra.types.images import Image, ImageCrop
29from collectra.types.links import Link
32def prepare_classification_inputs(
33 processed_inputs: list,
34 processed_parents: list,
35 input_maps: dict[str, list],
36 parent_input_maps: dict[str, list],
37) -> list:
38 """Use parent images labelled by their child Link node names."""
39 labeled_parents = []
40 for file_name, children in input_maps.items():
41 parents = parent_input_maps.get(file_name, [])
42 artefacts = {item.id: item for item in [*parents, *children]}
43 for item in artefacts.values():
44 if type(item) is Link:
45 item.bind(artefacts)
46 for child in children:
47 if type(child) is not Link:
48 raise TypeError(
49 f"Classifier label {child.id!r} in {file_name!r} must be "
50 f"a Link, got {type(child).__name__}"
51 )
52 if not child.parents:
53 raise ValueError(
54 f"Classifier Link {child.id!r} in {file_name!r} has no parent"
55 )
56 parent_id = (
57 child.parents if isinstance(child.parents, str) else child.parents[0]
58 )
59 parent = artefacts.get(parent_id)
60 if parent is None:
61 raise ValueError(
62 f"Classifier Link {child.id!r} in {file_name!r} points to "
63 f"missing parent {parent_id!r}; available parent IDs: "
64 f"{[item.id for item in parents]}"
65 )
66 child.target = parent
67 try:
68 target = child.resolve()
69 except RuntimeError as error:
70 raise ValueError(
71 f"Classifier Link {child.id!r} in {file_name!r} cannot "
72 f"resolve parent chain: {error}"
73 ) from error
74 if not isinstance(target, Image):
75 raise TypeError(
76 f"Classifier Link {child.id!r} resolves to "
77 f"{type(target).__name__}, expected Image or ImageCrop"
78 )
79 child.partition = target.partition
80 labeled_parents.append(child)
81 return labeled_parents
84logger = get_logger(__name__)
85console = Console()
88class ClassificationTrainResult(PositionalFields, BaseModel):
89 save_dir: Path
90 results_dict: dict
93class TorchClassifierTask(Task):
94 """Shared export, optimization, and metrics for PyTorch classification backends."""
96 @staticmethod
97 def _select_device(device: str = "") -> str:
98 import torch
100 if device:
101 return device
102 if torch.cuda.is_available():
103 return "cuda"
104 if torch.backends.mps.is_available():
105 return "mps"
106 return "cpu"
108 def _reload(self) -> None:
109 if self.original_model_path is None:
110 raise ValueError("No checkpoint is available to reload")
111 self.model = self.original_model_path
112 self._load()
114 def _prepare_assets(
115 self,
116 classes,
117 log,
118 validation,
119 exclude,
120 *images,
121 min_size=0,
122 workers=0,
123 use_existing=False,
124 ):
125 """Materialize labelled images and crops in train/<class> and val/<class>."""
126 if min_size < 0:
127 raise ValueError("min_size cannot be negative")
128 for name in classes:
129 if not name or name in {".", ".."} or "/" in name or "\\" in name:
130 raise ValueError(f"Class name must be a directory name: {name!r}")
131 train_dir, val_dir = log / "train", log / "val"
132 if use_existing and train_dir.exists() and val_dir.exists():
133 logger.info(
134 "Reusing existing classifier assets in %s and %s",
135 train_dir,
136 val_dir,
137 )
138 counts = {
139 split: {name: 0 for name in classes} for split in ("train", "val")
140 }
141 for split, directory in (("train", train_dir), ("val", val_dir)):
142 for name in classes:
143 class_dir = directory / name
144 if class_dir.exists():
145 counts[split][name] = sum(
146 1 for path in class_dir.iterdir() if path.is_file()
147 )
148 print_distribution_table(
149 "Class Distribution", classes, counts["train"], counts["val"]
150 )
151 missing = [name for name in classes if not counts["train"][name]]
152 if missing:
153 raise ValueError(
154 "No training images for classes in existing dataset: "
155 f"{', '.join(missing)}"
156 )
157 return train_dir, val_dir
158 for directory in (train_dir, val_dir):
159 if directory.exists() and any(directory.iterdir()):
160 raise ValueError(
161 f"Dataset directory is not empty: {directory}. Use a new output directory."
162 )
163 counts = {split: {name: 0 for name in classes} for split in ("train", "val")}
164 for directory in (train_dir, val_dir):
165 for name in classes:
166 (directory / name).mkdir(parents=True, exist_ok=True)
167 jobs = []
168 for index, image in enumerate(images):
169 if exclude and image.partition == exclude:
170 continue
171 if image.name not in classes:
172 raise ValueError(
173 f"Training label {image.name!r} is not a configured class"
174 )
175 target = image.resolve() if type(image) is Link else image
176 if not isinstance(target, Image):
177 raise TypeError(
178 f"Classifier input {image.id!r} does not resolve to an Image"
179 )
180 if isinstance(target, ImageCrop):
181 left, top, right, bottom = target.coordinates()
182 if right <= left or bottom <= top:
183 logger.warning("Skipping empty classifier crop %s", image.id)
184 continue
185 split = "val" if validation and image.partition == validation else "train"
186 destination = log / split / image.name / f"{index:08d}"
187 jobs.append((image.id, image.name, split, target, destination))
189 export_workers = max(0, int(workers))
190 tiff_decode_workers = 1 if export_workers > 1 else None
192 def export_job(target, destination):
193 return self._export_image(
194 target,
195 destination,
196 min_size,
197 tiff_maxworkers=tiff_decode_workers,
198 )
200 with Progress(
201 SpinnerColumn(),
202 TextColumn("{task.description}"),
203 BarColumn(),
204 MofNCompleteColumn(),
205 TextColumn("•"),
206 TimeElapsedColumn(),
207 TextColumn("•"),
208 TimeRemainingColumn(),
209 ) as progress:
210 task_id = progress.add_task(
211 "Exporting classifier assets...", total=len(jobs)
212 )
213 if export_workers > 0:
214 with ThreadPoolExecutor(max_workers=export_workers) as executor:
215 futures = {
216 executor.submit(export_job, target, destination): (
217 image_id,
218 class_name,
219 split,
220 )
221 for image_id, class_name, split, target, destination in jobs
222 }
223 for future in as_completed(futures):
224 image_id, class_name, split = futures[future]
225 progress.update(task_id, description=f"Exporting {image_id}")
226 if future.result():
227 counts[split][class_name] += 1
228 progress.advance(task_id)
229 else:
230 for image_id, class_name, split, target, destination in jobs:
231 progress.update(task_id, description=f"Exporting {image_id}")
232 if export_job(target, destination):
233 counts[split][class_name] += 1
234 progress.advance(task_id)
235 print_distribution_table(
236 "Class Distribution", classes, counts["train"], counts["val"]
237 )
238 missing = [name for name in classes if not counts["train"][name]]
239 if missing:
240 raise ValueError(f"No training images for classes: {', '.join(missing)}")
241 return train_dir, val_dir
243 def _export_image(
244 self, target, destination, min_size, tiff_maxworkers: int | None = None
245 ):
246 with target.pil() as pixels:
247 if min(pixels.size) < max(1, min_size):
248 logger.warning(
249 "Skipping classifier image %s below minimum size %d",
250 target.id,
251 min_size,
252 )
253 return False
254 pixels.convert("RGB").save(destination.with_suffix(".png"))
255 return True
257 def _make_datasets(self, train_dir, val_dir, augmentation):
258 from torchvision.datasets import ImageFolder
260 return (
261 ImageFolder(
262 train_dir, transform=self._transforms(training=True, **augmentation)
263 ),
264 ImageFolder(val_dir, transform=self._transforms(), allow_empty=True),
265 )
267 def _train(self, *images: Image, **kwargs) -> ClassificationTrainResult:
268 import torch
269 from torch.utils.data import DataLoader
271 epochs, batch = int(kwargs.get("epochs", 10)), int(kwargs.get("batch", 16))
272 workers, patience = int(kwargs.get("workers", 8)), int(
273 kwargs.get("early_stop", 10)
274 )
275 fliplr = float(kwargs.get("fliplr", 0.5))
276 augmentation = {"fliplr": fliplr}
277 if "flipud" in kwargs:
278 flipud = float(kwargs["flipud"])
279 if not 0 <= flipud <= 1:
280 raise ValueError("flipud must be in [0, 1]")
281 augmentation["flipud"] = flipud
282 if kwargs.get("rotate90"):
283 augmentation["rotate90"] = True
284 if (
285 epochs < 1
286 or batch < 1
287 or workers < 0
288 or patience < 0
289 or not 0 <= fliplr <= 1
290 ):
291 raise ValueError(
292 "epochs and batch must be positive; workers/early_stop nonnegative; fliplr in [0, 1]"
293 )
294 if "log" not in kwargs or "base_folder" not in kwargs:
295 raise ValueError("Training requires log and base_folder directories")
296 available_workers = max(1, os.cpu_count() or 1)
297 if workers > 0 and workers > available_workers:
298 logger.info(
299 "Capping workers from %d to available CPU count %d",
300 workers,
301 available_workers,
302 )
303 workers = available_workers
304 torch.manual_seed(int(kwargs.get("seed", 0)))
305 self._device = self._select_device(kwargs.get("device", ""))
306 if kwargs.get("model"):
307 self.model = kwargs["model"]
308 configured = kwargs.get("classes") or getattr(self, "output", [])
309 if isinstance(configured, str):
310 configured = [configured]
311 # The pipeline's outputs, in its order. Only without them are the classes
312 # found from the images.
313 classes = list(dict.fromkeys(configured)) or sorted(
314 {
315 image.name
316 for image in images
317 if not kwargs.get("exclude") or image.partition != kwargs["exclude"]
318 }
319 )
320 if not classes:
321 raise ValueError("No classes provided/found for classifier training")
322 log = (Path(kwargs["base_folder"]) / kwargs["log"]).resolve()
323 logger.info(
324 "Preparing classifier assets at %s (use_existing=%s, workers=%d)",
325 log,
326 bool(kwargs.get("use_existing", False)),
327 workers,
328 )
329 train_dir, val_dir = self._prepare_assets(
330 classes,
331 log,
332 kwargs.get("validation", ""),
333 kwargs.get("exclude", ""),
334 *images,
335 min_size=kwargs.get("min_size", 0),
336 workers=workers,
337 use_existing=bool(kwargs.get("use_existing", False)),
338 )
339 logger.info("Asset preparation complete: train=%s val=%s", train_dir, val_dir)
340 # Load preprocessing config before dataset construction so channel
341 # detection and normalization logic can run on real sample files.
342 logger.info(
343 "Loading model for preprocessing (model=%s, pretrained=%s)",
344 self.model,
345 kwargs.get("pretrained", True),
346 )
347 self._load(pretrained=kwargs.get("pretrained", True))
348 logger.info("Building datasets and detecting channel count")
349 train_data, val_data = self._make_datasets(train_dir, val_dir, augmentation)
350 # Torchvision stores normalization here; other backends (e.g. Hugging
351 # Face) own their preprocessing elsewhere. Logging must not require it.
352 preprocessing = getattr(self, "_preprocessing", {})
353 logger.info(
354 "Datasets ready: train=%d, val=%d, detected_channels=%s, mean_len=%d, std_len=%d",
355 len(train_data),
356 len(val_data),
357 getattr(self, "_input_channels", "unknown"),
358 len(preprocessing.get("mean", [])),
359 len(preprocessing.get("std", [])),
360 )
361 freeze = kwargs.get("freeze_backbone", False)
362 logger.info("Preparing training model (freeze_backbone=%s)", freeze)
363 self._prepare_training_model(classes, kwargs.get("pretrained", True), freeze)
364 if hasattr(self.model, "conv1") and hasattr(self.model.conv1, "in_channels"):
365 logger.info(
366 "Model conv1 channels after preparation: %s",
367 self.model.conv1.in_channels,
368 )
369 train_loader = DataLoader(
370 train_data, batch_size=batch, shuffle=True, num_workers=workers
371 )
372 val_loader = (
373 DataLoader(val_data, batch_size=batch, num_workers=workers)
374 if len(val_data)
375 else None
376 )
377 logger.info(
378 "DataLoaders ready: train_batches=%d, val_batches=%d, batch=%d, workers=%d",
379 len(train_loader),
380 len(val_loader) if val_loader is not None else 0,
381 batch,
382 workers,
383 )
384 if val_loader is None and kwargs.get("validation"):
385 raise ValueError(
386 f"No validation images match partition {kwargs['validation']!r} "
387 "after exclusions and size filtering"
388 )
389 if val_loader is None:
390 logger.warning(
391 "No validation images; best checkpoint will use training loss, with early stopping disabled"
392 )
393 optimizer = torch.optim.AdamW(
394 [
395 parameter
396 for parameter in self.model.parameters()
397 if parameter.requires_grad
398 ],
399 lr=float(kwargs.get("learning_rate", 0.0001)),
400 weight_decay=float(kwargs.get("weight_decay", 0.0001)),
401 )
402 weights_dir = log / "weights"
403 weights_dir.mkdir(parents=True, exist_ok=True)
404 write_class_names(weights_dir / "classes.yaml", classes)
405 wandb_run = None
406 if bool(kwargs.get("wandb", False)):
407 try:
408 import wandb
410 wandb_config = {
411 key: str(value) if isinstance(value, Path) else value
412 for key, value in kwargs.items()
413 }
414 wandb_config["classes"] = classes
415 wandb_run = wandb.init(
416 project=str(kwargs.get("project", "collectra-classifier")),
417 name=log.name,
418 dir=str(kwargs["base_folder"]),
419 config=wandb_config,
420 reinit=True,
421 )
422 except Exception as error:
423 logger.warning("W&B init skipped: %s", error)
424 history, best_accuracy, best_metrics, stale = [], -math.inf, {}, 0
425 try:
426 with Progress(
427 SpinnerColumn(),
428 TextColumn("{task.description}"),
429 BarColumn(),
430 MofNCompleteColumn(),
431 TextColumn("•"),
432 TimeElapsedColumn(),
433 TextColumn("•"),
434 TimeRemainingColumn(),
435 ) as progress:
436 epoch_task_id = progress.add_task("Training epochs...", total=epochs)
437 for epoch in range(1, epochs + 1):
438 progress.update(
439 epoch_task_id, description=f"Training epoch {epoch}/{epochs}"
440 )
441 logger.info("Starting epoch %d/%d", epoch, epochs)
442 self.model.train(
443 not freeze
444 ) # Frozen BatchNorm statistics must remain frozen too.
445 train_metrics = self._epoch(train_loader, optimizer)
446 self.model.eval()
447 with torch.inference_mode():
448 val_metrics = (
449 self._epoch(val_loader) if val_loader is not None else None
450 )
451 metrics = {
452 "epoch": epoch,
453 **{f"train_{k}": v for k, v in train_metrics.items()},
454 }
455 metrics.update(
456 {f"val_{k}": v for k, v in (val_metrics or {}).items()}
457 )
458 history.append(metrics)
459 checkpoint = self._checkpoint(epoch, metrics)
460 torch.save(checkpoint, weights_dir / "last.pt")
461 score = (
462 val_metrics["accuracy"]
463 if val_metrics
464 else train_metrics["accuracy"]
465 )
466 if not math.isfinite(score):
467 raise ValueError("Training produced a non-finite accuracy")
468 if score > best_accuracy:
469 best_accuracy, best_metrics, stale = score, dict(metrics), 0
470 torch.save(checkpoint, weights_dir / "best.pt")
471 best_print = " best"
472 else:
473 stale += 1
474 best_print = ""
475 if wandb_run is not None:
476 wandb_run.log(metrics)
477 logger.info("Epoch %d/%d: %s", epoch, epochs, metrics)
478 metrics_line = (
479 f"Epoch {epoch}/{epochs} "
480 f"train_loss={metrics['train_loss']:.4f} "
481 f"train_acc={metrics['train_accuracy']:.4f} "
482 f"train_top5={metrics['train_top5_accuracy']:.4f}"
483 )
484 if val_metrics is not None:
485 metrics_line += (
486 f" val_loss={metrics['val_loss']:.4f} "
487 f"val_acc={metrics['val_accuracy']:.4f} "
488 f"val_top5={metrics['val_top5_accuracy']:.4f}"
489 )
490 console.print(metrics_line + best_print)
491 with (log / "history.csv").open("w", newline="") as stream:
492 writer = csv.DictWriter(stream, fieldnames=list(metrics))
493 writer.writeheader()
494 writer.writerows(history)
495 progress.advance(epoch_task_id)
496 if val_loader is not None and patience and stale >= patience:
497 console.print(
498 f"Early stopping at epoch {epoch}: no val-accuracy improvement in {patience} epoch(s)."
499 )
500 break
501 finally:
502 if wandb_run is not None:
503 wandb_run.finish()
504 self.original_model_path = weights_dir / "best.pt"
505 self._reload()
506 best_metrics.update(classes=classes, epochs_completed=len(history))
507 (log / "metrics.json").write_text(json.dumps(best_metrics, indent=2))
508 return ClassificationTrainResult(save_dir=log, results_dict=best_metrics)
510 def _epoch(self, loader, optimizer=None) -> dict:
511 import torch
512 from torch.nn import functional as F
513 from sklearn.metrics import precision_recall_fscore_support
515 total, correct, correct5, total_loss = 0, 0, 0, 0.0
516 all_preds, all_labels = [], []
517 first_batch = True
518 phase = "train" if optimizer is not None else "val"
519 for pixels, labels in loader:
520 # Torchvision batches are tensors; Hugging Face batches are dicts
521 # of processor outputs keyed by model input name.
522 tensors = pixels if isinstance(pixels, Mapping) else {"pixels": pixels}
523 shapes = {name: tuple(tensor.shape) for name, tensor in tensors.items()}
524 if first_batch:
525 approximate_mib = sum(
526 tensor.numel() * tensor.element_size()
527 for tensor in tensors.values()
528 ) / (1024 * 1024)
529 logger.info(
530 "%s first batch: input_shapes=%s, labels_shape=%s, dtypes=%s, approx_input_mib=%.1f",
531 phase,
532 shapes,
533 tuple(labels.shape),
534 {name: tensor.dtype for name, tensor in tensors.items()},
535 approximate_mib,
536 )
537 first_batch = False
538 labels = labels.to(self._device)
539 if optimizer is not None:
540 optimizer.zero_grad(set_to_none=True)
541 try:
542 logits = self._forward(pixels)
543 loss = F.cross_entropy(logits, labels)
544 except RuntimeError as error:
545 raise RuntimeError(
546 f"{phase} step failed for input shapes {shapes} "
547 f"on device {self._device}: {error}"
548 ) from error
549 if optimizer is not None:
550 loss.backward()
551 optimizer.step()
552 total += labels.size(0)
553 total_loss += loss.item() * labels.size(0)
554 correct += (logits.argmax(1) == labels).sum().item()
555 correct5 += (
556 (
557 logits.topk(min(5, len(self._categories)), dim=1).indices
558 == labels[:, None]
559 )
560 .any(1)
561 .sum()
562 .item()
563 )
564 all_preds.extend(logits.argmax(1).detach().cpu().tolist())
565 all_labels.extend(labels.cpu().tolist())
566 precision, recall, f1, _ = precision_recall_fscore_support(
567 all_labels, all_preds, average="macro", zero_division=0
568 )
569 return {
570 "precision": float(precision),
571 "recall": float(recall),
572 "f1": float(f1),
573 "loss": total_loss / total,
574 "accuracy": correct / total,
575 "top5_accuracy": correct5 / total,
576 }