Coverage for collectra/tasks/object_detection/rfdetr_curves.py: 97.10%
69 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"""W&B detection curves from RF-DETR's native validation matching data."""
3from contextlib import contextmanager
4from functools import wraps
5import json
6from pathlib import Path
8import numpy as np
11def detection_curves(matching, class_names):
12 """Use RF-DETR's IoU=0.5 matching and confidence sweep, excluding void classes."""
13 from rfdetr.evaluation.f1_sweep import sweep_confidence_thresholds
15 ids = sorted(matching)
16 included = [index for index, cid in enumerate(ids) if matching[cid]["total_gt"] > 0]
17 if not included:
18 return None
19 sweep = sweep_confidence_thresholds(
20 [matching[cid] for cid in ids], np.linspace(0, 1, 101), included
21 )
22 confidence = [float(row["confidence_threshold"]) for row in sweep]
23 precision = np.asarray([row["per_class_prec"] for row in sweep])[:, included].T
24 recall = np.asarray([row["per_class_rec"] for row in sweep])[:, included].T
25 f1 = np.asarray([row["per_class_f1"] for row in sweep])[:, included].T
26 recall_grid = np.linspace(0, 1, 101)
27 pr = []
28 for r, p in zip(recall, precision):
29 # Recall repeats while confidence removes false positives. Keep the
30 # highest precision at each recall, then form its upper envelope.
31 unique = np.unique(r)
32 values = np.array([p[r == point].max() for point in unique])
33 envelope = np.maximum.accumulate(values[::-1])[::-1]
34 pr.append(np.interp(recall_grid, unique, envelope, right=0))
35 names = [str(class_names.get(ids[index], ids[index])) for index in included]
37 def series(values):
38 return np.concatenate([values, np.mean(values, axis=0, keepdims=True)]).tolist()
40 return {
41 "names": names + ["mean"],
42 "iou_threshold": 0.5,
43 "confidence": confidence,
44 "recall": series(recall),
45 "precision": series(precision),
46 "f1": series(f1),
47 "recall_grid": recall_grid.tolist(),
48 "pr_precision": series(np.asarray(pr)),
49 }
52def log_detection_curves(trainer, curves, output):
53 """Log into the trainer's existing W&B run, never create a second run."""
54 if curves is None or not trainer.is_global_zero:
55 return
56 from pytorch_lightning.loggers import WandbLogger
57 import wandb
59 directory = Path(output) / "curves"
60 directory.mkdir(parents=True, exist_ok=True)
61 epoch = int(trainer.current_epoch) + 1
62 (directory / f"epoch-{epoch:04d}.json").write_text(
63 json.dumps({"epoch": epoch, **curves}, indent=2) + "\n"
64 )
65 plots = {
66 "Recall-Confidence": ("confidence", "recall", "Confidence"),
67 "Precision-Recall": ("recall_grid", "pr_precision", "Recall"),
68 "Precision-Confidence": ("confidence", "precision", "Confidence"),
69 "F1-Confidence": ("confidence", "f1", "Confidence"),
70 }
71 for logger in trainer.loggers:
72 if not isinstance(logger, WandbLogger):
73 continue
74 payload = {
75 f"curves/{name}": wandb.plot.line_series(
76 xs=curves[x],
77 ys=curves[y],
78 keys=curves["names"],
79 title=f"{name} Curve (IoU 0.5)",
80 xname=xlabel,
81 )
82 for name, (x, y, xlabel) in plots.items()
83 }
84 payload["trainer/global_step"] = trainer.global_step
85 payload["epoch"] = int(trainer.current_epoch)
86 logger.experiment.log(payload)
89@contextmanager
90def wandb_detection_curves(enabled, output, classes):
91 """Capture compact matches before the native callback clears its epoch state."""
92 if not enabled:
93 yield
94 return
95 from rfdetr.training.callbacks import coco_eval
97 callback = coco_eval.COCOEvalCallback
98 original = getattr(callback, "_compute_and_log", None)
99 if original is None or not callable(
100 getattr(coco_eval, "distributed_merge_matching_data", None)
101 ):
102 raise RuntimeError(
103 "RF-DETR validation curves require its Lightning validation matching API. "
104 'Update the backend with: pip install --upgrade "rfdetr[train,loggers]"'
105 )
107 @wraps(original)
108 def compute_and_log(self, trainer, pl_module, split, *args, **kwargs):
109 # All ranks must enter this collective, including ranks with no local
110 # detections. Only rank zero builds plots and writes files afterward.
111 matching = None
112 if split == "val" and not trainer.sanity_checking:
113 matching = coco_eval.distributed_merge_matching_data(self._f1_local)
114 result = original(self, trainer, pl_module, split, *args, **kwargs)
115 if matching is not None and trainer.is_global_zero:
116 names = dict(enumerate(classes))
117 names.update(getattr(self, "_cat_id_to_name", {}))
118 log_detection_curves(trainer, detection_curves(matching, names), output)
119 return result
121 callback._compute_and_log = compute_and_log
122 try:
123 yield
124 finally:
125 callback._compute_and_log = original