Coverage for collectra/tasks/object_detection/rfdetr_input_adaptation.py: 79.76%
84 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"""Adapt RGB RF-DETR checkpoints to concatenated aligned views."""
3from pathlib import Path
5import torch
7from .rfdetr_channels import absolute_checkpoint
10def _patch_embeddings(detector):
11 try:
12 embeddings = detector.model.model.backbone[
13 0
14 ].encoder.encoder.embeddings.patch_embeddings
15 except (AttributeError, IndexError, TypeError) as exc:
16 raise RuntimeError(
17 "Could not locate RF-DETR's DINOv2 patch embeddings."
18 ) from exc
19 if not isinstance(embeddings.projection, torch.nn.Conv2d):
20 raise RuntimeError("Expected the patch projection to be torch.nn.Conv2d.")
21 return embeddings
24def _expand_model(detector, num_views: int) -> None:
25 if num_views < 1:
26 raise ValueError("num_views must be >= 1")
27 embeddings = _patch_embeddings(detector)
28 old_conv = embeddings.projection
29 if old_conv.in_channels != 3:
30 raise ValueError(
31 "Expected a 3-channel pretrained model, but the patch projection "
32 f"has {old_conv.in_channels} input channels."
33 )
34 if old_conv.groups != 1:
35 raise RuntimeError("Grouped input convolutions are not supported.")
37 channels = 3 * num_views
38 new_conv = torch.nn.Conv2d(
39 channels,
40 old_conv.out_channels,
41 kernel_size=old_conv.kernel_size,
42 stride=old_conv.stride,
43 padding=old_conv.padding,
44 dilation=old_conv.dilation,
45 groups=old_conv.groups,
46 bias=old_conv.bias is not None,
47 padding_mode=old_conv.padding_mode,
48 ).to(device=old_conv.weight.device, dtype=old_conv.weight.dtype)
49 with torch.no_grad():
50 new_conv.weight.copy_(old_conv.weight.repeat(1, num_views, 1, 1) / num_views)
51 if old_conv.bias is not None:
52 new_conv.bias.copy_(old_conv.bias)
53 new_conv.weight.requires_grad_(old_conv.weight.requires_grad)
54 if old_conv.bias is not None:
55 new_conv.bias.requires_grad_(old_conv.bias.requires_grad)
56 new_conv.train(old_conv.training)
57 embeddings.projection = new_conv
58 # DINOv2 checks this attribute before calling the convolution.
59 embeddings.num_channels = channels
60 detector.model.model.backbone[0].encoder.encoder.config.num_channels = channels
61 detector.model_config.num_channels = channels
62 detector.model.args.num_channels = channels
63 detector.means = list(detector.means[:3]) * num_views
64 detector.stds = list(detector.stds[:3]) * num_views
67def expand_rfdetr_input_channels(
68 input_model: Path,
69 output_model: Path,
70 num_views: int,
71 variant: str | None = None,
72) -> None:
73 """Save expanded model weights and reconstruction metadata (no optimizer)."""
74 if num_views < 1:
75 raise ValueError("num_views must be >= 1")
76 import rfdetr
78 if variant is None:
79 try:
80 detector = rfdetr.RFDETR.from_checkpoint(
81 absolute_checkpoint(input_model), device="cpu"
82 )
83 except (KeyError, ValueError) as exc:
84 raise ValueError(
85 "Could not reconstruct the input checkpoint automatically. "
86 "Use --variant with its model size, e.g. --variant nano. "
87 f"RF-DETR reported: {exc}"
88 ) from exc
89 else:
90 variants = {
91 "nano": "RFDETRNano",
92 "small": "RFDETRSmall",
93 "medium": "RFDETRMedium",
94 "base": "RFDETRBase",
95 "large": "RFDETRLarge",
96 "xlarge": "RFDETRXLarge",
97 "2xlarge": "RFDETR2XLarge",
98 }
99 name = variants.get(variant.lower(), variant)
100 model_class = getattr(rfdetr, name, None)
101 if model_class is None or not name.startswith("RFDETR"):
102 raise ValueError(f"Unknown or unavailable RF-DETR variant: {variant}")
103 detector = model_class(
104 pretrain_weights=absolute_checkpoint(input_model), device="cpu"
105 )
107 _expand_model(detector, num_views)
108 config = detector.model_config.model_dump(mode="json")
109 args = dict(config)
110 args["class_names"] = list(detector.model.class_names or [])
111 checkpoint = {
112 "model": detector.model.model.state_dict(),
113 "model_name": type(detector).__name__,
114 "model_config": config,
115 "args": args,
116 "multichannel": {
117 "num_views": num_views,
118 "num_channels": 3 * num_views,
119 "means": detector.means,
120 "stds": detector.stds,
121 },
122 }
123 output_model.parent.mkdir(parents=True, exist_ok=True)
124 torch.save(checkpoint, output_model)
127def load_adapted_model(output_model: Path, device: str = "cpu"):
128 """Reconstruct a checkpoint produced here, expanding before loading weights.
130 Returns the RF-DETR wrapper, including repeated RGB normalization statistics.
131 Use CHW tensors with 3 * num_views channels for prediction.
132 """
133 import rfdetr
135 checkpoint = torch.load(output_model, map_location="cpu", weights_only=True)
136 metadata = checkpoint["multichannel"]
137 num_views = metadata["num_views"]
138 if num_views < 1 or metadata["num_channels"] != 3 * num_views:
139 raise ValueError("Inconsistent multichannel checkpoint metadata.")
140 config = dict(checkpoint["model_config"])
141 # Avoid the upstream order: loading expanded weights into an RGB layer.
142 config.update(pretrain_weights=None, num_channels=3, device=device)
143 model_class = getattr(rfdetr, checkpoint["model_name"])
144 detector = model_class(**config)
145 _expand_model(detector, num_views)
146 detector.model.model.load_state_dict(checkpoint["model"], strict=True)
147 detector.model.class_names = checkpoint["args"].get("class_names", [])
148 detector.means = list(metadata["means"])
149 detector.stds = list(metadata["stds"])
150 return detector
153def validate_saved_model(output_model: Path, expected_channels: int) -> None:
154 reloaded = load_adapted_model(output_model)
155 embeddings = _patch_embeddings(reloaded)
156 conv = embeddings.projection
157 if conv.in_channels != expected_channels:
158 raise RuntimeError(
159 f"Reloaded model has {conv.in_channels} input channels; "
160 f"expected {expected_channels}."
161 )
162 # Exercise the channel guard as well as the convolution after strict reload.
163 with torch.no_grad():
164 embeddings(torch.zeros(1, expected_channels, *conv.kernel_size))