Coverage for collectra/tasks/image_segmentation/yolo.py: 88.00%

150 statements  

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

1"""YOLO 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 

26 

27from collectra.tasks.machine_learning.yolo import get_yolo_class 

28 

29 

30def yolo_device(device, num_gpus=1): 

31 """Translate torch-style devices to Ultralytics device selectors.""" 

32 if device == "cuda" or str(device).startswith("cuda:"): 

33 start = int(str(device).split(":", 1)[1]) if ":" in str(device) else 0 

34 return list(range(start, start + num_gpus)) if num_gpus > 1 else start 

35 if num_gpus != 1: 

36 raise ValueError("Multiple GPUs require a CUDA device") 

37 return device 

38 

39 

40class ImageSegmenterYOLO(SegmentationTrainingData, Task): 

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

42 

43 ``model`` is an Ultralytics segmentation model name or a local YOLO 

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

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

46 """ 

47 

48 def __init__( 

49 self, 

50 name: str, 

51 model: str | Path = "yolo11n-seg.pt", 

52 threshold: float = 0.5, 

53 device: str | None = None, 

54 resolution: int | None = None, 

55 **kwargs, 

56 ): 

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

58 if not 0 <= threshold <= 1: 

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

60 if resolution is not None and resolution < 1: 

61 raise ValueError("resolution must be positive") 

62 self.model, self.threshold, self.device = ( 

63 model or "yolo11n-seg.pt", 

64 threshold, 

65 device, 

66 ) 

67 self.resolution = resolution 

68 self._predictor = None 

69 

70 def resolved_device(self) -> str: 

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

72 from .rfdetr import _auto_device 

73 

74 return self.device or _auto_device() 

75 

76 def attributes_to_ignore(self): 

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

78 

79 def input_type(self) -> type: 

80 return Image 

81 

82 def output_type(self) -> type: 

83 return ImageSegmentation 

84 

85 @staticmethod 

86 def _progress(message): 

87 print(f"[YOLO Seg] {message}", flush=True) 

88 

89 def _label_prompts(self, samples): 

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

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

92 

93 def _model_path(self): 

94 path = Path(self.model).expanduser() 

95 if not path.is_absolute() and self.pipeline is not None: 

96 candidate = self.pipeline.path / path 

97 if candidate.is_file(): 

98 return str(candidate) 

99 if path.is_absolute() or path.parent != Path("."): 

100 if not path.is_file(): 

101 raise FileNotFoundError(path) 

102 return str(path) 

103 

104 def _init_model(self): 

105 if self._predictor is None: 

106 predictor = get_yolo_class()(self._model_path()) 

107 if predictor.task != "segment": 

108 raise ValueError( 

109 "ImageSegmenterYOLO requires a YOLO segmentation model (-seg)" 

110 ) 

111 self._predictor = predictor 

112 

113 @threading_locked() 

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

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

116 raise TypeError("YOLO segmentation requires one or more Image artefacts") 

117 self._init_model() 

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

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

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

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

122 results = [] 

123 for image in images: 

124 view = image.pil().convert("RGB") 

125 options = dict( 

126 conf=self.threshold, 

127 device=yolo_device(self.resolved_device()), 

128 retina_masks=True, 

129 verbose=False, 

130 ) 

131 if self.resolution is not None: 

132 options["imgsz"] = self.resolution 

133 (prediction,) = self._predictor.predict(view, **options) 

134 if prediction.masks is None: 

135 continue 

136 masks = prediction.masks.data.detach().cpu().numpy() 

137 classes = prediction.boxes.cls.detach().cpu().numpy().astype(int) 

138 if masks.shape != (len(classes), view.height, view.width): 

139 raise ValueError( 

140 "YOLO returned masks that do not match the input image view" 

141 ) 

142 for mask, class_id in zip(masks, classes): 

143 label = prediction.names[int(class_id)] 

144 if outputs: 

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

146 aliases.update( 

147 { 

148 prompt: item 

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

150 if item in outputs 

151 } 

152 ) 

153 label = aliases.get(label, label) 

154 if len(outputs) == 1 and len(prediction.names) == 1: 

155 label = outputs[0] 

156 if outputs and label not in outputs: 

157 continue 

158 pixels = mask_to_source(image, mask > 0.5) 

159 if not pixels.any(): 

160 continue 

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

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

163 results.append( 

164 ImageSegmentation( 

165 name=label, 

166 data=image.get_path(), 

167 mask=path, 

168 parents=[image.id], 

169 orientation=image.orientation, 

170 partition=image.partition, 

171 ) 

172 ) 

173 return results 

174 

175 @command 

176 def train( 

177 self, 

178 inputs: Annotated[ 

179 list[str], 

180 Arg( 

181 required=False, 

182 default=[], 

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

184 ), 

185 ], 

186 output: Annotated[ 

187 Path | None, 

188 Arg( 

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

190 ), 

191 ] = None, 

192 validation: Annotated[ 

193 str, 

194 Arg( 

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

196 ), 

197 ] = "", 

198 exclude: Annotated[ 

199 str, 

200 Arg( 

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

202 ), 

203 ] = "", 

204 epochs: Annotated[ 

205 int, 

206 Arg( 

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

208 ), 

209 ] = 20, 

210 batch: Annotated[ 

211 int, 

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

213 ] = 1, 

214 num_gpus: Annotated[ 

215 int, 

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

217 ] = 1, 

218 keep_log: Annotated[ 

219 bool, 

220 Arg( 

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

222 ), 

223 ] = True, 

224 reuse_data: Annotated[ 

225 bool, 

226 Arg( 

227 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." 

228 ), 

229 ] = False, 

230 wandb: Annotated[ 

231 bool, 

232 Arg( 

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

234 ), 

235 ] = False, 

236 max_items: Annotated[ 

237 int | None, 

238 Arg( 

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

240 ), 

241 ] = None, 

242 ) -> Path: 

243 """Fine-tune YOLO on mask annotations and adopt its best weights.""" 

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

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

246 if self.pipeline is None: 

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

248 if reuse_data and output is None: 

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

250 output = ( 

251 Path(output).expanduser().resolve() 

252 if output is not None 

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

254 ) 

255 dataset = output / "dataset" 

256 reuse_prepared = reuse_data and all( 

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

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

259 ) 

260 if not reuse_prepared: 

261 if max_items is not None and max_items < 1: 

262 raise ValueError("max_items must be positive") 

263 if not inputs: 

264 raise ValueError( 

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

266 ) 

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

268 self._progress( 

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

270 ) 

271 if reuse_prepared: 

272 self._progress( 

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

274 ) 

275 else: 

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

277 dataset = self.prepare_training_data( 

278 inputs, dataset, validation, exclude, max_items=max_items 

279 ) 

280 annotations = json.loads( 

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

282 ) 

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

284 raise ValueError( 

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

286 ) 

287 has_validation = bool( 

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

289 "images" 

290 ] 

291 ) 

292 device = yolo_device(self.resolved_device(), num_gpus) 

293 config = { 

294 "model": self._model_path(), 

295 "threshold": self.threshold, 

296 "dataset": str(dataset), 

297 "has_validation": has_validation, 

298 "wandb": wandb, 

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

300 "run_name": output.name, 

301 "params": { 

302 "data": str(output / "yolo-training.json"), 

303 "project": str(output.parent), 

304 "name": output.name, 

305 "exist_ok": True, 

306 "epochs": epochs, 

307 "batch": batch * num_gpus, 

308 "device": device, 

309 "imgsz": self.resolution or 640, 

310 "overlap_mask": False, 

311 "mask_ratio": 1, 

312 "close_mosaic": 0, 

313 "multi_scale": False, 

314 "plots": False, 

315 "save": True, 

316 "save_period": -1, 

317 "resume": False, 

318 }, 

319 } 

320 config_path = output / "yolo-training.json" 

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

322 self._progress( 

323 "Starting YOLO trainer (initial weights may download); trainer output follows" 

324 ) 

325 subprocess.run( 

326 [ 

327 sys.executable, 

328 "-u", 

329 "-c", 

330 "from collectra.tasks.image_segmentation.yolo_training import launch; import sys; launch(sys.argv[1])", 

331 str(config_path), 

332 ], 

333 check=True, 

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

335 ) 

336 checkpoint = output / "weights" / "best.pt" 

337 if not checkpoint.is_file(): 

338 raise FileNotFoundError( 

339 f"YOLO training produced no checkpoint at {checkpoint}" 

340 ) 

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

342 shutil.copy2(checkpoint, destination) 

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

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

345 self.pipeline.save(self.name) 

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

347 if not keep_log: 

348 shutil.rmtree(output) 

349 return destination 

350 

351 

352# The former name of ImageSegmenterYOLO. 

353ImageSegmentationYOLO = ImageSegmenterYOLO