Coverage for collectra/tasks/object_detection/rfdetr_channels.py: 92.77%
83 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"""Load and train RF-DETR checkpoints whose input layer has more than three channels.
3RF-DETR loads checkpoint weights into a 3-channel model and only afterwards
4widens the input layer to ``num_channels``, so a checkpoint whose input layer is
5already wider (e.g. one written by the ``adapt-input-channels`` task command or by multi-channel
6training) cannot be loaded through ``pretrain_weights``. Its Lightning training
7module also never widens the input layer at all.
9``multichannel_checkpoints()`` wraps ``load_pretrain_weights`` so the model's
10patch projection is resized to the checkpoint's channel count before loading,
11and, for training, widened to ``model_config.num_channels`` afterwards using
12RF-DETR's own filter repetition.
13"""
15from __future__ import annotations
17import contextlib
18import copy
19import os
20from typing import Iterator
22import torch
24from .rfdetr_data import channel_stats
26PROJECTION_KEY = (
27 "backbone.0.encoder.encoder.embeddings.patch_embeddings.projection.weight"
28)
31MIN_RFDETR_VERSION = (1, 10, 1)
34def require_multichannel_rfdetr() -> None:
35 """Fail clearly on rfdetr releases whose data pipeline is PIL/RGB-only."""
36 from importlib.metadata import version
38 installed = version("rfdetr")
39 parts = tuple(int(p) for p in installed.split(".")[:3] if p.isdigit())
40 if parts < MIN_RFDETR_VERSION:
41 required = ".".join(map(str, MIN_RFDETR_VERSION))
42 raise RuntimeError(
43 f"Training RF-DETR on TIFF inputs requires rfdetr>={required}, "
44 f"but rfdetr {installed} is installed. Upgrade it, "
45 f"e.g. `pip install 'rfdetr[metrics,train,loggers]>={required}'`."
46 )
49def absolute_checkpoint(path) -> str:
50 """The checkpoint's path made absolute.
52 RF-DETR reads a bare filename as a file in its model cache directory
53 (``~/.roboflow/models``), not in the working directory, so a checkpoint
54 beside the pipeline file must be given with its directory.
55 """
56 return os.path.abspath(os.path.expanduser(str(path)))
59def _patch_embeddings(nn_model):
60 return nn_model.backbone[0].encoder.encoder.embeddings.patch_embeddings
63def checkpoint_channels(path) -> int:
64 """Input channels of a checkpoint's patch projection (3 if it cannot be read)."""
65 if path is None or not os.path.isfile(str(path)):
66 return 3
67 # RF-DETR checkpoints store their args as Python objects, as RF-DETR's
68 # own loader assumes when it reads the same file.
69 checkpoint = torch.load(str(path), map_location="cpu", weights_only=False)
70 state = checkpoint.get("model")
71 if state is None:
72 state = {
73 key.removeprefix("model.").removeprefix("_orig_mod."): value
74 for key, value in checkpoint.get("state_dict", {}).items()
75 }
76 weight = state.get(PROJECTION_KEY)
77 return 3 if weight is None else int(weight.shape[1])
80def set_input_channels(nn_model, channels: int) -> None:
81 """Widen or narrow the patch projection, repeating pretrained filters as RF-DETR does."""
82 from rfdetr.inference import _adapt_input_conv
84 embeddings = _patch_embeddings(nn_model)
85 projection = embeddings.projection
86 if projection.in_channels == channels:
87 return
88 if projection.in_channels != 3:
89 raise ValueError(
90 f"Cannot adapt a {projection.in_channels}-channel input layer to {channels} channels"
91 )
92 new_projection = copy.deepcopy(projection)
93 new_projection.in_channels = channels
94 new_projection.weight = torch.nn.Parameter(
95 _adapt_input_conv(channels, projection.weight),
96 requires_grad=projection.weight.requires_grad,
97 )
98 embeddings.projection = new_projection
99 embeddings.num_channels = channels
102def sync_channels(detector) -> int:
103 """Align an RFDETR wrapper's config and normalization with its input layer.
105 Wrappers without a DINOv2 patch projection (e.g. test doubles) are left unchanged.
106 """
107 try:
108 encoder = detector.model.model.backbone[0].encoder
109 channels = (
110 3 * encoder.num_views
111 if hasattr(encoder, "fusion_spec")
112 else _patch_embeddings(detector.model.model).projection.in_channels
113 )
114 except (AttributeError, IndexError, TypeError):
115 return getattr(getattr(detector, "model_config", None), "num_channels", 3)
116 detector.model_config.num_channels = channels
117 args = getattr(detector.model, "args", None)
118 if args is not None and hasattr(args, "num_channels"):
119 args.num_channels = channels
120 mean, std = channel_stats(channels)
121 detector.means, detector.stds = list(mean), list(std)
122 return channels
125def _channel_aware(load_pretrain_weights, widen_after: bool):
126 def load(nn_model, model_config, *args, **kwargs):
127 # Feature fusion processes each view with an RGB projection. Its builder
128 # installs the fusion modules before loading; never widen that projection.
129 if hasattr(nn_model.backbone[0].encoder, "fusion_spec"):
130 return load_pretrain_weights(nn_model, model_config, *args, **kwargs)
131 stored = checkpoint_channels(model_config.pretrain_weights)
132 if stored != 3:
133 set_input_channels(nn_model, stored)
134 result = load_pretrain_weights(nn_model, model_config, *args, **kwargs)
135 if widen_after and model_config.num_channels != 3:
136 set_input_channels(nn_model, model_config.num_channels)
137 return result
139 return load
142@contextlib.contextmanager
143def multichannel_checkpoints() -> Iterator[None]:
144 """Let RF-DETR load, and train from, checkpoints with any number of input channels."""
145 import rfdetr.inference as inference
147 # The inference builder widens the input layer itself after loading.
148 patches = [(inference, False)]
149 try:
150 import rfdetr.training.module_model as module_model
152 patches.append((module_model, True))
153 except ImportError:
154 pass
156 originals = [(module, module.load_pretrain_weights) for module, _ in patches]
157 for module, widen_after in patches:
158 module.load_pretrain_weights = _channel_aware(
159 module.load_pretrain_weights, widen_after
160 )
161 try:
162 yield
163 finally:
164 for module, original in originals:
165 module.load_pretrain_weights = original