Coverage for collectra/tasks/image_classifier/torchvision_fusion.py: 100.00%
99 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 classifier encoding with spatial attention over stacked RGB views.
3Every view passes through one shared RGB encoder. Immediately before global
4pooling, softmax attention chooses how much each view contributes at each
5spatial position. No view is privileged: attention is conditioned on the mean
6of all views, so the prediction does not depend on the order of the views.
7"""
9import torch
10from torch import nn
12FORMAT_VERSION = 2
13PROBE_SIZE = 224
16def _take_projection(model):
17 """Separate the final linear projection without changing its input features."""
18 for name in ("fc", "classifier", "heads", "head"):
19 head = getattr(model, name, None)
20 if isinstance(head, nn.Linear):
21 setattr(model, name, nn.Identity())
22 return head
23 if isinstance(head, nn.Sequential):
24 projections = [
25 (path, layer)
26 for path, layer in head.named_modules()
27 if isinstance(layer, (nn.Linear, nn.Conv2d))
28 ]
29 if not projections or not isinstance(projections[-1][1], nn.Linear):
30 continue
31 path, projection = projections[-1]
32 parent_path, _, child = path.rpartition(".")
33 parent = head.get_submodule(parent_path) if parent_path else head
34 setattr(parent, child, nn.Identity())
35 return projection
36 raise ValueError(
37 "Classifier fusion requires a final linear classification head (for example ResNet or ConvNeXt)"
38 )
41def _pooled_channels(model, pool):
42 """Run a dummy RGB image to find the channel count of the map entering avgpool."""
43 shapes = []
44 handle = pool.register_forward_pre_hook(
45 lambda module, args: shapes.append(args[0].shape)
46 )
47 parameter = next(model.parameters())
48 modes = [(module, module.training) for module in model.modules()]
49 model.eval()
50 try:
51 with torch.no_grad():
52 model(
53 torch.zeros(
54 1,
55 3,
56 PROBE_SIZE,
57 PROBE_SIZE,
58 device=parameter.device,
59 dtype=parameter.dtype,
60 )
61 )
62 finally:
63 handle.remove()
64 for module, training in modes:
65 module.training = training
66 if len(shapes) != 1 or len(shapes[0]) != 4:
67 raise ValueError(
68 "Classifier fusion requires an avgpool layer that pools a spatial feature map"
69 )
70 return shapes[0][1]
73class SpatialViewAttention(nn.Module):
74 """Per-position softmax attention over views, conditioned on the view mean."""
76 def __init__(self, channels: int, hidden_dim: int):
77 super().__init__()
78 self.score = nn.Sequential(
79 nn.Conv2d(2 * channels, hidden_dim, 1),
80 nn.GELU(),
81 nn.Conv2d(hidden_dim, 1, 1),
82 )
83 # Begin with uniform weights: the fused map is the mean of the views.
84 nn.init.zeros_(self.score[-1].weight)
85 nn.init.zeros_(self.score[-1].bias)
87 def weights(self, features):
88 """Return B,V,H,W weights that sum to one over views at each position."""
89 batch, views, channels, height, width = features.shape
90 context = features.mean(dim=1, keepdim=True).expand_as(features)
91 paired = torch.cat((features, context), dim=2).reshape(
92 batch * views, 2 * channels, height, width
93 )
94 logits = self.score(paired).reshape(batch, views, height, width)
95 return logits.float().softmax(dim=1).to(features.dtype)
97 def forward(self, features):
98 return (features * self.weights(features)[:, :, None]).sum(dim=1)
101class ViewFusionPool(nn.Module):
102 """Fuse B*V feature maps into B maps, then apply the encoder's original pool."""
104 def __init__(self, attention, pool, num_views: int):
105 super().__init__()
106 self.attention = attention
107 self.pool = pool
108 self.num_views = num_views
110 def forward(self, features):
111 views = features.reshape(-1, self.num_views, *features.shape[1:])
112 return self.pool(self.attention(views))
115class RGBViewFusionClassifier(nn.Module):
116 """Encode B*V RGB images with one encoder, fuse spatially across V, classify once."""
118 def __init__(self, model, input_channels, *, hidden_dim=128):
119 super().__init__()
120 if input_channels < 3 or input_channels % 3:
121 raise ValueError(
122 "fusion requires stacked RGB views: input channels must be a positive multiple of 3"
123 )
124 if hidden_dim < 1:
125 raise ValueError("Invalid classifier fusion hidden dimension")
126 first = next(
127 (layer for layer in model.modules() if isinstance(layer, nn.Conv2d)), None
128 )
129 if first is not None and first.in_channels != 3:
130 raise ValueError(
131 "fusion requires an RGB backbone, not an expanded first convolution; start from an RGB model or a fusion checkpoint"
132 )
133 pool = getattr(model, "avgpool", None)
134 if not isinstance(pool, nn.Module):
135 raise ValueError(
136 "Classifier fusion requires a convolutional model with an avgpool layer (for example ResNet, ConvNeXt or EfficientNet)"
137 )
138 channels = _pooled_channels(model, pool)
139 self.head = _take_projection(model)
140 self.num_views = input_channels // 3
141 model.avgpool = ViewFusionPool(
142 SpatialViewAttention(channels, hidden_dim), pool, self.num_views
143 )
144 self.encoder = model
145 self.input_channels = input_channels
146 self.hidden_dim = hidden_dim
147 self.to(device=self.head.weight.device, dtype=self.head.weight.dtype)
148 # Match the encoder's mode without overriding its submodules' own modes.
149 self.training = model.training
150 model.avgpool.train(model.training)
152 @property
153 def attention(self):
154 return self.encoder.avgpool.attention
156 @property
157 def fusion_spec(self):
158 return {
159 "version": FORMAT_VERSION,
160 "num_views": self.num_views,
161 "hidden_dim": self.hidden_dim,
162 }
164 def forward(self, pixels):
165 if pixels.ndim != 4 or pixels.shape[1] != self.input_channels:
166 raise ValueError(
167 f"Fusion classifier expects BCHW with {self.input_channels} channels; got {tuple(pixels.shape)}"
168 )
169 batch, _, height, width = pixels.shape
170 rgb = pixels.reshape(batch * self.num_views, 3, height, width)
171 return self.head(self.encoder(rgb))
174def restore_fusion(model, input_channels, spec):
175 if not isinstance(spec, dict) or spec.get("version") != FORMAT_VERSION:
176 raise ValueError(
177 "Unsupported torchvision classifier fusion checkpoint version; retrain with the current fusion"
178 )
179 if spec.get("num_views", 0) * 3 != input_channels:
180 raise ValueError("Fusion checkpoint view count does not match input_channels")
181 return RGBViewFusionClassifier(model, input_channels, hidden_dim=spec["hidden_dim"])