Coverage for collectra/tasks/object_detection/rfdetr_feature_fusion.py: 88.29%
205 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"""Shared RGB DINOv2 encoding and attention pooling across aligned RGB views.
3Checkpoints use state dictionaries, never serialized Python model objects.
4The fusion specification is a persistent buffer, so upstream training/EMA
5checkpoints remain reconstructible even when custom top-level metadata is lost.
6"""
8from __future__ import annotations
10import contextlib
11from pathlib import Path
12import tempfile
13import types
15import torch
16from torch import nn
17from rfdetr.models.backbone.backbone import Backbone
18from rfdetr.models.backbone.dinov2 import DinoV2
20from .rfdetr_channels import absolute_checkpoint
22SPEC_KEY = "backbone.0.encoder.fusion_spec"
23FORMAT_VERSION = 1
26class ViewAttention(nn.Module):
27 """Reference-conditioned spatial attention over views, not over image pixels."""
29 def __init__(
30 self, channels: int, num_views: int, reference_view: int, hidden_dim: int
31 ):
32 super().__init__()
33 self.reference_view = reference_view
34 self.score = nn.Sequential(
35 nn.Linear(2 * channels, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, 1)
36 )
37 # Begin with uniform attention; the residual gate preserves RGB exactly.
38 nn.init.zeros_(self.score[-1].weight)
39 nn.init.zeros_(self.score[-1].bias)
40 self.view_bias = nn.Parameter(torch.zeros(num_views))
41 self.gate = nn.Parameter(torch.zeros(()))
43 def forward(self, views: torch.Tensor) -> torch.Tensor:
44 # B,V,C,H,W -> B,H,W,V,C. Attention is local to aligned positions.
45 features = views.permute(0, 3, 4, 1, 2)
46 reference = features[..., self.reference_view, :]
47 query = reference.unsqueeze(-2).expand_as(features)
48 logits = self.score(torch.cat((features, query), dim=-1)).squeeze(-1)
49 weights = (logits + self.view_bias).float().softmax(dim=-1).to(features.dtype)
50 pooled = (features * weights.unsqueeze(-1)).sum(dim=-2)
51 fused = reference + self.gate.tanh() * (pooled - reference)
52 return fused.permute(0, 3, 1, 2).contiguous()
55class MultiViewDinoV2(DinoV2):
56 def forward(self, pixels: torch.Tensor) -> list[torch.Tensor]:
57 if pixels.ndim != 4 or pixels.shape[1] != 3 * self.num_views:
58 raise ValueError(
59 f"Expected BCHW with {3 * self.num_views} channels; got {tuple(pixels.shape)}"
60 )
61 batch, _, height, width = pixels.shape
62 # One encoder invocation batches all views; parameters are shared.
63 rgb = pixels.reshape(batch * self.num_views, 3, height, width)
64 features = super().forward(rgb)
65 if len(features) != len(self.view_fusion):
66 raise RuntimeError(
67 "Encoder feature levels changed; cannot apply saved fusion modules"
68 )
69 return [
70 fusion(feature.reshape(batch, self.num_views, *feature.shape[1:]))
71 for feature, fusion in zip(features, self.view_fusion)
72 ]
74 def export(self) -> None:
75 raise NotImplementedError(
76 "Feature fusion currently supports eager prediction/training, not ONNX export"
77 )
80class FeatureFusionBackbone(Backbone):
81 def get_named_param_lr_pairs(self, args, prefix="backbone.0"):
82 pairs = super().get_named_param_lr_pairs(args, prefix)
83 # New fusion parameters must not inherit the tiny pretrained embedding LR.
84 for name, param in self.encoder.view_fusion.named_parameters():
85 pairs[f"{prefix}.encoder.view_fusion.{name}"] = {
86 "params": param,
87 "lr": args.lr,
88 "weight_decay": args.weight_decay,
89 }
90 return pairs
93def fusion_spec(state: dict) -> dict | None:
94 value = state.get(SPEC_KEY)
95 if value is None:
96 return None
97 # EMA can convert integer buffers to floats and introduce roundoff.
98 # Truncation would turn e.g. 24.999998 views into 24. The learned
99 # parameter shapes are authoritative for reconstruction, including older
100 # checkpoints whose specification has already been truncated.
101 version, views, reference, hidden = (round(v) for v in value.tolist())
102 prefix = "backbone.0.encoder.view_fusion.0."
103 if prefix + "view_bias" in state:
104 views = state[prefix + "view_bias"].shape[0]
105 if prefix + "score.0.weight" in state:
106 hidden = state[prefix + "score.0.weight"].shape[0]
107 if version != FORMAT_VERSION:
108 raise ValueError(f"Unsupported feature-fusion checkpoint version: {version}")
109 if views < 1 or not 0 <= reference < views or hidden < 1:
110 raise ValueError("Invalid feature-fusion checkpoint specification")
111 return {"num_views": views, "reference_view": reference, "hidden_dim": hidden}
114def install_feature_fusion(
115 nn_model, num_views: int, reference_view: int = 0, hidden_dim: int = 64
116) -> None:
117 if num_views < 1 or not 0 <= reference_view < num_views or hidden_dim < 1:
118 raise ValueError(
119 "Require num_views >= 1, 0 <= reference_view < num_views, hidden_dim >= 1"
120 )
121 backbone = nn_model.backbone[0]
122 encoder = backbone.encoder
123 if type(backbone) is not Backbone or type(encoder) is not DinoV2:
124 raise ValueError(
125 "Expected an unmodified RF-DETR DINOv2 backbone (LoRA/export/fusion wrappers are unsupported)"
126 )
127 projection = encoder.encoder.embeddings.patch_embeddings.projection
128 if projection.in_channels != 3:
129 raise ValueError(
130 "Feature fusion requires an RGB checkpoint, not an expanded input projection"
131 )
132 # Preserve every existing weight and key; only add fusion parameters/buffer.
133 encoder.__class__ = MultiViewDinoV2
134 backbone.__class__ = FeatureFusionBackbone
135 encoder.num_views = num_views
136 encoder.view_fusion = nn.ModuleList(
137 [
138 ViewAttention(channels, num_views, reference_view, hidden_dim)
139 for channels in encoder._out_feature_channels
140 ]
141 ).to(device=projection.weight.device, dtype=projection.weight.dtype)
142 encoder.register_buffer(
143 "fusion_spec",
144 torch.tensor(
145 [FORMAT_VERSION, num_views, reference_view, hidden_dim],
146 dtype=torch.int64,
147 device=projection.weight.device,
148 ),
149 )
150 encoder.view_fusion.train(encoder.training)
153def _sync(detector, spec: dict) -> None:
154 channels = 3 * spec["num_views"]
155 detector.model_config.num_channels = channels
156 detector.model.args.num_channels = channels
157 detector.means = [0.485, 0.456, 0.406] * spec["num_views"]
158 detector.stds = [0.229, 0.224, 0.225] * spec["num_views"]
159 detector.train = types.MethodType(_train_feature_fusion, detector)
162def adapt_model(
163 detector, num_views: int, reference_view: int = 0, hidden_dim: int = 64
164):
165 if detector.model_config.backbone_lora:
166 raise ValueError("LoRA backbones are not supported by feature fusion")
167 spec = dict(
168 num_views=num_views, reference_view=reference_view, hidden_dim=hidden_dim
169 )
170 install_feature_fusion(detector.model.model, **spec)
171 _sync(detector, spec)
172 return detector
175def save_adapted_model(detector, path: str | Path) -> None:
176 state = detector.model.model.state_dict()
177 spec = fusion_spec(state)
178 if spec is None:
179 raise ValueError("Model has no feature-fusion specification")
180 config = detector.model_config.model_dump(mode="json")
181 config["model_name"] = type(detector).__name__
182 args = dict(config, class_names=list(detector.model.class_names or []))
183 path = Path(path)
184 path.parent.mkdir(parents=True, exist_ok=True)
185 torch.save(
186 {
187 "model": state,
188 "model_name": type(detector).__name__,
189 "model_config": config,
190 "args": args,
191 "feature_fusion": spec,
192 },
193 path,
194 )
197def load_adapted_model(path: str | Path, device: str = "cpu"):
198 import rfdetr
200 checkpoint = torch.load(path, map_location="cpu", weights_only=True)
201 state = checkpoint["model"]
202 spec = fusion_spec(state)
203 if spec is None:
204 raise ValueError("Checkpoint is not an RF-DETR feature-fusion model")
205 args = checkpoint.get("args", {})
206 notes = args.get("notes") or {}
207 saved_config = checkpoint.get("model_config")
208 if saved_config is None and isinstance(notes, dict):
209 saved_config = notes.get("collectra_feature_fusion", {}).get("model_config")
210 if saved_config is None:
211 raise ValueError("Fusion checkpoint has no reconstruction config")
212 config = dict(saved_config)
213 name = checkpoint.get("model_name") or config.get("model_name")
214 if not isinstance(name, str) or not name.startswith("RFDETR"):
215 raise ValueError("Checkpoint has no RFDETR model class")
216 # Reconstruct RGB architecture before installing fusion. Never tile input weights.
217 config.update(pretrain_weights=None, num_channels=3, device=device)
218 config["num_classes"] = state["class_embed.weight"].shape[0] - 1
219 detector = getattr(rfdetr, name)(**config)
220 # Settings read from the checkpoint are not the user's choices. rfdetr only
221 # adapts a model to new training data (such as its number of classes) when
222 # the setting was not given explicitly, as its own from_checkpoint does.
223 detector.model_config.model_fields_set.difference_update(
224 set(config) - {"pretrain_weights", "num_channels", "device"}
225 )
226 adapt_model(detector, **spec)
227 detector.model.model.load_state_dict(state, strict=True)
228 detector.model.class_names = checkpoint.get("args", {}).get("class_names", [])
229 detector.model_config.pretrain_weights = str(Path(path).resolve())
230 return detector
233@contextlib.contextmanager
234def feature_fusion_training(spec: dict):
235 """Install fusion before upstream loads weights and creates the optimizer."""
236 import rfdetr.training.module_model as module_model
238 original = module_model.build_model_from_config
240 def build(model_config, *args, **kwargs):
241 model = original(model_config, *args, **kwargs)
242 install_feature_fusion(model, **spec)
243 # Upstream strips model_config from best_total. TrainConfig.notes lives
244 # inside args and survives stripping, including custom resolutions.
245 train_config = args[0] if args else kwargs.get("train_config")
246 if train_config is not None:
247 previous_notes = train_config.notes
248 notes = (
249 dict(previous_notes)
250 if isinstance(previous_notes, dict)
251 else (
252 {"user_notes": previous_notes} if previous_notes is not None else {}
253 )
254 )
255 notes["collectra_feature_fusion"] = {
256 "model_config": model_config.model_dump(mode="json"),
257 **spec,
258 }
259 train_config.notes = notes
260 return model
262 module_model.build_model_from_config = build
263 try:
264 yield
265 finally:
266 module_model.build_model_from_config = original
269def _train_feature_fusion(detector, **kwargs):
270 """Train the current fusion weights rather than an unmodified RGB rebuild."""
271 from rfdetr.detr import RFDETR
272 from .rfdetr_data import multichannel_datasets
273 from .rfdetr_channels import require_multichannel_rfdetr
275 require_multichannel_rfdetr()
276 spec = fusion_spec(detector.model.model.state_dict())
277 if spec is None:
278 raise ValueError("Missing feature-fusion specification")
279 # Runtime model-builder patches do not propagate to independently spawned ranks.
280 devices = kwargs.get("devices", 1)
281 strategy = kwargs.get("strategy", "auto")
282 if (
283 devices not in (1, "1")
284 or kwargs.get("num_nodes", 1) != 1
285 or strategy not in ("auto", "single_device")
286 ):
287 raise ValueError(
288 "Feature fusion currently supports single-device training only"
289 )
290 augmentation = kwargs.pop("augmentation", "default")
291 if augmentation not in ("default", "none"):
292 raise ValueError(
293 "Feature fusion supports default/none torchvision augmentation"
294 )
295 if kwargs.get("aug_config") not in (None, {}):
296 raise ValueError(
297 "Nonempty Albumentations presets cannot preserve multichannel TIFFs"
298 )
299 if augmentation == "none":
300 kwargs["aug_config"] = {}
301 kwargs["augmentation_backend"] = "torchvision"
302 kwargs.setdefault("devices", 1)
303 kwargs.setdefault("save_dataset_grids", False)
304 previous = detector.model_config.pretrain_weights
305 # RF-DETR constructs a separate training module. Snapshot current weights,
306 # including learned attention, so repeated training calls retain them.
307 with tempfile.TemporaryDirectory(prefix="rfdetr-feature-fusion-") as folder:
308 snapshot = Path(folder) / "initial.pth"
309 save_adapted_model(detector, snapshot)
310 detector.model_config.pretrain_weights = str(snapshot)
311 try:
312 with feature_fusion_training(spec), multichannel_datasets():
313 RFDETR.train(detector, **kwargs)
314 finally:
315 detector.model_config.pretrain_weights = previous
318def expand_rfdetr_feature_fusion(
319 input_model: Path,
320 output_model: Path,
321 num_views: int,
322 variant: str | None = None,
323 reference_view: int = 0,
324 hidden_dim: int = 64,
325):
326 import rfdetr
328 if variant is None:
329 detector = rfdetr.RFDETR.from_checkpoint(
330 absolute_checkpoint(input_model), device="cpu"
331 )
332 else:
333 names = {
334 "nano": "RFDETRNano",
335 "small": "RFDETRSmall",
336 "medium": "RFDETRMedium",
337 "base": "RFDETRBase",
338 "large": "RFDETRLarge",
339 "xlarge": "RFDETRXLarge",
340 "2xlarge": "RFDETR2XLarge",
341 }
342 name = names.get(variant.lower(), variant)
343 if not name.startswith("RFDETR") or not hasattr(rfdetr, name):
344 raise ValueError(f"Unknown RF-DETR variant: {variant}")
345 detector = getattr(rfdetr, name)(
346 pretrain_weights=absolute_checkpoint(input_model), device="cpu"
347 )
348 adapt_model(detector, num_views, reference_view, hidden_dim)
349 save_adapted_model(detector, output_model)
350 return detector
353def validate_saved_model(path: Path, expected_views: int) -> None:
354 import torch
356 detector = load_adapted_model(path)
357 encoder = detector.model.model.backbone[0].encoder
358 if encoder.num_views != expected_views:
359 raise RuntimeError("Reloaded view count does not match")
360 detector.model.model.eval()
361 # Exercise the real encoder/attention/projector rather than only inspecting weights.
362 block = detector.model_config.patch_size * detector.model_config.num_windows
363 with torch.no_grad():
364 features = encoder(torch.zeros(1, 3 * expected_views, block, block))
365 projected = detector.model.model.backbone[0].projector(features)
366 if not projected or any(not torch.isfinite(feature).all() for feature in projected):
367 raise RuntimeError("Feature-fusion forward produced invalid features")