Coverage for collectra/tasks/object_detection/detr.py: 41.16%

345 statements  

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

1from __future__ import annotations 

2 

3from pydantic import BaseModel, Field 

4 

5from collectra.commons import PositionalFields 

6from pathlib import Path 

7from typing import TYPE_CHECKING, Any 

8 

9from collectra.cli import command 

10from collectra.types.images import Image, ImageCrop, open_oriented 

11from collectra.utils import change_dir 

12 

13from ...logger import get_logger 

14from ..base import Task 

15from .base import ( 

16 Batch, 

17 Epochs, 

18 LearningRate, 

19 ObjectDetector, 

20 TrainResolution, 

21 WeightDecay, 

22) 

23from collectra.utils import threading_locked 

24from ..machine_learning.training import ( 

25 prepare_object_detection_inputs, 

26 print_distribution_table, 

27 run_training_command, 

28) 

29 

30if TYPE_CHECKING: 

31 from torch import nn 

32 

33logger = get_logger(__name__) 

34 

35__all__ = ["ObjectDetectorDETR", "ObjectDetectionDETR", "DetectionTrainResult"] 

36 

37 

38class DetectionTrainResult(PositionalFields, BaseModel): 

39 save_dir: Path 

40 results_dict: dict 

41 

42 

43class ObjectDetectorDETR(ObjectDetector): 

44 """DETR task backed by Hugging Face Transformers.""" 

45 

46 model: Any = None # a path or a loaded torch module 

47 original_model_path: str | Path | None = None 

48 batch: int = Field(default=2, ge=1) # DETR is memory hungry 

49 

50 def __init__( 

51 self, 

52 name: str, 

53 model: str | Path | nn.Module | None = None, 

54 **kwargs, 

55 ): 

56 super().__init__(name, model=model, **kwargs) 

57 self._device = None 

58 self._processor = None 

59 self._categories: list[str] = [] 

60 self._model_name = "facebook/detr-resnet-50" 

61 

62 def _load_processor(self, model_name: str, resolution: int | None): 

63 """The image processor, resizing to ``resolution`` when one is given.""" 

64 from transformers import DetrImageProcessor 

65 

66 kwargs = {} 

67 if resolution is not None: 

68 kwargs["size"] = {"shortest_edge": resolution, "longest_edge": resolution} 

69 return DetrImageProcessor.from_pretrained(model_name, **kwargs) 

70 

71 def _init_model(self) -> None: 

72 from torch import nn 

73 

74 self._load() 

75 if not isinstance(self.model, nn.Module): 

76 raise ValueError("Model must be a torch.nn.Module instance") 

77 

78 def _reload(self) -> None: 

79 if not self.original_model_path: 

80 logger.warning("Original model path is not set. Skipping...") 

81 return 

82 self.model = self.original_model_path 

83 self._load() 

84 

85 def _load_model_from_hf(self, model_name: str) -> None: 

86 from transformers import DetrForObjectDetection, DetrImageProcessor 

87 

88 self._model_name = model_name 

89 self._processor = self._load_processor(model_name, self.inference_resolution) 

90 model = DetrForObjectDetection.from_pretrained(model_name) 

91 self._categories = [ 

92 model.config.id2label[i] for i in sorted(model.config.id2label.keys()) 

93 ] 

94 self.model = model.to(self._device) 

95 self.model.eval() 

96 

97 def _load_model_from_checkpoint(self, checkpoint_path: Path) -> None: 

98 import torch 

99 from transformers import DetrConfig, DetrForObjectDetection, DetrImageProcessor 

100 

101 checkpoint = torch.load(checkpoint_path, map_location=self._device) 

102 if isinstance(checkpoint, dict): 

103 state_dict = checkpoint.get("model_state_dict", checkpoint) 

104 classes = checkpoint.get("classes", []) 

105 model_name = checkpoint.get("model_name", self._model_name) 

106 else: 

107 state_dict = checkpoint 

108 classes = [] 

109 model_name = self._model_name 

110 

111 self._model_name = model_name 

112 self._processor = self._load_processor( 

113 self._model_name, self.inference_resolution 

114 ) 

115 

116 if classes: 

117 id2label = {idx: name for idx, name in enumerate(classes)} 

118 label2id = {name: idx for idx, name in enumerate(classes)} 

119 config = DetrConfig.from_pretrained( 

120 self._model_name, 

121 num_labels=len(classes), 

122 id2label=id2label, 

123 label2id=label2id, 

124 ) 

125 model = DetrForObjectDetection.from_pretrained( 

126 self._model_name, 

127 config=config, 

128 ignore_mismatched_sizes=True, 

129 ) 

130 self._categories = classes 

131 else: 

132 model = DetrForObjectDetection.from_pretrained(self._model_name) 

133 self._categories = [ 

134 model.config.id2label[i] for i in sorted(model.config.id2label.keys()) 

135 ] 

136 

137 model.load_state_dict(state_dict) 

138 model.to(self._device) 

139 model.eval() 

140 self.model = model 

141 

142 def _load(self) -> None: 

143 from torch import nn 

144 

145 if isinstance(self.model, nn.Module): 

146 if self._device is None: 

147 self._device = self._select_device() 

148 self.model.to(self._device) 

149 self.model.eval() 

150 return 

151 

152 self._device = self._select_device() 

153 

154 if self.model is None or ( 

155 isinstance(self.model, str) and self.model == "default" 

156 ): 

157 self._load_model_from_hf("facebook/detr-resnet-50") 

158 return 

159 

160 if not isinstance(self.model, (str, Path)): 

161 raise ValueError( 

162 "Model must be None, 'default', a path, a model id, or nn.Module" 

163 ) 

164 

165 model_value = str(self.model) 

166 checkpoint_path = Path(model_value) 

167 if checkpoint_path.exists() and checkpoint_path.is_file(): 

168 self.original_model_path = checkpoint_path 

169 self._load_model_from_checkpoint(checkpoint_path) 

170 return 

171 

172 # Treat as Hugging Face model id if local file path does not exist. 

173 self._load_model_from_hf(model_value) 

174 

175 @threading_locked() 

176 def run(self, *args: Image) -> list[ImageCrop]: 

177 import torch 

178 

179 if len(args) != 1: 

180 raise ValueError("This task only supports a single Image input.") 

181 if not isinstance(args[0], Image): 

182 raise TypeError("Input must be an instance of Image.") 

183 

184 image = args[0] 

185 self._init_model() 

186 from torch import nn 

187 

188 if not isinstance(self.model, nn.Module) or self._processor is None: 

189 raise ValueError("DETR model is not initialised properly.") 

190 

191 threshold = self.threshold 

192 pil_image = image.pil().convert("RGB") 

193 width, height = pil_image.size 

194 

195 inputs = self._processor(images=pil_image, return_tensors="pt") 

196 inputs = {k: v.to(self._device) for k, v in inputs.items()} 

197 

198 with torch.no_grad(): 

199 outputs = self.model(**inputs) 

200 

201 target_sizes = torch.tensor([[height, width]], device=self._device) 

202 processed = self._processor.post_process_object_detection( 

203 outputs, 

204 threshold=threshold, 

205 target_sizes=target_sizes, 

206 )[0] 

207 

208 detections: list[Image] = [] 

209 for box, label in zip(processed["boxes"], processed["labels"]): 

210 x1, y1, x2, y2 = box.detach().cpu().tolist() 

211 x1 = max(0.0, min(float(width), float(x1))) 

212 x2 = max(0.0, min(float(width), float(x2))) 

213 y1 = max(0.0, min(float(height), float(y1))) 

214 y2 = max(0.0, min(float(height), float(y2))) 

215 

216 bbox_width = x2 - x1 

217 bbox_height = y2 - y1 

218 if bbox_width <= 0 or bbox_height <= 0: 

219 continue 

220 

221 x_center = (x1 + x2) / 2.0 / width 

222 y_center = (y1 + y2) / 2.0 / height 

223 width_relative = bbox_width / width 

224 height_relative = bbox_height / height 

225 

226 class_idx = int(label.detach().cpu().item()) 

227 class_name = ( 

228 self._categories[class_idx] 

229 if 0 <= class_idx < len(self._categories) 

230 else str(class_idx) 

231 ) 

232 

233 detections.append( 

234 image.make_crop( 

235 x_center=x_center, 

236 y_center=y_center, 

237 width_relative=width_relative, 

238 height_relative=height_relative, 

239 orientation=image.orientation, 

240 name=class_name, 

241 ) 

242 ) 

243 

244 print(f"Found {len(detections)} objects in the image.") 

245 return self._orient_crops(detections) 

246 

247 def _prepare_params(self, **kwargs) -> dict: 

248 model_name = kwargs.get("model_name", self._model_name) 

249 if isinstance(self.model, str) and self.model not in ("", "default"): 

250 if not Path(self.model).exists(): 

251 model_name = self.model 

252 return { 

253 "name": kwargs["log"], 

254 "project": kwargs.get("project", "runs/detr"), 

255 "device": self._select_device(), 

256 "epochs": int(kwargs.get("epochs", 1)), 

257 "batch": int(kwargs.get("batch", 2)), 

258 "workers": int(kwargs.get("workers", 0)), 

259 "lr": float(kwargs.get("lr", 1e-4)), 

260 "weight_decay": float(kwargs.get("weight_decay", 1e-4)), 

261 "pretrained": bool(kwargs.get("pretrained", True)), 

262 "model_name": model_name, 

263 } 

264 

265 def _check_distribution( 

266 self, 

267 classes: list[str], 

268 train_samples: list[dict], 

269 val_samples: list[dict], 

270 ) -> None: 

271 train_classes = {name: 0 for name in classes} 

272 val_classes = {name: 0 for name in classes} 

273 label_to_name = {index: name for index, name in enumerate(classes)} 

274 

275 for sample in train_samples: 

276 for label in sample["labels"]: 

277 class_name = label_to_name.get(label, "") 

278 if class_name: 

279 train_classes[class_name] += 1 

280 

281 for sample in val_samples: 

282 for label in sample["labels"]: 

283 class_name = label_to_name.get(label, "") 

284 if class_name: 

285 val_classes[class_name] += 1 

286 

287 print_distribution_table( 

288 "Class Distribution", classes, train_classes, val_classes 

289 ) 

290 

291 def _prepare_assets( 

292 self, 

293 classes: list[str], 

294 validation_flag: str, 

295 exclude_flag: str, 

296 *images: ImageCrop, 

297 ) -> tuple[list[dict], list[dict]]: 

298 class_to_idx = {name: idx for idx, name in enumerate(classes)} 

299 grouped: dict[Path, dict] = {} 

300 

301 for img in images: 

302 if exclude_flag and img.partition == exclude_flag: 

303 continue 

304 

305 base_img: Image | ImageCrop = img 

306 if isinstance(img, ImageCrop): 

307 if img.source_parent: 

308 base_img = img.source_parent 

309 if isinstance(img.source_parent, ImageCrop): 

310 img.set_rel_to_src_parent() 

311 

312 image_path = base_img.get_path() 

313 if image_path not in grouped: 

314 grouped[image_path] = { 

315 "image_path": image_path, 

316 "partition": img.partition, 

317 "boxes": [], 

318 "labels": [], 

319 } 

320 

321 if not isinstance(img, ImageCrop): 

322 continue 

323 if img.name not in class_to_idx: 

324 continue 

325 

326 width, height = base_img.width, base_img.height 

327 box_w = float(img.width_relative) * width 

328 box_h = float(img.height_relative) * height 

329 cx = float(img.x_center) * width 

330 cy = float(img.y_center) * height 

331 

332 x1 = max(0.0, cx - box_w / 2.0) 

333 y1 = max(0.0, cy - box_h / 2.0) 

334 x2 = min(float(width), cx + box_w / 2.0) 

335 y2 = min(float(height), cy + box_h / 2.0) 

336 if x2 <= x1 or y2 <= y1: 

337 continue 

338 

339 grouped[image_path]["boxes"].append([x1, y1, x2, y2]) 

340 grouped[image_path]["labels"].append(class_to_idx[img.name]) 

341 

342 train_samples: list[dict] = [] 

343 val_samples: list[dict] = [] 

344 for sample in grouped.values(): 

345 if validation_flag and sample["partition"] == validation_flag: 

346 val_samples.append(sample) 

347 elif not exclude_flag or sample["partition"] != exclude_flag: 

348 train_samples.append(sample) 

349 return train_samples, val_samples 

350 

351 def _train_fold( 

352 self, 

353 train_samples: list[dict], 

354 val_samples: list[dict], 

355 classes: list[str], 

356 log: Path, 

357 kwargs: dict, 

358 ) -> DetectionTrainResult: 

359 import torch 

360 from torch.utils.data import DataLoader, Dataset 

361 from transformers import DetrConfig, DetrForObjectDetection, DetrImageProcessor 

362 

363 params_kwargs = dict(kwargs) 

364 params_kwargs["log"] = f"{log.name}" 

365 params = self._prepare_params(**params_kwargs) 

366 self._device = params["device"] 

367 self._model_name = params["model_name"] 

368 

369 self._processor = self._load_processor(self._model_name, self.resolution) 

370 

371 class DetrDataset(Dataset): 

372 def __init__(self, samples: list[dict], processor: DetrImageProcessor): 

373 self.samples = samples 

374 self.processor = processor 

375 

376 def __len__(self): 

377 return len(self.samples) 

378 

379 def __getitem__(self, idx: int): 

380 sample = self.samples[idx] 

381 with open_oriented(sample["image_path"]).convert("RGB") as pil_image: 

382 annotations = { 

383 "image_id": idx, 

384 "annotations": [], 

385 } 

386 for box, label in zip(sample["boxes"], sample["labels"]): 

387 x1, y1, x2, y2 = box 

388 w = x2 - x1 

389 h = y2 - y1 

390 annotations["annotations"].append( 

391 { 

392 "bbox": [x1, y1, w, h], 

393 "category_id": int(label), 

394 "area": float(w * h), 

395 "iscrowd": 0, 

396 } 

397 ) 

398 

399 encoding = self.processor( 

400 images=pil_image, 

401 annotations=annotations, 

402 return_tensors="pt", 

403 ) 

404 

405 pixel_values = encoding["pixel_values"].squeeze(0) 

406 labels = encoding["labels"][0] 

407 return pixel_values, labels 

408 

409 def collate_fn(batch): 

410 import torch 

411 

412 pixel_values = [item[0] for item in batch] 

413 labels = [item[1] for item in batch] 

414 

415 max_h = max(pv.shape[1] for pv in pixel_values) 

416 max_w = max(pv.shape[2] for pv in pixel_values) 

417 batch_size = len(pixel_values) 

418 

419 pixel_values_padded = torch.zeros( 

420 (batch_size, 3, max_h, max_w), 

421 dtype=pixel_values[0].dtype, 

422 ) 

423 pixel_mask = torch.zeros((batch_size, max_h, max_w), dtype=torch.long) 

424 

425 for i, pv in enumerate(pixel_values): 

426 h, w = pv.shape[1], pv.shape[2] 

427 pixel_values_padded[i, :, :h, :w] = pv 

428 pixel_mask[i, :h, :w] = 1 

429 

430 return { 

431 "pixel_values": pixel_values_padded, 

432 "pixel_mask": pixel_mask, 

433 "labels": labels, 

434 } 

435 

436 train_loader = DataLoader( 

437 DetrDataset(train_samples, self._processor), 

438 batch_size=params["batch"], 

439 shuffle=True, 

440 num_workers=params["workers"], 

441 collate_fn=collate_fn, 

442 ) 

443 

444 val_loader = None 

445 if len(val_samples) > 0: 

446 val_loader = DataLoader( 

447 DetrDataset(val_samples, self._processor), 

448 batch_size=params["batch"], 

449 shuffle=False, 

450 num_workers=params["workers"], 

451 collate_fn=collate_fn, 

452 ) 

453 

454 id2label = {idx: name for idx, name in enumerate(classes)} 

455 label2id = {name: idx for idx, name in enumerate(classes)} 

456 

457 from torch import nn 

458 

459 if isinstance(self.model, nn.Module): 

460 model = self.model 

461 else: 

462 config = DetrConfig.from_pretrained( 

463 self._model_name, 

464 num_labels=len(classes), 

465 id2label=id2label, 

466 label2id=label2id, 

467 ) 

468 model = DetrForObjectDetection.from_pretrained( 

469 self._model_name, 

470 config=config, 

471 ignore_mismatched_sizes=True, 

472 ) 

473 

474 model.to(self._device) 

475 self.model = model 

476 self._categories = classes 

477 

478 optimizer = torch.optim.AdamW( 

479 model.parameters(), 

480 lr=params["lr"], 

481 weight_decay=params["weight_decay"], 

482 ) 

483 

484 best_score = float("inf") 

485 best_metrics: dict = {} 

486 weights_dir = log / "weights" 

487 weights_dir.mkdir(parents=True, exist_ok=True) 

488 

489 wandb_run = None 

490 if bool(kwargs.get("wandb", False)): 

491 try: 

492 import wandb 

493 

494 wandb_run = wandb.init( 

495 project=params["project"], 

496 name=params["name"], 

497 dir=str(kwargs["base_folder"]), 

498 config=params, 

499 reinit=True, 

500 ) 

501 except Exception as error: 

502 logger.warning("W&B init skipped: %s", error) 

503 

504 def move_labels_to_device(batch_labels: list[dict]) -> list[dict]: 

505 out = [] 

506 for label_dict in batch_labels: 

507 out.append({k: v.to(self._device) for k, v in label_dict.items()}) 

508 return out 

509 

510 def run_epoch(data_loader: DataLoader, train_mode: bool) -> float: 

511 if train_mode: 

512 model.train() 

513 else: 

514 model.eval() 

515 running_loss = 0.0 

516 running_count = 0 

517 

518 for batch in data_loader: 

519 pixel_values = batch["pixel_values"].to(self._device) 

520 pixel_mask = batch["pixel_mask"].to(self._device) 

521 labels = move_labels_to_device(batch["labels"]) 

522 

523 if train_mode: 

524 optimizer.zero_grad(set_to_none=True) 

525 

526 with torch.set_grad_enabled(train_mode): 

527 outputs = model( 

528 pixel_values=pixel_values, 

529 pixel_mask=pixel_mask, 

530 labels=labels, 

531 ) 

532 loss = outputs.loss 

533 if train_mode: 

534 loss.backward() 

535 optimizer.step() 

536 

537 running_loss += float(loss.detach().cpu().item()) 

538 running_count += 1 

539 

540 return running_loss / max(running_count, 1) 

541 

542 for epoch in range(params["epochs"]): 

543 train_loss = run_epoch(train_loader, train_mode=True) 

544 val_loss = run_epoch(val_loader, train_mode=False) if val_loader else None 

545 metric_to_track = val_loss if val_loss is not None else train_loss 

546 

547 epoch_metrics = {"epoch": epoch + 1, "train/loss": train_loss} 

548 if val_loss is not None: 

549 epoch_metrics["val/loss"] = val_loss 

550 

551 if metric_to_track < best_score: 

552 best_score = metric_to_track 

553 best_metrics = epoch_metrics.copy() 

554 torch.save( 

555 { 

556 "model_state_dict": model.state_dict(), 

557 "classes": classes, 

558 "epoch": epoch + 1, 

559 "metrics": epoch_metrics, 

560 "model_name": self._model_name, 

561 }, 

562 weights_dir / "best.pt", 

563 ) 

564 

565 if wandb_run is not None: 

566 wandb_run.log(epoch_metrics) 

567 

568 logger.info("DETR epoch %s metrics: %s", epoch + 1, epoch_metrics) 

569 

570 torch.save( 

571 { 

572 "model_state_dict": model.state_dict(), 

573 "classes": classes, 

574 "epoch": params["epochs"], 

575 "metrics": best_metrics, 

576 "model_name": self._model_name, 

577 }, 

578 weights_dir / "last.pt", 

579 ) 

580 

581 if wandb_run is not None: 

582 wandb_run.finish() 

583 

584 model.eval() 

585 self.original_model_path = weights_dir / "best.pt" 

586 self._reload() 

587 return DetectionTrainResult(save_dir=log, results_dict=best_metrics) 

588 

589 @command 

590 def train( 

591 self, 

592 inputs: list[str], 

593 output: Path | None = None, 

594 keep_log: bool = True, 

595 validation: str = "", 

596 exclude: str = "", 

597 epochs: Epochs = None, 

598 batch: Batch = None, 

599 workers: int = 0, 

600 learning_rate: LearningRate = None, 

601 weight_decay: WeightDecay = None, 

602 pretrained: bool = True, 

603 model_name: str = "facebook/detr-resnet-50", 

604 wandb: bool = False, 

605 resolution: TrainResolution = None, 

606 ): 

607 """Train this DETR object detector.""" 

608 settings = self._settings_for_run( 

609 epochs=epochs, 

610 batch=batch, 

611 learning_rate=learning_rate, 

612 weight_decay=weight_decay, 

613 resolution=resolution, 

614 ) 

615 return run_training_command( 

616 self, 

617 inputs, 

618 self._train, 

619 keep_log=keep_log, 

620 output=output, 

621 validation=validation, 

622 exclude=exclude, 

623 prepare_inputs=prepare_object_detection_inputs, 

624 include_unlabelled=True, 

625 epochs=settings["epochs"], 

626 batch=settings["batch"], 

627 workers=workers, 

628 lr=settings["learning_rate"], 

629 weight_decay=settings["weight_decay"], 

630 resolution=settings["resolution"], 

631 pretrained=pretrained, 

632 model_name=model_name, 

633 wandb=wandb, 

634 ) 

635 

636 def _train(self, *images: ImageCrop, **kwargs) -> DetectionTrainResult: 

637 log = kwargs.get("log", None) 

638 if log is None: 

639 raise ValueError( 

640 "Log directory must be specified in kwargs with key 'log'." 

641 ) 

642 if "base_folder" not in kwargs: 

643 raise ValueError( 

644 "Base folder must be specified in kwargs with key 'base_folder'." 

645 ) 

646 

647 log = kwargs["base_folder"] / log 

648 log.mkdir(parents=True, exist_ok=True) 

649 print(f"Training files will be saved to: {log}") 

650 

651 classes = kwargs.get("classes", []) 

652 if not classes: 

653 classes = sorted({img.name for img in images if isinstance(img, ImageCrop)}) 

654 if not classes: 

655 raise ValueError("No classes provided/found for DETR training.") 

656 

657 print("Training with model: DETR") 

658 

659 validation = kwargs.get("validation", "") 

660 exclude = kwargs.get("exclude", "") 

661 train_samples, val_samples = self._prepare_assets( 

662 classes, 

663 validation, 

664 exclude, 

665 *images, 

666 ) 

667 self._check_distribution(classes, train_samples, val_samples) 

668 

669 with change_dir(kwargs["base_folder"]): 

670 results = self._train_fold(train_samples, val_samples, classes, log, kwargs) 

671 

672 print(f"Best DETR model saved to: {results.save_dir / 'weights' / 'best.pt'}") 

673 return results 

674 

675 

676# The former name of ObjectDetectorDETR. 

677ObjectDetectionDETR = ObjectDetectorDETR