Coverage for collectra/tasks/image_segmentation/rfdetr.py: 85.45%

165 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""RF-DETR instance segmentation with Collectra's shared mask training format.""" 

2 

3from __future__ import annotations 

4 

5import json 

6import shutil 

7import os 

8import subprocess 

9import sys 

10import uuid 

11from datetime import datetime 

12from pathlib import Path 

13from typing import Annotated 

14 

15from cappa import Arg 

16import numpy as np 

17from PIL import Image as PILImage 

18 

19from collectra.cli import command 

20from collectra.tasks.base import Task 

21from collectra.types.images import Image, ImageSegmentation 

22from collectra.utils import threading_locked 

23 

24from .data import SegmentationTrainingData, mask_to_source 

25 

26VARIANTS = { 

27 size: f"RFDETRSeg{suffix}" 

28 for size, suffix in ( 

29 ("nano", "Nano"), 

30 ("small", "Small"), 

31 ("medium", "Medium"), 

32 ("large", "Large"), 

33 ("xlarge", "XLarge"), 

34 ("2xlarge", "2XLarge"), 

35 ) 

36} 

37 

38 

39def _rfdetr(): 

40 try: 

41 import rfdetr 

42 except ModuleNotFoundError as error: 

43 if error.name != "rfdetr": 

44 raise 

45 raise ImportError( 

46 'RF-DETR segmentation requires optional dependencies: pip install "collectra[ml]"' 

47 ) from error 

48 return rfdetr 

49 

50 

51def _auto_device() -> str: 

52 """CUDA if there is an NVIDIA GPU, else Apple's MPS, else the CPU.""" 

53 import torch 

54 

55 if torch.cuda.is_available(): 

56 return "cuda" 

57 if torch.backends.mps.is_available(): 

58 return "mps" 

59 return "cpu" 

60 

61 

62class ImageSegmenterRFDETR(SegmentationTrainingData, Task): 

63 """Predict one source-aligned ImageSegmentation for each detected instance. 

64 

65 ``model`` is a segmentation variant (small by default) or a local RF-DETR 

66 checkpoint. Training learns the annotation names as classes. SAM prompt and 

67 version settings are accepted for pipeline migration, but are not used. 

68 """ 

69 

70 def __init__( 

71 self, 

72 name: str, 

73 model: str | Path = "small", 

74 threshold: float = 0.5, 

75 device: str | None = None, 

76 resolution: int | None = None, 

77 **kwargs, 

78 ): 

79 super().__init__(name, **kwargs) 

80 if not 0 <= threshold <= 1: 

81 raise ValueError("threshold must be between 0 and 1") 

82 if resolution is not None and resolution < 1: 

83 raise ValueError("resolution must be positive") 

84 self.model, self.threshold, self.device = model or "small", threshold, device 

85 self.resolution = resolution 

86 self._predictor = None 

87 

88 def attributes_to_ignore(self): 

89 return super().attributes_to_ignore() | {"_predictor"} 

90 

91 def resolved_device(self) -> str: 

92 """The device given, or else the best one this machine has.""" 

93 return self.device or _auto_device() 

94 

95 def input_type(self) -> type: 

96 return Image 

97 

98 def output_type(self) -> type: 

99 return ImageSegmentation 

100 

101 @staticmethod 

102 def _progress(message): 

103 print(f"[RF-DETR Seg] {message}", flush=True) 

104 

105 def _label_prompts(self, samples): 

106 # Preserve artefact names verbatim rather than SAM's prompt descriptions. 

107 return {item.name: item.name for sample in samples for item in sample.instances} 

108 

109 def _init_model(self): 

110 if self._predictor is not None: 

111 return 

112 backend = _rfdetr() 

113 options = {"device": self.resolved_device()} 

114 if self.resolution is not None: 

115 options["resolution"] = self.resolution 

116 variant = str(self.model) 

117 # Accept the package's class names as well as short variant names. 

118 variant = next((k for k, v in VARIANTS.items() if v == variant), variant) 

119 if variant in VARIANTS: 

120 predictor = getattr(backend, VARIANTS[variant])(**options) 

121 else: 

122 checkpoint = Path(self.model).expanduser() 

123 if not checkpoint.is_absolute() and self.pipeline is not None: 

124 checkpoint = self.pipeline.path / checkpoint 

125 if not checkpoint.is_file(): 

126 raise FileNotFoundError(checkpoint) 

127 predictor = backend.RFDETR.from_checkpoint(str(checkpoint), **options) 

128 if not predictor.model_config.segmentation_head: 

129 raise ValueError( 

130 "ImageSegmenterRFDETR requires an RF-DETR segmentation checkpoint" 

131 ) 

132 self._predictor = predictor 

133 

134 @threading_locked() 

135 def run(self, *images: Image) -> list[ImageSegmentation]: 

136 if not images or any(not isinstance(image, Image) for image in images): 

137 raise TypeError("RF-DETR segmentation requires one or more Image artefacts") 

138 self._init_model() 

139 directory = Path(self.context.file_path or Path.cwd()) / "masks" 

140 directory.mkdir(parents=True, exist_ok=True) 

141 outputs = getattr(self, "output", None) 

142 outputs = [outputs] if isinstance(outputs, str) else outputs 

143 results = [] 

144 for image in images: 

145 prediction = self._predictor.predict( 

146 image.pil().convert("RGB"), threshold=self.threshold 

147 ) 

148 if not len(prediction): 

149 continue 

150 masks = prediction.mask 

151 if masks is None or np.asarray(masks).ndim != 3: 

152 raise ValueError("RF-DETR did not return instance segmentation masks") 

153 names = prediction.data.get("class_name") 

154 for index, mask in enumerate(masks): 

155 if names is not None: 

156 label = str(names[index]) 

157 else: 

158 label = self._predictor.class_names[int(prediction.class_id[index])] 

159 if outputs: 

160 aliases = {item.replace("_", " "): item for item in outputs} 

161 aliases.update( 

162 { 

163 prompt: item 

164 for item, prompt in getattr(self, "prompts", {}).items() 

165 if item in outputs 

166 } 

167 ) 

168 label = aliases.get(label, label) 

169 if len(outputs) == 1 and len(self._predictor.class_names) == 1: 

170 label = outputs[0] 

171 if ( 

172 not label 

173 or label == "__background__" 

174 or (outputs and label not in outputs) 

175 ): 

176 continue 

177 pixels = mask_to_source(image, np.asarray(mask) > 0.5) 

178 if not pixels.any(): 

179 continue 

180 path = directory / f"rfdetr-{uuid.uuid4().hex}.png" 

181 PILImage.fromarray(pixels).save(path) 

182 results.append( 

183 ImageSegmentation( 

184 name=label, 

185 data=image.get_path(), 

186 mask=path, 

187 parents=[image.id], 

188 orientation=image.orientation, 

189 partition=image.partition, 

190 ) 

191 ) 

192 return results 

193 

194 @command 

195 def train( 

196 self, 

197 inputs: Annotated[ 

198 list[str], 

199 Arg( 

200 required=False, 

201 default=[], 

202 help="Results YAML files, result directories, or parent directories containing annotated images and masks. May be omitted when reusing an existing export.", 

203 ), 

204 ], 

205 output: Annotated[ 

206 Path | None, 

207 Arg( 

208 help="Directory for prepared data, metrics.csv, logs and best model weights. Defaults to a timestamped directory; required with --reuse-data." 

209 ), 

210 ] = None, 

211 model: Annotated[ 

212 str, 

213 Arg( 

214 help="Model to fine-tune: a variant (nano, small, medium, large, xlarge or 2xlarge), its class name such as RFDETRSegMedium, or an RF-DETR segmentation checkpoint relative to the pipeline directory. Omit to use the configured model. The trained weights replace the configured model either way." 

215 ), 

216 ] = "", 

217 validation: Annotated[ 

218 str, 

219 Arg( 

220 help="Partition used for validation and best-model selection by mask IoU. Omit to train without validation. Ignored when reusing an existing export." 

221 ), 

222 ] = "", 

223 exclude: Annotated[ 

224 str, 

225 Arg( 

226 help="Partition excluded from both training and validation during data preparation. Ignored when reusing an existing export." 

227 ), 

228 ] = "", 

229 epochs: Annotated[ 

230 int, 

231 Arg( 

232 help="Number of training epochs; validation runs after every epoch when available." 

233 ), 

234 ] = 20, 

235 batch: Annotated[ 

236 int, 

237 Arg(help="Number of training images per batch on each GPU."), 

238 ] = 1, 

239 num_gpus: Annotated[ 

240 int, 

241 Arg(help="Number of GPUs used for training on this node."), 

242 ] = 1, 

243 keep_log: Annotated[ 

244 bool, 

245 Arg( 

246 help="Keep prepared data, metrics, logs and checkpoints after copying the best weights into the pipeline. --no-keep-log removes the output directory." 

247 ), 

248 ] = True, 

249 reuse_data: Annotated[ 

250 bool, 

251 Arg( 

252 help="Reuse OUTPUT/dataset when both split annotation files exist; otherwise prepare it from the input paths. Requires --output. Reuse ignores input paths, partitions and --max-items. Does not resume optimizer state." 

253 ), 

254 ] = False, 

255 wandb: Annotated[ 

256 bool, 

257 Arg( 

258 help="Log epoch metrics to Weights & Biases. Project: <pipeline-directory>-<task>; run: output directory name; entity: W&B settings or WANDB_ENTITY." 

259 ), 

260 ] = False, 

261 max_items: Annotated[ 

262 int | None, 

263 Arg( 

264 help="Maximum total images across training and validation, after exclusions, in input order. Omit for all images. Ignored when reusing an existing export." 

265 ), 

266 ] = None, 

267 eval_masks_head_resolution: Annotated[ 

268 bool, 

269 Arg( 

270 help="Score validation (and train/mask_iou) at the mask head's resolution instead of upsampling every prediction to the full image. Avoids GPU out-of-memory on large pages; changes only these metrics and best-epoch selection, not training or the saved model's inference." 

271 ), 

272 ] = False, 

273 ) -> Path: 

274 """Fine-tune RF-DETR on mask annotations and adopt its best weights.""" 

275 if min(epochs, batch, num_gpus) < 1: 

276 raise ValueError("epochs, batch and num_gpus must be positive") 

277 if self.pipeline is None: 

278 raise RuntimeError("Attach the task to a pipeline before training") 

279 if reuse_data and output is None: 

280 raise ValueError("--reuse-data requires --output") 

281 # Resolve the starting weights before any data preparation so typos fail fast. 

282 model = str(model or self.model) 

283 if model not in VARIANTS and model not in VARIANTS.values(): 

284 path = Path(model).expanduser() 

285 path = ( 

286 path.resolve() 

287 if path.is_absolute() 

288 else (self.pipeline.path / path).resolve() 

289 ) 

290 if not path.is_file(): 

291 raise FileNotFoundError( 

292 f"RF-DETR model must be one of {', '.join(VARIANTS)} or a checkpoint file: {path}" 

293 ) 

294 model = str(path) 

295 output = ( 

296 Path(output).expanduser().resolve() 

297 if output is not None 

298 else Path.cwd() / datetime.now().strftime("%Y%m%d_%H%M%S") 

299 ) 

300 dataset = output / "dataset" 

301 reuse_prepared = reuse_data and all( 

302 (dataset / split / "_annotations.coco.json").is_file() 

303 for split in ("train", "valid") 

304 ) 

305 if not reuse_prepared: 

306 if max_items is not None and max_items < 1: 

307 raise ValueError("max_items must be positive") 

308 if not inputs: 

309 raise ValueError( 

310 "Supply training inputs or reuse an existing OUTPUT/dataset export" 

311 ) 

312 output.mkdir(parents=True, exist_ok=True) 

313 self._progress( 

314 f"Training {self.name}: output={output}, epochs={epochs}, batch={batch}, GPUs={num_gpus}" 

315 ) 

316 if reuse_prepared: 

317 self._progress( 

318 f"Reusing {dataset}; ignoring inputs, partitions and --max-items" 

319 ) 

320 else: 

321 self._progress("Preparing masks and images (missing exports are rebuilt)") 

322 dataset = self.prepare_training_data( 

323 inputs, dataset, validation, exclude, max_items=max_items 

324 ) 

325 annotations = json.loads( 

326 (dataset / "train" / "_annotations.coco.json").read_text() 

327 ) 

328 if not annotations["images"] or not annotations["categories"]: 

329 raise ValueError( 

330 "No labelled training images were found in the prepared dataset" 

331 ) 

332 has_validation = bool( 

333 json.loads((dataset / "valid" / "_annotations.coco.json").read_text())[ 

334 "images" 

335 ] 

336 ) 

337 config = { 

338 "model": model, 

339 "device": self.resolved_device(), 

340 "resolution": self.resolution, 

341 "threshold": self.threshold, 

342 "has_validation": has_validation, 

343 "params": { 

344 "dataset_dir": str(dataset), 

345 "output_dir": str(output), 

346 "epochs": epochs, 

347 "batch_size": batch, 

348 "devices": num_gpus, 

349 "grad_accum_steps": 1, 

350 "device": self.resolved_device(), 

351 "wandb": wandb, 

352 "project": f"{self.pipeline.name}-{self.name}", 

353 "run": output.name, 

354 "use_ema": False, 

355 "run_test": False, 

356 "eval_interval": 1, 

357 "eval_masks_head_resolution": eval_masks_head_resolution, 

358 }, 

359 } 

360 config_path = output / "rfdetr-training.json" 

361 config_path.write_text(json.dumps(config, indent=2), encoding="utf-8") 

362 self._progress( 

363 "Starting RF-DETR trainer (initial weights may download); trainer output follows" 

364 ) 

365 subprocess.run( 

366 [ 

367 sys.executable, 

368 "-u", 

369 "-m", 

370 "collectra.tasks.image_segmentation.rfdetr_training", 

371 str(config_path), 

372 ], 

373 check=True, 

374 env={**os.environ, "PYTHONUNBUFFERED": "1"}, 

375 ) 

376 checkpoint = output / "best.pt" 

377 if not checkpoint.is_file(): 

378 raise FileNotFoundError( 

379 f"RF-DETR training produced no checkpoint at {checkpoint}" 

380 ) 

381 destination = self.pipeline.path / f"{self.name}-{uuid.uuid4().hex[:8]}.pt" 

382 shutil.copy2(checkpoint, destination) 

383 self.model, self._predictor = destination, None 

384 self.pipeline.data[self.name]["model"] = destination.name 

385 self.pipeline.save(self.name) 

386 self._progress(f"Saved trained checkpoint: {destination}") 

387 if not keep_log: 

388 shutil.rmtree(output) 

389 return destination 

390 

391 

392# The former name of ImageSegmenterRFDETR. 

393ImageSegmentationRFDETR = ImageSegmenterRFDETR