Coverage for collectra/tasks/image_segmentation/rfdetr_training.py: 89.24%
158 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"""Optional RF-DETR training integration; no backend imports during discovery."""
3from contextlib import contextmanager
4import csv
5import json
6import math
7from pathlib import Path
8import time
11from .mask_metrics import mask_overlap
14def rfdetr_train_predictions(output):
15 """Predict the training images like validation: eval mode, no augmentation.
17 Returns a function yielding (results, targets) batches for make_callback.
18 RF-DETR builds non-augmented loaders only for its fixed split names, so a
19 view directory OUTPUT/train-eval links both "train" (label mapping) and
20 "valid" (images) to the exported training split.
21 """
22 cache = {}
24 def datamodule(pl_module):
25 if "module" not in cache:
26 from rfdetr.training.module_data import RFDETRDataModule
28 images = Path(pl_module.train_config.dataset_dir).resolve() / "train"
29 view = Path(output) / "train-eval"
30 view.mkdir(exist_ok=True)
31 for name in ("train", "valid"):
32 try:
33 (view / name).symlink_to(images, target_is_directory=True)
34 except FileExistsError:
35 if (view / name).resolve() != images:
36 raise
37 config = pl_module.train_config.model_copy(
38 update={"dataset_dir": str(view)}
39 )
40 cache["module"] = RFDETRDataModule(pl_module.model_config, config)
41 cache["module"].setup("validate")
42 return cache["module"]
44 def predict(trainer, pl_module):
45 import torch
47 module = datamodule(pl_module)
48 model = pl_module._resolve_eval_model()
49 was_training = model.training
50 model.eval()
51 try:
52 with torch.inference_mode(), trainer.precision_plugin.val_step_context():
53 for batch in module.val_dataloader():
54 samples, targets = module.transfer_batch_to_device(
55 batch, pl_module.device, 0
56 )
57 sizes = torch.stack([target["orig_size"] for target in targets])
58 yield pl_module.postprocess(model(samples), sizes), targets
59 finally:
60 model.train(was_training)
62 return predict
65def make_callback(output, threshold, has_validation, train_predictions=None):
66 """Build the optional Lightning callback after training dependencies load.
68 train_predictions(trainer, pl_module), when given, yields (results, targets)
69 for the training images; their mask IoU is logged as train/mask_iou.
70 """
71 import torch
72 from pytorch_lightning.callbacks import Callback
74 class SegmentationMetrics(Callback):
75 def __init__(self):
76 self.best = -math.inf
77 self.rows = {}
79 def on_fit_start(self, trainer, pl_module):
80 if trainer.is_global_zero:
81 for name in ("best.pt", "best.json"):
82 (Path(output) / name).unlink(missing_ok=True)
84 def on_validation_epoch_start(self, trainer, pl_module):
85 self.overlap = torch.zeros(2, dtype=torch.int64, device=pl_module.device)
87 def on_validation_batch_end(
88 self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0
89 ):
90 if trainer.sanity_checking:
91 return
92 for prediction, target in zip(outputs["results"], outputs["targets"]):
93 self.overlap += mask_overlap(prediction, target, threshold)
95 def on_validation_epoch_end(self, trainer, pl_module):
96 if trainer.sanity_checking:
97 return
98 if torch.distributed.is_available() and torch.distributed.is_initialized():
99 torch.distributed.all_reduce(self.overlap)
100 score = self.overlap[0] / self.overlap[1].clamp_min(1)
101 pl_module.log("val/mask_iou", score.float(), prog_bar=True, sync_dist=False)
102 self._log_train_iou(trainer, pl_module)
104 def _log_train_iou(self, trainer, pl_module):
105 """Score the training images like validation and log train/mask_iou.
107 Every rank scores all images (no sampler sharding), so no reduction is needed.
108 """
109 if train_predictions is None:
110 return
111 started = time.monotonic()
112 overlap = torch.zeros(2, dtype=torch.int64, device=pl_module.device)
113 for results, targets in train_predictions(trainer, pl_module):
114 for prediction, target in zip(results, targets):
115 overlap += mask_overlap(prediction, target, threshold)
116 score = overlap[0] / overlap[1].clamp_min(1)
117 pl_module.log("train/mask_iou", score.float(), sync_dist=False)
118 print(
119 f"Train mask IoU (eval pass): epoch={trainer.current_epoch + 1}, "
120 f"iou={float(score):.4f}, {time.monotonic() - started:.0f}s",
121 flush=True,
122 )
124 def _report(self, trainer):
125 if not trainer.is_global_zero or trainer.sanity_checking:
126 return
127 row = self.rows.setdefault(
128 trainer.current_epoch + 1, {"epoch": trainer.current_epoch + 1}
129 )
130 for key, value in trainer.callback_metrics.items():
131 if hasattr(value, "numel") and value.numel() != 1:
132 continue
133 try:
134 value = float(value)
135 except (TypeError, ValueError):
136 continue
137 row[key] = value
138 fields = ["epoch"] + sorted(
139 {key for row in self.rows.values() for key in row if key != "epoch"}
140 )
141 with (Path(output) / "metrics.csv").open(
142 "w", newline="", encoding="utf-8"
143 ) as stream:
144 writer = csv.DictWriter(stream, fieldnames=fields)
145 writer.writeheader()
146 writer.writerows(self.rows.values())
148 def _save(self, trainer, pl_module, metric, score):
149 if (
150 not trainer.is_global_zero
151 or not math.isfinite(score)
152 or score <= self.best
153 ):
154 return
155 self.best = score
156 args = pl_module.train_config.model_dump()
157 args["class_names"] = list(trainer.datamodule.class_names)
158 config = pl_module.model_config.model_dump()
159 checkpoint = {
160 "model": pl_module.model.state_dict(),
161 "args": args,
162 "model_config": config,
163 "model_name": config["model_name"],
164 "epoch": trainer.current_epoch,
165 }
166 temporary = Path(output) / "best.pt.tmp"
167 torch.save(checkpoint, temporary)
168 temporary.replace(Path(output) / "best.pt")
169 (Path(output) / "best.json").write_text(
170 json.dumps(
171 {
172 "epoch": trainer.current_epoch + 1,
173 "metric": metric,
174 "value": -score if metric == "train/loss" else score,
175 }
176 ),
177 encoding="utf-8",
178 )
180 def on_validation_end(self, trainer, pl_module):
181 if trainer.sanity_checking:
182 return
183 self._report(trainer)
184 score = trainer.callback_metrics.get("val/mask_iou")
185 if score is not None:
186 self._save(trainer, pl_module, "val/mask_iou", float(score))
188 def on_train_epoch_end(self, trainer, pl_module):
189 if not has_validation:
190 self._log_train_iou(trainer, pl_module)
191 self._report(trainer)
192 if not has_validation:
193 score = trainer.callback_metrics.get("train/loss")
194 if score is not None:
195 self._save(trainer, pl_module, "train/loss", -float(score))
197 return SegmentationMetrics()
200@contextmanager
201def training_hooks(output, threshold, has_validation):
202 """Replace native optimizer snapshots with one best, reloadable weights file.
204 RF-DETR's train() constructs its own callbacks. Scope the extension to this
205 training process, leaving its COCO evaluation and W&B/CSV loggers intact.
206 RF-DETR's CSV logger is moved to OUTPUT/lightning: it also writes
207 metrics.csv, and rereads that file whenever new metric keys appear, so
208 sharing Collectra's per-epoch OUTPUT/metrics.csv crashes training.
209 """
210 import rfdetr.training.trainer as native
211 from pytorch_lightning.callbacks import ModelCheckpoint
213 original = native._append_training_callbacks
215 def append(callbacks, loggers, *args, **kwargs):
216 original(callbacks, loggers, *args, **kwargs)
217 callbacks[:] = [cb for cb in callbacks if not isinstance(cb, ModelCheckpoint)]
218 callbacks.append(
219 make_callback(
220 output,
221 threshold,
222 has_validation,
223 train_predictions=rfdetr_train_predictions(output),
224 )
225 )
227 # Also disable Lightning's implicit default checkpoint when none remains.
228 import rfdetr.training as training
230 original_builder = training.build_trainer
232 def build(*args, **kwargs):
233 kwargs["enable_checkpointing"] = False
234 if not has_validation:
235 kwargs["limit_val_batches"] = 0
236 return original_builder(*args, **kwargs)
238 original_csv_logger = native.CSVLogger
240 def csv_logger(save_dir, *args, **kwargs):
241 return original_csv_logger(Path(save_dir) / "lightning", *args, **kwargs)
243 native._append_training_callbacks = append
244 training.build_trainer = build
245 native.CSVLogger = csv_logger
246 try:
247 yield
248 finally:
249 native._append_training_callbacks = original
250 training.build_trainer = original_builder
251 native.CSVLogger = original_csv_logger
254def launch(config_path):
255 from .rfdetr import ImageSegmenterRFDETR
257 config = json.loads(Path(config_path).read_text())
258 task = ImageSegmenterRFDETR(
259 "train",
260 model=config["model"],
261 device=config["device"],
262 resolution=config["resolution"],
263 )
264 with training_hooks(
265 config["params"]["output_dir"], config["threshold"], config["has_validation"]
266 ):
267 task._init_model()
268 task._predictor.train(**config["params"])
271if __name__ == "__main__":
272 import sys
274 launch(sys.argv[1])