Coverage for collectra/tasks/object_detection/rfdetr.py: 89.90%
307 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
1from __future__ import annotations
3import shutil
4from pathlib import Path
5from typing import Annotated, TYPE_CHECKING, Any
7from pydantic import Field
9from cappa import Arg
11from collectra.cli import command
12from .adaptation_commands import RFDETRAdaptationCommands
13from .base import (
14 Batch,
15 Epochs,
16 LearningRate,
17 ObjectDetector,
18 RunResolution,
19 Threshold,
20 TrainResolution,
21 WeightDecay,
22)
23from collectra.types.images import (
24 Image,
25 ImageCrop,
26 read_tiff_channels,
27)
28from collectra.utils import change_dir
30from ...logger import get_logger
31from ..base import Task
32from collectra.utils import threading_locked
33from ..machine_learning.class_names import (
34 read_class_names,
35 sidecar_candidates,
36 write_class_names,
37)
38from ..machine_learning.training import (
39 prepare_object_detection_inputs,
40 run_training_command,
41)
42from .coco_data import CocoDetectionData
43from .detr import DetectionTrainResult
45if TYPE_CHECKING:
46 from rfdetr.detr import RFDETR
48logger = get_logger(__name__)
50__all__ = ["ObjectDetectorRFDETR", "ObjectDetectionRFDETR"]
52_MODEL_VARIANTS = {
53 "base": "RFDETRBase",
54 "nano": "RFDETRNano",
55 "small": "RFDETRSmall",
56 "medium": "RFDETRMedium",
57 "large": "RFDETRLarge",
58 "xlarge": "RFDETRXLarge",
59 "2xlarge": "RFDETR2XLarge",
60}
63def __getattr__(name: str):
64 """Expose patchable backend classes without importing them during CLI help."""
65 if name == "RFDETR":
66 from rfdetr.detr import RFDETR
68 return RFDETR
69 if name in _MODEL_VARIANTS.values():
70 import rfdetr
72 return getattr(rfdetr, name)
73 raise AttributeError(name)
76def _backend_class(name: str):
77 return globals().get(name) or __getattr__(name)
80def class_head_size(model) -> int | None:
81 """The number of outputs of the model's last classification layer, if it has one.
83 RF-DETR gives that layer one output for each class plus one for the background.
84 """
85 head = getattr(
86 getattr(getattr(model, "model", None), "model", None), "class_embed", None
87 )
88 return getattr(head, "out_features", None)
91def load_rfdetr_model(model_path: str | Path) -> RFDETR:
92 from .rfdetr_channels import (
93 absolute_checkpoint,
94 multichannel_checkpoints,
95 sync_channels,
96 )
98 model_path = absolute_checkpoint(model_path)
100 # Fusion checkpoints retain a three-channel projection but consume many
101 # RGB views. Ordinary RF-DETR loading would silently discard fusion weights.
102 import torch
104 try:
105 checkpoint = torch.load(model_path, map_location="cpu", weights_only=True)
106 except Exception:
107 checkpoint = {}
108 if "backbone.0.encoder.fusion_spec" in checkpoint.get("model", {}):
109 from .rfdetr_feature_fusion import load_adapted_model
111 return load_adapted_model(model_path)
112 del checkpoint
114 errors = []
115 try:
116 # Resolves the model size from checkpoint metadata. The loader widens
117 # the input layer to the stored channel count; num_channels=3 stops
118 # RF-DETR from widening it a second time.
119 with multichannel_checkpoints():
120 model = _backend_class("RFDETR").from_checkpoint(
121 str(model_path), num_channels=3
122 )
123 if isinstance(model, _backend_class("RFDETR")):
124 sync_channels(model)
125 return model
126 except Exception as e:
127 errors.append(("RFDETR.from_checkpoint", str(e)))
129 # Fallback for checkpoints without metadata. RF-DETR loads non-strictly, so
130 # a smaller variant can "load" a larger checkpoint while dropping weights.
131 for class_name in _MODEL_VARIANTS.values():
132 try:
133 model_class = _backend_class(class_name)
134 with multichannel_checkpoints():
135 model = model_class(pretrain_weights=str(model_path))
136 sync_channels(model)
137 return model
138 except Exception as e:
139 errors.append((class_name, str(e)))
141 logger.error("Failed to load RF-DETR model from %s. Errors: %s", model_path, errors)
144class ObjectDetectorRFDETR(CocoDetectionData, RFDETRAdaptationCommands, ObjectDetector):
145 """RF-DETR task backed by the Roboflow rfdetr package."""
147 model: Any = None # a path or a loaded RF-DETR model
148 original_model_path: str | Path | None = None
149 batch_size: int = Field(default=1, ge=1)
151 def __init__(
152 self,
153 name: str,
154 model: str | Path | object | None = None,
155 **kwargs,
156 ):
157 super().__init__(name, model=model, **kwargs)
158 self._device = None
159 self._categories: list[str] = []
161 def _init_model(self, *, training: bool = False) -> None:
162 """Load the model; with ``training`` it is only a starting point."""
163 self._load(training=training)
165 if not isinstance(self.model, _backend_class("RFDETR")):
166 raise ValueError("Model must be an RFDETR instance")
168 def _reload(self) -> None:
169 if not self.original_model_path:
170 logger.warning("Original model path is not set. Skipping...")
171 return
173 self.model = load_rfdetr_model(self.original_model_path)
174 self._set_categories(Path(self.original_model_path))
176 def _load_categories_from_sidecar(self, checkpoint_path: Path) -> None:
177 classes = read_class_names(checkpoint_path)
178 if classes is not None:
179 self._categories = classes
181 def _output_names(self) -> list[str]:
182 """Names of this task's output nodes, in the order the pipeline lists them."""
183 pipeline = self.pipeline
184 if pipeline is None or not pipeline.node_manager.has_node(self.name):
185 return []
186 node = pipeline.node_manager.resolve_node(self.name)
187 return [str(output.name) for output in pipeline._output_nodes(node)]
189 def _set_categories(self, checkpoint_path: Path, *, training: bool = False) -> None:
190 """Name the model's classes: the pipeline's outputs, else the sidecar.
192 The pipeline is the source of truth. A sidecar that disagrees is warned
193 about and ignored. To predict, the last layer must fit the names.
194 Training replaces that layer, so a checkpoint used as its starting
195 point may have any number of classes.
196 """
197 self._load_categories_from_sidecar(checkpoint_path)
198 outputs = self._output_names()
199 if outputs:
200 if self._categories and self._categories != outputs:
201 logger.warning(
202 "Class names in the sidecar next to %s (%s) differ from the outputs "
203 "of task %r (%s); using the pipeline's outputs.",
204 checkpoint_path,
205 ", ".join(self._categories),
206 self.name,
207 ", ".join(outputs),
208 )
209 self._categories = outputs
210 size = class_head_size(self.model)
211 if self._categories and size is not None and size != len(self._categories) + 1:
212 if training:
213 logger.info(
214 "Checkpoint %s has %d classes; training replaces its last layer.",
215 checkpoint_path,
216 size - 1,
217 )
218 return
219 raise ValueError(
220 f"Task {self.name!r} has {len(self._categories)} output(s) "
221 f"({', '.join(self._categories)}) but the model has {size - 1} classes."
222 )
224 def _load(self, *, training: bool = False) -> None:
225 if isinstance(self.model, _backend_class("RFDETR")):
226 return
228 self._device = self._select_device()
230 variant = "base" if self.model is None else None
231 if isinstance(self.model, str):
232 name = self.model.lower()
233 if name == "default":
234 variant = "base"
235 elif name in _MODEL_VARIANTS:
236 variant = name
237 else:
238 variant = next(
239 (
240 key
241 for key, value in _MODEL_VARIANTS.items()
242 if value.lower() == name
243 ),
244 None,
245 )
246 if variant is not None:
247 self.model = _backend_class(_MODEL_VARIANTS[variant])()
248 self.original_model_path = None
249 from rfdetr.assets.coco_classes import COCO_CLASSES
251 self._categories = list(COCO_CLASSES)
252 return
254 if not isinstance(self.model, (str, Path)):
255 raise ValueError(
256 "Model must be None, 'default', a model variant name, "
257 "a checkpoint path, or an RFDETR instance"
258 )
260 checkpoint_path = Path(str(self.model))
261 if checkpoint_path.exists() and checkpoint_path.is_file():
262 self.original_model_path = checkpoint_path
263 self.model = load_rfdetr_model(self.original_model_path)
264 self._categories = []
265 self._set_categories(checkpoint_path, training=training)
266 candidates = sidecar_candidates(checkpoint_path)
267 if not self._categories and not any(c.exists() for c in candidates):
268 logger.warning(
269 "No classes sidecar found alongside checkpoint %s "
270 "(looked for %s); inference labels will fall back to "
271 "numeric class indices because no class metadata is available.",
272 checkpoint_path,
273 [str(c) for c in candidates],
274 )
275 return
277 raise ValueError(
278 f"Model path does not exist: {checkpoint_path}. "
279 "RF-DETR requires a valid checkpoint path, None/'default', "
280 f"or a model variant: {', '.join(_MODEL_VARIANTS)}."
281 )
283 def _tiff_tensor(self, image: Image):
284 """Read every channel of a TIFF image as a CHW float tensor in [0, 1]."""
285 import numpy as np
286 import torch
288 from .rfdetr_data import scale_tiff_pixels
290 pixels = read_tiff_channels(image.get_path())
291 if isinstance(image, ImageCrop):
292 left, top, right, bottom = image.coordinates()
293 if right <= left or bottom <= top:
294 raise ValueError(f"ImageCrop {image.id!r} produces an empty pixel crop")
295 pixels = pixels[top:bottom, left:right, :]
296 pixels = np.rot90(pixels, k=image.orientation.to_degree() // 90)
298 expected = self.model.model_config.num_channels
299 if pixels.shape[2] != expected:
300 raise ValueError(
301 f"{image.get_path()}: {pixels.shape[2]} image channels, "
302 f"but the detection model expects {expected}"
303 )
304 pixels = scale_tiff_pixels(pixels)
305 return torch.from_numpy(np.ascontiguousarray(pixels.transpose(2, 0, 1)))
307 @command(name="run")
308 def cli_run(
309 self,
310 inputs: list[str],
311 output: Path | None = None,
312 verbose: bool = False,
313 usage: bool = False,
314 render: bool = False,
315 model: Annotated[
316 Path | None,
317 Arg(help="Model checkpoint path. Omit to keep the configured model."),
318 ] = None,
319 resolution: RunResolution = None,
320 threshold: Threshold = None,
321 batch_size: Annotated[
322 int,
323 Arg(
324 help="Number of files to run through the model at once; results are saved after each batch."
325 ),
326 ] = 16,
327 force: Annotated[
328 bool,
329 Arg(
330 help="Rerun tasks whose outputs already exist, replacing those outputs. By default such tasks are skipped."
331 ),
332 ] = False,
333 ) -> None:
334 """Run this object detector for the supplied input files."""
335 if batch_size < 1:
336 raise ValueError("--batch-size must be at least 1")
337 if model is not None:
338 self.model = model
339 if resolution is not None:
340 self.resolution = resolution
341 if threshold is not None:
342 self.threshold = threshold
343 self.batch_size = batch_size
344 super().cli_run(
345 inputs,
346 output=output,
347 verbose=verbose,
348 usage=usage,
349 render=render,
350 force=force,
351 )
353 def _predict(self, images: list[Image]) -> list[tuple]:
354 """Run the model over ``images`` together as ``(detections, width, height)``."""
355 threshold = self.threshold
356 inputs = []
357 sizes = []
358 for image in images:
359 if image.get_path().suffix.lower() in {".tif", ".tiff"}:
360 model_input = self._tiff_tensor(image)
361 height, width = model_input.shape[1:]
362 else:
363 model_input = image.pil().convert("RGB")
364 width, height = model_input.size
365 inputs.append(model_input)
366 sizes.append((width, height))
368 kwargs = {}
369 resolution = self.inference_resolution
370 if resolution is not None:
371 kwargs["shape"] = (int(resolution), int(resolution))
372 detections = self.model.predict(
373 inputs if len(inputs) > 1 else inputs[0],
374 threshold=threshold,
375 include_source_image=False,
376 **kwargs,
377 )
378 if not isinstance(detections, list):
379 detections = [detections]
380 return [(d, w, h) for d, (w, h) in zip(detections, sizes)]
382 def _predict_batch(self, images: list[Image]) -> list[tuple]:
383 return self._predict(images)
385 def _before_prefetch(self) -> None:
386 logger.info(
387 "RF-DETR inference resolution: %s",
388 self.inference_resolution
389 or getattr(self.model.model_config, "resolution", "model default"),
390 )
392 @threading_locked()
393 def run(self, *args: Image) -> list[ImageCrop]:
394 if len(args) != 1:
395 raise ValueError("This task only supports a single Image input.")
396 if not isinstance(args[0], Image):
397 raise TypeError("Input must be an instance of Image.")
399 image = args[0]
400 self._init_model()
402 predicted = self._take_prefetched(image)
403 detections, width, height = predicted or self._predict([image])[0]
405 confidences = getattr(detections, "confidence", None)
406 results: list[ImageCrop] = []
407 for i in range(len(detections.xyxy)):
408 x1, y1, x2, y2 = detections.xyxy[i]
409 x1 = max(0.0, min(float(width), float(x1)))
410 x2 = max(0.0, min(float(width), float(x2)))
411 y1 = max(0.0, min(float(height), float(y1)))
412 y2 = max(0.0, min(float(height), float(y2)))
414 bbox_width = x2 - x1
415 bbox_height = y2 - y1
416 if bbox_width <= 0 or bbox_height <= 0:
417 continue
419 x_center = (x1 + x2) / 2.0 / width
420 y_center = (y1 + y2) / 2.0 / height
421 width_relative = bbox_width / width
422 height_relative = bbox_height / height
424 class_idx = int(detections.class_id[i])
425 class_name = (
426 self._categories[class_idx]
427 if 0 <= class_idx < len(self._categories)
428 else str(class_idx)
429 )
431 results.append(
432 image.make_crop(
433 x_center=x_center,
434 y_center=y_center,
435 width_relative=width_relative,
436 height_relative=height_relative,
437 confidence=(
438 float(confidences[i]) if confidences is not None else None
439 ),
440 orientation=image.orientation,
441 name=class_name,
442 )
443 )
445 print(f"Found {len(results)} objects in the image.")
446 return self._orient_crops(results)
448 def _prepare_params(self, **kwargs) -> dict:
449 params = {
450 "epochs": int(kwargs.get("epochs", 1)),
451 "batch_size": int(kwargs.get("batch", 4)),
452 "grad_accum_steps": int(kwargs.get("grad_accum_steps", 4)),
453 "lr": float(kwargs.get("lr", 1e-4)),
454 "lr_encoder": float(kwargs.get("lr_encoder", 1.5e-4)),
455 "lr_vit_layer_decay": float(kwargs.get("lr_vit_layer_decay", 0.8)),
456 "lr_component_decay": float(kwargs.get("lr_component_decay", 0.7)),
457 "warmup_epochs": float(kwargs.get("warmup_epochs", 0.0)),
458 "weight_decay": float(kwargs.get("weight_decay", 1e-4)),
459 "drop_path": float(kwargs.get("drop_path", 0.0)),
460 "multi_scale": bool(kwargs.get("multi_scale", True)),
461 "expanded_scales": bool(kwargs.get("expanded_scales", True)),
462 "do_random_resize_via_padding": bool(
463 kwargs.get("do_random_resize_via_padding", False)
464 ),
465 "augmentation_backend": kwargs.get("augmentation_backend", "cpu"),
466 "use_ema": bool(kwargs.get("use_ema", True)),
467 "ema_decay": float(kwargs.get("ema_decay", 0.993)),
468 "ema_tau": int(kwargs.get("ema_tau", 100)),
469 "ema_update_interval": int(kwargs.get("ema_update_interval", 1)),
470 "output_dir": str(kwargs["output_dir"]),
471 "wandb": bool(kwargs.get("wandb", False)),
472 "project": kwargs.get("project", "runs/rfdetr"),
473 "run": kwargs.get("log", "rfdetr-run"),
474 "early_stopping": bool(kwargs.get("early_stopping", False)),
475 "early_stopping_patience": int(kwargs.get("early_stopping_patience", 10)),
476 "early_stopping_min_delta": float(
477 kwargs.get("early_stopping_min_delta", 0.001)
478 ),
479 "early_stopping_use_ema": bool(kwargs.get("early_stopping_use_ema", False)),
480 }
482 resolution = kwargs.get("resolution")
483 if resolution is not None:
484 params["resolution"] = int(resolution)
486 augmentation = kwargs.get("augmentation", "default").lower()
487 if augmentation != "default":
488 preset_names = {
489 "none",
490 "conservative",
491 "aggressive",
492 "aerial",
493 "industrial",
494 }
495 if augmentation not in preset_names:
496 raise ValueError(
497 "augmentation must be one of: default, none, conservative, "
498 "aggressive, aerial, industrial"
499 )
500 from rfdetr.datasets.aug_configs import (
501 AUG_AERIAL,
502 AUG_AGGRESSIVE,
503 AUG_CONSERVATIVE,
504 AUG_INDUSTRIAL,
505 )
507 presets = {
508 "none": {},
509 "conservative": AUG_CONSERVATIVE,
510 "aggressive": AUG_AGGRESSIVE,
511 "aerial": AUG_AERIAL,
512 "industrial": AUG_INDUSTRIAL,
513 }
514 params["aug_config"] = presets[augmentation]
515 return params
517 def _train_fold(
518 self,
519 train_samples: list[dict],
520 val_samples: list[dict],
521 classes: list[str],
522 log: Path,
523 kwargs: dict,
524 ) -> DetectionTrainResult:
526 weights_dir = log / "weights"
527 weights_dir.mkdir(parents=True, exist_ok=True)
529 dataset_dir = log / "dataset"
530 dataset_dir.mkdir(parents=True, exist_ok=True)
531 self._write_coco_dataset(
532 train_samples,
533 val_samples,
534 classes,
535 dataset_dir,
536 rgb=kwargs.get("rgb", False),
537 )
539 params_kwargs = dict(kwargs)
540 params_kwargs["log"] = f"{log.name}"
541 params_kwargs["output_dir"] = str(weights_dir)
542 params = self._prepare_params(**params_kwargs)
543 has_tiffs = any(
544 Path(sample["image_path"]).suffix.lower() in {".tif", ".tiff"}
545 for sample in [*train_samples, *val_samples]
546 )
547 if has_tiffs:
548 from .rfdetr_channels import require_multichannel_rfdetr
550 require_multichannel_rfdetr()
551 if has_tiffs and params["augmentation_backend"] != "torchvision":
552 # Albumentations round-trips through PIL; the GPU path uses
553 # three-channel normalization outside our dataset patch. "auto"
554 # can select either path, so TIFFs must explicitly use torchvision.
555 logger.info("TIFF inputs: using the torchvision augmentation backend")
556 params["augmentation_backend"] = "torchvision"
558 from .rfdetr_channels import multichannel_checkpoints
559 from .rfdetr_data import multichannel_datasets
560 from .rfdetr_curves import wandb_detection_curves
562 model = self.model
563 with (
564 multichannel_datasets(),
565 multichannel_checkpoints(),
566 wandb_detection_curves(params["wandb"] and bool(val_samples), log, classes),
567 ):
568 model.train(
569 dataset_dir=str(dataset_dir),
570 **params,
571 )
573 self._categories = classes
574 self.model = model
576 # Persist class names alongside checkpoint for later reloading
577 write_class_names(weights_dir / "classes.yaml", classes)
579 # RF-DETR's total checkpoint selects the validation winner across
580 # regular and EMA weights. Prefer it so best.pt keeps that winner.
581 best_pt = weights_dir / "best.pt"
582 for candidate in [
583 weights_dir / "checkpoint_best_total.pth",
584 weights_dir / "checkpoint_best_regular.pth",
585 ]:
586 if candidate.exists():
587 shutil.copy2(candidate, best_pt)
588 break
590 if best_pt.exists():
591 self.original_model_path = best_pt
592 self._reload()
594 best_metrics = {"status": "completed", "classes": classes}
596 logger.info("RF-DETR training completed. Weights saved to: %s", weights_dir)
597 return DetectionTrainResult(save_dir=log, results_dict=best_metrics)
599 @command
600 def train(
601 self,
602 inputs: Annotated[
603 list[str],
604 Arg(
605 help="Pipeline data files or directories containing training annotations."
606 ),
607 ],
608 output: Annotated[
609 Path | None,
610 Arg(help="Directory for training logs, dataset files, and checkpoints."),
611 ] = None,
612 keep_log: Annotated[
613 bool,
614 Arg(
615 help="Keep the training directory after saving the model to the pipeline."
616 ),
617 ] = True,
618 validation: Annotated[
619 str,
620 Arg(help="Partition value identifying validation examples."),
621 ] = "",
622 exclude: Annotated[
623 str,
624 Arg(help="Partition value identifying examples to exclude from training."),
625 ] = "",
626 epochs: Epochs = None,
627 batch: Batch = None,
628 grad_accum_steps: Annotated[
629 int,
630 Arg(
631 help="Accumulate gradients over this many batches before an optimizer step."
632 ),
633 ] = 4,
634 learning_rate: LearningRate = None,
635 rgb: Annotated[
636 bool,
637 Arg(
638 help="Convert all prepared training images to 3-channel RGB, so images with differing channel counts (grayscale, RGBA) can be trained together."
639 ),
640 ] = False,
641 wandb: Annotated[
642 bool,
643 Arg(help="Log training metrics to Weights & Biases."),
644 ] = False,
645 early_stopping: Annotated[
646 bool,
647 Arg(help="Stop training when validation performance stops improving."),
648 ] = False,
649 weight_decay: WeightDecay = None,
650 drop_path: Annotated[
651 float,
652 Arg(help="Stochastic depth drop probability used for regularization."),
653 ] = 0.0,
654 augmentation: Annotated[
655 str,
656 Arg(
657 help="Augmentation preset: default, none, conservative, aggressive, aerial, or industrial."
658 ),
659 ] = "default",
660 augmentation_backend: Annotated[
661 str,
662 Arg(help="Augmentation execution backend: cpu, auto, or gpu."),
663 ] = "cpu",
664 multi_scale: Annotated[
665 bool,
666 Arg(help="Train with multiple image resolutions."),
667 ] = True,
668 expanded_scales: Annotated[
669 bool,
670 Arg(help="Use an expanded range of resolutions for multi-scale training."),
671 ] = True,
672 do_random_resize_via_padding: Annotated[
673 bool,
674 Arg(help="Use padding for random image resizing."),
675 ] = False,
676 use_ema: Annotated[
677 bool,
678 Arg(help="Maintain an exponential moving average (EMA) of model weights."),
679 ] = True,
680 ema_decay: Annotated[
681 float,
682 Arg(
683 help="Decay factor for the exponential moving average of model weights."
684 ),
685 ] = 0.993,
686 ema_tau: Annotated[
687 int,
688 Arg(help="Time constant controlling the warmup of EMA decay."),
689 ] = 100,
690 ema_update_interval: Annotated[
691 int,
692 Arg(help="Number of optimizer steps between EMA updates."),
693 ] = 1,
694 early_stopping_patience: Annotated[
695 int,
696 Arg(
697 help="Number of validation checks without sufficient improvement before stopping."
698 ),
699 ] = 10,
700 early_stopping_min_delta: Annotated[
701 float,
702 Arg(help="Minimum improvement required to reset early-stopping patience."),
703 ] = 0.001,
704 early_stopping_use_ema: Annotated[
705 bool,
706 Arg(help="Use EMA model metrics for early stopping."),
707 ] = False,
708 lr_encoder: Annotated[
709 float,
710 Arg(help="Learning rate for the image encoder."),
711 ] = 1.5e-4,
712 lr_vit_layer_decay: Annotated[
713 float,
714 Arg(
715 help="Layer-wise learning-rate decay factor for the vision transformer."
716 ),
717 ] = 0.8,
718 lr_component_decay: Annotated[
719 float,
720 Arg(help="Learning-rate decay factor for encoder components."),
721 ] = 0.7,
722 warmup_epochs: Annotated[
723 float,
724 Arg(
725 help="Number of epochs for learning-rate warmup; fractional values are allowed."
726 ),
727 ] = 0.0,
728 model: Annotated[
729 str,
730 Arg(
731 help="Checkpoint path or pretrained variant: nano, small, base, medium, large, xlarge, or 2xlarge (full RFDETR class names also accepted). XL variants require rfdetr[plus]. 'default' selects Base; omit to keep the configured model."
732 ),
733 ] = "",
734 resolution: TrainResolution = None,
735 max_items: Annotated[
736 int,
737 Arg(
738 help="Use at most this many images in each of the training and validation sets (0 uses all); for quick tests."
739 ),
740 ] = 0,
741 ):
742 """Train this RF-DETR object detector."""
743 settings = self._settings_for_run(
744 epochs=epochs,
745 batch=batch,
746 learning_rate=learning_rate,
747 weight_decay=weight_decay,
748 resolution=resolution,
749 )
750 return run_training_command(
751 self,
752 inputs,
753 self._train,
754 keep_log=keep_log,
755 output=output,
756 validation=validation,
757 exclude=exclude,
758 prepare_inputs=prepare_object_detection_inputs,
759 include_unlabelled=True,
760 epochs=settings["epochs"],
761 batch=settings["batch"],
762 grad_accum_steps=grad_accum_steps,
763 lr=settings["learning_rate"],
764 rgb=rgb,
765 wandb=wandb,
766 early_stopping=early_stopping,
767 weight_decay=settings["weight_decay"],
768 drop_path=drop_path,
769 augmentation=augmentation,
770 augmentation_backend=augmentation_backend,
771 multi_scale=multi_scale,
772 expanded_scales=expanded_scales,
773 do_random_resize_via_padding=do_random_resize_via_padding,
774 use_ema=use_ema,
775 ema_decay=ema_decay,
776 ema_tau=ema_tau,
777 ema_update_interval=ema_update_interval,
778 early_stopping_patience=early_stopping_patience,
779 early_stopping_min_delta=early_stopping_min_delta,
780 early_stopping_use_ema=early_stopping_use_ema,
781 lr_encoder=lr_encoder,
782 lr_vit_layer_decay=lr_vit_layer_decay,
783 lr_component_decay=lr_component_decay,
784 warmup_epochs=warmup_epochs,
785 model=model,
786 resolution=settings["resolution"],
787 max_items=max_items,
788 )
790 def _train(self, *images: ImageCrop, **kwargs) -> DetectionTrainResult:
791 if kwargs.get("model"):
792 self.model = kwargs["model"]
794 self._init_model(training=True)
795 log = kwargs.get("log", None)
796 if log is None:
797 raise ValueError(
798 "Log directory must be specified in kwargs with key 'log'."
799 )
800 if "base_folder" not in kwargs:
801 raise ValueError(
802 "Base folder must be specified in kwargs with key 'base_folder'."
803 )
805 log = kwargs["base_folder"] / log
806 log.mkdir(parents=True, exist_ok=True)
807 print(f"Training files will be saved to: {log}")
809 classes = kwargs.get("classes", [])
810 if not classes:
811 classes = sorted({img.name for img in images if isinstance(img, ImageCrop)})
812 if not classes:
813 raise ValueError("No classes provided/found for RF-DETR training.")
815 print("Training with model: RF-DETR")
817 validation = kwargs.get("validation", "")
818 exclude = kwargs.get("exclude", "")
819 train_samples, val_samples = self._prepare_assets(
820 classes,
821 validation,
822 exclude,
823 *images,
824 )
825 max_items = int(kwargs.get("max_items", 0) or 0)
826 if max_items > 0:
827 train_samples = train_samples[:max_items]
828 val_samples = val_samples[:max_items]
829 print(
830 f"Limiting to {len(train_samples)} training and "
831 f"{len(val_samples)} validation images (max_items={max_items})"
832 )
833 self._check_distribution(classes, train_samples, val_samples)
835 with change_dir(kwargs["base_folder"]):
836 results = self._train_fold(train_samples, val_samples, classes, log, kwargs)
838 print(
839 f"Best RF-DETR model saved to: {results.save_dir / 'weights' / 'best.pt'}"
840 )
841 return results
844# The former name of ObjectDetectorRFDETR.
845ObjectDetectionRFDETR = ObjectDetectorRFDETR