aryaaan12 commited on
Commit
b19f6dc
·
verified ·
1 Parent(s): e2b3733

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +607 -0
model.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import logging
4
+ import numpy as np
5
+ import kornia
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ try:
10
+ from .task_utils import CenterPadding, upsample_features
11
+ except ImportError:
12
+ from task_utils import CenterPadding, upsample_features
13
+
14
+
15
+ logging.getLogger().setLevel(logging.WARNING)
16
+
17
+
18
+ class FeatureExtractor(nn.Module):
19
+ def __init__(self, config, device, return_class_token=False):
20
+ super(FeatureExtractor, self).__init__()
21
+ self.feature_extractor = config['pretrained']['feature_extractor']
22
+ self.patch_size = config['architecture']['patch_size']
23
+ self.backbone_ckpt_path = os.path.join(config['logging']['save_dir'], config['logging']['exp_name'],
24
+ 'dinov3_vitl16_pretrain_lvd1689m-8aa4cbdd.pth')
25
+ self.head_ckpt_path = os.path.join(config['logging']['save_dir'], config['logging']['exp_name'],
26
+ 'dinov3_vitl16_dinotxt_vision_head_and_text_encoder-a442d8f5.pth')
27
+ self.return_class_token = return_class_token
28
+ self.device = device
29
+
30
+ if self.feature_extractor == 'dinov3_vitl16':
31
+ self.backbone, _ = torch.hub.load('facebookresearch/dinov3', 'dinov3_vitl16_dinotxt_tet1280d20h24l',
32
+ backbone_weights=self.backbone_ckpt_path, weights=self.head_ckpt_path)
33
+ del self.backbone.text_model
34
+ self.model = self.backbone.visual_model.backbone.to(device)
35
+ self.head = self.backbone.visual_model.head.to(device)
36
+ else:
37
+ raise ValueError(f'Feature extractor {self.feature_extractor} not supported.')
38
+
39
+ def extract_dinov3(self, images, batch_size=1024, patch_length=16, layers=[23]):
40
+ transform = kornia.augmentation.AugmentationSequential(
41
+ CenterPadding(multiple=patch_length),
42
+ kornia.augmentation.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
43
+ )
44
+ transformed_images = transform(images)
45
+
46
+ class_tokens, text_aligned_class_tokens, patch_tokens, register_tokens, feature_maps = [], [], [], [], []
47
+ for i in range(0, transformed_images.shape[0], batch_size):
48
+ image_batch = transformed_images[i:(i + batch_size)].to(device=self.device)
49
+ with torch.inference_mode():
50
+ features_out = self.model.get_intermediate_layers(image_batch, return_class_token=True,
51
+ return_extra_tokens=True, n=layers)
52
+ class_tokens.append(features_out[-1][1])
53
+ patch_tokens.append(features_out[0][0])
54
+ register_tokens.append(features_out[0][2])
55
+
56
+ head_inputs = torch.cat([class_tokens[-1].unsqueeze(1), register_tokens[-1], patch_tokens[-1]], dim=1)
57
+ text_aligned_class_token = self.head(head_inputs)[0][0:1]
58
+ text_aligned_class_tokens.append(text_aligned_class_token)
59
+
60
+ B, _, C = patch_tokens[-1].size()
61
+ H, W = image_batch.shape[2], image_batch.shape[3]
62
+ patch_H, patch_W = math.ceil(H / patch_length), math.ceil(W / patch_length)
63
+ feature_maps.append(patch_tokens[-1].permute(0, 2, 1).view(B, C, patch_H, patch_W))
64
+
65
+ class_tokens = torch.cat(class_tokens, dim=0)
66
+ text_aligned_class_tokens = torch.cat(text_aligned_class_tokens, dim=0)
67
+ patch_tokens = torch.cat(patch_tokens, dim=0)
68
+ register_tokens = torch.cat(register_tokens, dim=0)
69
+ feature_maps = torch.cat(feature_maps, dim=0)
70
+ return class_tokens, text_aligned_class_tokens, patch_tokens, register_tokens, feature_maps
71
+
72
+ def forward(self, images, resize=False):
73
+ if self.feature_extractor == 'dinov3_vitl16':
74
+ class_tokens, text_aligned_class_tokens, patch_tokens, register_tokens, feature_maps = self.extract_dinov3(images)
75
+
76
+ if resize:
77
+ image_height, image_width = images.shape[2], images.shape[3]
78
+ padded_height = math.ceil(image_height / self.patch_size) * self.patch_size
79
+ padded_width = math.ceil(image_width / self.patch_size) * self.patch_size
80
+ resized_feature_maps = []
81
+ chunk_size = 32
82
+ for i in range(0, len(feature_maps), chunk_size):
83
+ resized_feature_maps.append(upsample_features(feature_maps[i:i + chunk_size], image_height,
84
+ image_width, padded_height, padded_width))
85
+ feature_maps = torch.cat(resized_feature_maps)
86
+
87
+ return {
88
+ 'class_tokens': class_tokens,
89
+ 'text_aligned_class_tokens': text_aligned_class_tokens,
90
+ 'patch_tokens': patch_tokens,
91
+ 'register_tokens': register_tokens,
92
+ 'feature_maps': feature_maps
93
+ }
94
+
95
+
96
+ class RegionTokenGenerator(nn.Module):
97
+ def __init__(self, pooling_method='average', device='cuda'):
98
+ super(RegionTokenGenerator, self).__init__()
99
+ self.model, _ = torch.hub.load('facebookresearch/dinov3', 'dinov3_vitl16_dinotxt_tet1280d20h24l')
100
+ self.model = self.model.visual_model.head.to(device)
101
+ self.pooling_method = pooling_method
102
+ self.device = device
103
+
104
+ def forward(self, regions, class_tokens, feature_maps, register_tokens):
105
+ pooled_tokens, text_aligned_tokens = [], []
106
+ for scale_idx in range(regions.shape[2]):
107
+ scale_pooled_tokens, scale_text_aligned_tokens = [], []
108
+ for batch_idx in range(len(regions)):
109
+ image_regions = regions[batch_idx, :, scale_idx]
110
+ image_class_tokens = class_tokens[batch_idx]
111
+ image_feature_maps = feature_maps[batch_idx]
112
+ image_register_tokens = register_tokens[batch_idx]
113
+ if image_regions.numel() == 0:
114
+ scale_pooled_tokens.append(torch.zeros((0, image_feature_maps.shape[0]), device=self.device))
115
+ scale_text_aligned_tokens.append(torch.zeros((0, image_feature_maps.shape[0]), device=self.device))
116
+ continue
117
+
118
+ # Get the features that pertain to the regions
119
+ region_features = torch.einsum('rhw,chw->rc', image_regions.float(), image_feature_maps)
120
+ text_alignment_inputs = torch.cat([image_class_tokens[None], image_register_tokens, region_features], dim=0)
121
+ text_aligned_region_features = self.model(text_alignment_inputs[None])[0][image_register_tokens.shape[0] + 1 :]
122
+
123
+ # Pool the region features
124
+ if self.pooling_method == 'average':
125
+ valid_elements = image_regions.sum(dim=(1, 2), dtype=torch.float32).clamp(min=1).unsqueeze(1)
126
+ region_features = region_features / valid_elements
127
+ text_aligned_region_features = text_aligned_region_features / valid_elements
128
+ else:
129
+ raise ValueError(f'Pooling method {self.pooling_method} not supported.')
130
+ scale_pooled_tokens.append(region_features)
131
+ scale_text_aligned_tokens.append(text_aligned_region_features)
132
+ scale_pooled_tokens = torch.stack(scale_pooled_tokens)
133
+ scale_text_aligned_tokens = torch.stack(scale_text_aligned_tokens)
134
+ pooled_tokens.append(scale_pooled_tokens.unsqueeze(2))
135
+ text_aligned_tokens.append(scale_text_aligned_tokens.unsqueeze(2))
136
+ pooled_tokens = torch.cat(pooled_tokens, dim=2)
137
+ text_aligned_tokens = torch.cat(text_aligned_tokens, dim=2)
138
+ return {
139
+ 'pooled_tokens': pooled_tokens,
140
+ 'text_aligned_tokens': text_aligned_tokens
141
+ }
142
+
143
+
144
+ class TextEncoder(nn.Module):
145
+ def __init__(self, config, device, prompt='photo of a '):
146
+ super(TextEncoder, self).__init__()
147
+ self.ckpt_path = os.path.join(config['logging']['save_dir'], config['logging']['exp_name'],
148
+ 'dinov3_vitl16_dinotxt_vision_head_and_text_encoder-a442d8f5.pth')
149
+ self.model, self.tokenizer = torch.hub.load('facebookresearch/dinov3', 'dinov3_vitl16_dinotxt_tet1280d20h24l',
150
+ weights=self.ckpt_path)
151
+ del self.model.visual_model
152
+ self.model = self.model.to(device)
153
+ self.prompt = prompt
154
+ self.device = device
155
+
156
+ def forward(self, texts):
157
+ texts = [self.prompt + t for t in texts]
158
+ text_tokens = self.tokenizer.tokenize(texts).to(self.device)
159
+ with torch.no_grad():
160
+ text_embeddings = self.model.encode_text(text_tokens)
161
+ text_embeddings = text_embeddings[:, text_embeddings.shape[1] // 2 :]
162
+ return text_embeddings
163
+
164
+
165
+ class PositionalEmbedding2D(nn.Module):
166
+ def __init__(self, embedding_dim=64, scale=None):
167
+ super().__init__()
168
+ if scale is None or scale <= 0.0:
169
+ scale = 1.0
170
+ generator = torch.Generator()
171
+ generator.manual_seed(42)
172
+ self.register_buffer("positional_encoding_gaussian_matrix",
173
+ scale * torch.randn((2, embedding_dim // 2), generator=generator))
174
+
175
+ def _pe_encoding(self, coords):
176
+ coords = 2 * coords - 1
177
+ coords = coords @ self.positional_encoding_gaussian_matrix
178
+ coords = 2 * np.pi * coords
179
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
180
+
181
+ def forward(self, size):
182
+ h, w = size
183
+ device = self.positional_encoding_gaussian_matrix.device
184
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
185
+ y_embed = grid.cumsum(dim=0) - 0.5
186
+ x_embed = grid.cumsum(dim=1) - 0.5
187
+ y_embed = y_embed / h
188
+ x_embed = x_embed / w
189
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
190
+ return pe.permute(2, 0, 1)
191
+
192
+
193
+ class AttentionLayer(nn.Module):
194
+ def __init__(self, q_dim, kv_dim, hidden_dim, num_heads=8, dropout=0.1, use_bias=False, use_v_proj=True, use_out_proj=True):
195
+ super(AttentionLayer, self).__init__()
196
+ self.hidden_dim = hidden_dim
197
+ self.num_heads = num_heads
198
+ assert hidden_dim % num_heads == 0, 'Hidden dimension must be a multiple of the number of heads.'
199
+ self.head_dim = hidden_dim // num_heads
200
+ if not use_v_proj:
201
+ assert kv_dim == hidden_dim, 'Key and value dimensions must be the same as the hidden dimension if not using v_proj.'
202
+
203
+ self.q_proj = nn.Linear(q_dim, hidden_dim, bias=use_bias)
204
+ nn.init.kaiming_normal_(self.q_proj.weight, mode='fan_in', nonlinearity='linear')
205
+ self.k_proj = nn.Linear(kv_dim, hidden_dim, bias=use_bias)
206
+ nn.init.kaiming_normal_(self.k_proj.weight, mode='fan_in', nonlinearity='linear')
207
+ if use_v_proj:
208
+ self.v_proj = nn.Linear(kv_dim, hidden_dim, bias=use_bias)
209
+ nn.init.kaiming_normal_(self.v_proj.weight, mode='fan_in', nonlinearity='linear')
210
+ else:
211
+ self.v_proj = nn.Identity()
212
+ if use_bias:
213
+ nn.init.zeros_(self.q_proj.bias)
214
+ nn.init.zeros_(self.k_proj.bias)
215
+ if use_v_proj:
216
+ nn.init.zeros_(self.v_proj.bias)
217
+
218
+ self.q_norm = nn.LayerNorm(self.head_dim)
219
+ self.k_norm = nn.LayerNorm(self.head_dim)
220
+
221
+ self.dropout = nn.Dropout(dropout)
222
+ if use_out_proj:
223
+ self.out_proj = nn.Linear(hidden_dim, hidden_dim, bias=use_bias)
224
+ nn.init.kaiming_normal_(self.out_proj.weight, mode='fan_in', nonlinearity='linear')
225
+ if use_bias:
226
+ nn.init.zeros_(self.out_proj.bias)
227
+ else:
228
+ self.out_proj = nn.Identity()
229
+
230
+ self.scale = self.head_dim ** -0.5
231
+
232
+ def forward(self, q, k, v, mask=None, attn_threshold=None):
233
+ batch_size, q_len, _ = q.shape
234
+ _, kv_len, _ = k.shape
235
+
236
+ query = self.q_proj(q).view(batch_size, q_len, self.num_heads, -1).transpose(1, 2)
237
+ key = self.k_proj(k).view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
238
+ value = self.v_proj(v).view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
239
+
240
+ query = self.q_norm(query)
241
+ key = self.k_norm(key)
242
+
243
+ attn_scores = torch.matmul(query, key.transpose(-2, -1)) * self.scale
244
+ if mask is not None:
245
+ attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))
246
+ if attn_threshold is not None:
247
+ max_attn_scores, _ = attn_scores.max(dim=-1, keepdim=True)
248
+ thresholding_mask = attn_scores >= (attn_threshold * max_attn_scores)
249
+ attn_scores = attn_scores.masked_fill(thresholding_mask == 0, -1e9)
250
+ attn_weights = F.softmax(attn_scores, dim=-1)
251
+ attn_weights = self.dropout(attn_weights)
252
+
253
+ attn_out = torch.matmul(attn_weights, value)
254
+ attn_out = attn_out.transpose(1, 2).contiguous().view(batch_size, q_len, self.hidden_dim)
255
+
256
+ out = self.out_proj(attn_out)
257
+ return out, attn_weights
258
+
259
+
260
+ class MLPBlock(nn.Module):
261
+ def __init__(self, hidden_dim, intermediate_dim, dropout=0.1):
262
+ super(MLPBlock, self).__init__()
263
+ self.linear1 = nn.Linear(hidden_dim, intermediate_dim)
264
+ self.gelu = nn.GELU()
265
+ self.linear2 = nn.Linear(intermediate_dim, hidden_dim)
266
+ self.dropout = nn.Dropout(dropout)
267
+
268
+ def forward(self, x):
269
+ z = self.linear1(x)
270
+ z = self.gelu(z)
271
+ z = self.dropout(z)
272
+ z = self.linear2(z)
273
+ return z
274
+
275
+
276
+ class CrossAttentionBlock(nn.Module):
277
+ def __init__(self, q_dim, kv_dim, hidden_dim, mlp_dim, num_heads, dropout, use_bias):
278
+ super(CrossAttentionBlock, self).__init__()
279
+ self.query_norm = nn.LayerNorm(q_dim)
280
+ self.cross_attn = AttentionLayer(q_dim, kv_dim, hidden_dim, num_heads, dropout, use_bias)
281
+ self.dropout = nn.Dropout(dropout)
282
+ self.mlp_norm = nn.LayerNorm(hidden_dim)
283
+ self.mlp = MLPBlock(hidden_dim, mlp_dim)
284
+ self.out_norm = nn.LayerNorm(hidden_dim)
285
+
286
+ def forward(self, query, context, mask=None):
287
+ x = self.query_norm(query)
288
+ x, attn_scores = self.cross_attn(q=x, k=context, v=context, mask=mask)
289
+ x = self.dropout(x)
290
+ x = x + query
291
+
292
+ y = self.mlp_norm(x)
293
+ y = self.mlp(y)
294
+ out = self.out_norm(y) + x
295
+ return out, attn_scores
296
+
297
+
298
+ class TextAlignmentBlock(nn.Module):
299
+ def __init__(self, hidden_dim, intermediate_dim, output_dim, dropout=0.1):
300
+ super(TextAlignmentBlock, self).__init__()
301
+ self.linear1 = nn.Linear(hidden_dim, intermediate_dim)
302
+ self.gelu = nn.GELU()
303
+ self.linear2 = nn.Linear(intermediate_dim, output_dim)
304
+ self.dropout = nn.Dropout(dropout)
305
+
306
+ def forward(self, x):
307
+ z = self.linear1(x)
308
+ z = self.gelu(z)
309
+ z = self.dropout(z)
310
+ z = self.linear2(z)
311
+ return z
312
+
313
+
314
+ class TokenAggregator(nn.Module):
315
+ def __init__(self, config):
316
+ super(TokenAggregator, self).__init__()
317
+ self.merging_iou_threshold = config['parameters']['merging_iou_threshold']
318
+ self.merging_similarity_threshold = config['parameters']['merging_similarity_threshold']
319
+ self.binarization_threshold = config['parameters'].get('binarization_threshold', 0.5)
320
+
321
+ def _compute_binary_masks(self, region_masks):
322
+ num_masks = region_masks.shape[0]
323
+ return (region_masks.reshape(num_masks, -1) > self.binarization_threshold).float()
324
+
325
+ def _compute_iou_matrix(self, binary_masks):
326
+ num_masks = binary_masks.shape[0]
327
+ if num_masks == 0:
328
+ return torch.zeros(0, 0, device=binary_masks.device)
329
+ intersection = torch.mm(binary_masks, binary_masks.t())
330
+ areas = binary_masks.sum(dim=1)
331
+ union = areas.unsqueeze(1) + areas.unsqueeze(0) - intersection
332
+ return intersection / torch.clamp(union, min=1.0)
333
+
334
+ def _find_connected_components(self, adjacency):
335
+ n = adjacency.shape[0]
336
+ if n == 0:
337
+ return []
338
+
339
+ # Initialize labels
340
+ labels = torch.arange(n, device=adjacency.device)
341
+
342
+ # Iterative label propagation
343
+ for _ in range(int(np.ceil(np.log2(n + 1))) + 1):
344
+ neighbor_labels = torch.where(adjacency, labels.unsqueeze(0).expand(n, -1), labels.unsqueeze(1).expand(-1, n))
345
+ new_labels = neighbor_labels.min(dim=1)[0]
346
+ new_labels = torch.minimum(new_labels, labels)
347
+ if torch.equal(new_labels, labels):
348
+ break
349
+ labels = new_labels
350
+
351
+ # Convert to groups
352
+ labels_cpu = labels.cpu().tolist()
353
+ label_to_group = {}
354
+ for idx, label in enumerate(labels_cpu):
355
+ if label not in label_to_group:
356
+ label_to_group[label] = []
357
+ label_to_group[label].append(idx)
358
+ return list(label_to_group.values())
359
+
360
+ def _compute_token_similarity_matrix(self, pred_tokens):
361
+ num_tokens = pred_tokens.shape[0]
362
+ if num_tokens == 0:
363
+ return torch.zeros(0, 0, device=pred_tokens.device)
364
+ pred_tokens = F.normalize(pred_tokens, p=2, dim=-1)
365
+ return torch.mm(pred_tokens, pred_tokens.t())
366
+
367
+ def group_predictions(self, region_masks, pred_tokens=None):
368
+ num_masks = region_masks.shape[0]
369
+ if num_masks == 0:
370
+ return []
371
+ binary_masks = self._compute_binary_masks(region_masks)
372
+ iou_matrix = self._compute_iou_matrix(binary_masks)
373
+ mask_adjacency = iou_matrix > self.merging_iou_threshold
374
+ if pred_tokens is not None and pred_tokens.shape[0] == num_masks:
375
+ token_sim = self._compute_token_similarity_matrix(pred_tokens)
376
+ token_adjacency = token_sim > self.merging_similarity_threshold
377
+ adjacency = mask_adjacency | token_adjacency
378
+ else:
379
+ adjacency = mask_adjacency
380
+ return self._find_connected_components(adjacency)
381
+
382
+ def forward(self, ren_outputs, remove_singleton_groups=True):
383
+ pred_tokens = ren_outputs['pred_tokens']
384
+ region_masks = ren_outputs['region_masks']
385
+ text_aligned_tokens = ren_outputs['text_aligned_tokens']
386
+
387
+ pred_tokens = torch.flatten(pred_tokens, 1, 2)
388
+ region_masks = torch.flatten(region_masks, 1, 2)
389
+ text_aligned_tokens = torch.flatten(text_aligned_tokens, 1, 2)
390
+
391
+ aggregated_outputs = {'pred_tokens': [], 'region_masks': [], 'text_aligned_tokens': []}
392
+ for batch_idx in range(pred_tokens.shape[0]):
393
+ batch_pred_tokens = pred_tokens[batch_idx]
394
+ batch_region_masks = region_masks[batch_idx]
395
+ batch_text_aligned_tokens = text_aligned_tokens[batch_idx]
396
+
397
+ groups = self.group_predictions(batch_region_masks, batch_pred_tokens)
398
+
399
+ kept_groups = []
400
+ for local_group_idxs in groups:
401
+ if remove_singleton_groups and len(local_group_idxs) == 1:
402
+ continue
403
+ global_idxs = torch.tensor(local_group_idxs, device=batch_region_masks.device)
404
+ group_mean_mask = batch_region_masks[global_idxs].mean(dim=0)
405
+ kept_groups.append({'global_idxs': global_idxs, 'mean_mask': group_mean_mask})
406
+
407
+ if len(kept_groups) == 0:
408
+ mask_areas = batch_region_masks.sum(dim=(-2, -1))
409
+ best_idx = mask_areas.argmax()
410
+ kept_groups.append({
411
+ 'global_idxs': best_idx.unsqueeze(0),
412
+ 'mean_mask': batch_region_masks[best_idx],
413
+ })
414
+
415
+ new_pred_tokens, new_region_masks, new_text_aligned_tokens = [], [], []
416
+ for gd in kept_groups:
417
+ global_idxs = gd['global_idxs']
418
+ new_pred_tokens.append(pred_tokens[batch_idx][global_idxs].mean(dim=0))
419
+ new_region_masks.append(gd['mean_mask'])
420
+ new_text_aligned_tokens.append(text_aligned_tokens[batch_idx][global_idxs].mean(dim=0))
421
+
422
+ aggregated_outputs['pred_tokens'].append(torch.stack(new_pred_tokens, dim=0))
423
+ aggregated_outputs['region_masks'].append(torch.stack(new_region_masks, dim=0))
424
+ aggregated_outputs['text_aligned_tokens'].append(torch.stack(new_text_aligned_tokens, dim=0))
425
+ return aggregated_outputs
426
+
427
+
428
+ class RegionEncoder(nn.Module):
429
+ def __init__(self, config):
430
+ super(RegionEncoder, self).__init__()
431
+ hidden_dim = config['architecture']['hidden_dim']
432
+ text_embed_dim = config['architecture']['text_embed_dim']
433
+ image_resolution = config['parameters']['image_resolution']
434
+ patch_size = config['architecture']['patch_size']
435
+ feature_map_resolution = image_resolution // patch_size
436
+ self.feature_map_resolution = feature_map_resolution
437
+ self.image_resolution = image_resolution
438
+
439
+ # Create position embeddings for the prompts and feature maps
440
+ position_embedder = PositionalEmbedding2D(hidden_dim)
441
+ location_embeddings = position_embedder((image_resolution, image_resolution))
442
+ feature_embeddings = position_embedder((feature_map_resolution, feature_map_resolution)).flatten(-2).permute(1, 0)
443
+ self.register_buffer('location_embeddings', location_embeddings)
444
+ self.register_buffer('feature_embeddings', feature_embeddings)
445
+
446
+ # Define scale embeddings for multiscale region tokens
447
+ self.num_multiscale_regions = config['parameters']['num_multiscale_regions']
448
+ self.scale_embeddings = nn.Embedding(self.num_multiscale_regions, hidden_dim)
449
+ nn.init.normal_(self.scale_embeddings.weight, std=0.02)
450
+
451
+ # Instantiate the prompt and region attention layers
452
+ self.num_decoder_layers = config['architecture']['num_decoder_layers']
453
+ self.num_attention_heads = config['architecture']['num_attention_heads']
454
+ self.prompt_attention_layers = nn.ModuleList([
455
+ AttentionLayer(hidden_dim, hidden_dim, hidden_dim, num_heads=self.num_attention_heads)
456
+ for _ in range(self.num_decoder_layers)
457
+ ])
458
+ self.prompt_attention_norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(self.num_decoder_layers)])
459
+ self.region_attention_layers = nn.ModuleList([
460
+ CrossAttentionBlock(q_dim=hidden_dim, kv_dim=hidden_dim, hidden_dim=hidden_dim, mlp_dim=2 * hidden_dim,
461
+ num_heads=self.num_attention_heads, dropout=0.1, use_bias=False)
462
+ for _ in range(self.num_decoder_layers)
463
+ ])
464
+ self.region_attention_norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(self.num_decoder_layers)])
465
+
466
+ # Instantiate the region token prediction head
467
+ self.token_prediction_head = AttentionLayer(hidden_dim, hidden_dim, hidden_dim, num_heads=1, dropout=0.0,
468
+ use_v_proj=False, use_out_proj=False)
469
+
470
+ # Instantiate the text alignment head
471
+ self.text_alignment_block = TextAlignmentBlock(hidden_dim, 2 * hidden_dim, text_embed_dim)
472
+
473
+ # Instantiate the token aggregator
474
+ self.token_aggregator = TokenAggregator(config)
475
+
476
+ def load_state_dict_resolution_agnostic(self, state_dict, strict=False):
477
+ model_state = self.state_dict()
478
+ new_state = dict(state_dict)
479
+
480
+ # Interpolate location_embeddings if spatial size differs
481
+ if 'location_embeddings' in new_state and new_state['location_embeddings'].shape != model_state['location_embeddings'].shape:
482
+ old = new_state['location_embeddings']
483
+ target_shape = model_state['location_embeddings'].shape
484
+ if old.shape[0] == target_shape[0]:
485
+ resized = F.interpolate(old.unsqueeze(0), size=(target_shape[1], target_shape[2]), mode='bilinear', align_corners=False)
486
+ new_state['location_embeddings'] = resized.squeeze(0)
487
+ else:
488
+ new_state['location_embeddings'] = model_state['location_embeddings'].clone()
489
+
490
+ # Interpolate feature_embeddings if spatial size differs
491
+ if 'feature_embeddings' in new_state and new_state['feature_embeddings'].shape != model_state['feature_embeddings'].shape:
492
+ old = new_state['feature_embeddings']
493
+ target = model_state['feature_embeddings']
494
+ if old.shape[1] == target.shape[1]:
495
+ num_pos_old, C = old.shape
496
+ num_pos_new = target.shape[0]
497
+ h_old = int(round(num_pos_old ** 0.5))
498
+ w_old = num_pos_old // h_old
499
+ h_new = int(round(num_pos_new ** 0.5))
500
+ w_new = num_pos_new // h_new
501
+ old_2d = old.view(h_old, w_old, C).permute(2, 0, 1).unsqueeze(0)
502
+ resized = F.interpolate(old_2d, size=(h_new, w_new), mode='bilinear', align_corners=False)
503
+ new_state['feature_embeddings'] = resized.squeeze(0).permute(1, 2, 0).reshape(-1, C)
504
+ else:
505
+ new_state['feature_embeddings'] = model_state['feature_embeddings'].clone()
506
+
507
+ return self.load_state_dict(new_state, strict=strict)
508
+
509
+ def forward(self, feature_maps, grid_points, aggregate_tokens=False, remove_singleton_groups=True):
510
+ if isinstance(grid_points, list):
511
+ grid_points = torch.stack([gp.to(feature_maps.device) for gp in grid_points])
512
+ batch_size, num_prompts, _ = grid_points.shape
513
+
514
+ # Create scale prompt embeddings for multiscale region tokens
515
+ scale_prompt_embeddings = self.scale_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
516
+ scale_prompt_embeddings = scale_prompt_embeddings.unsqueeze(1).repeat(1, num_prompts, 1, 1)
517
+
518
+ # Create spatial prompt embeddings to encode the location of the point prompts
519
+ spatial_prompt_embeddings = self.location_embeddings[:, grid_points[..., 0], grid_points[..., 1]]
520
+ spatial_prompt_embeddings = spatial_prompt_embeddings.permute(1, 2, 0).unsqueeze(2)
521
+ spatial_prompt_embeddings = spatial_prompt_embeddings.repeat(1, 1, self.num_multiscale_regions, 1)
522
+
523
+ # Create the query tokens
524
+ q = scale_prompt_embeddings
525
+
526
+ # Get the key and value tokens for the region attention layers
527
+ kv = feature_maps.flatten(-2).permute(0, 2, 1)
528
+ kv = kv + self.feature_embeddings[None]
529
+
530
+ # Apply the region attention layers and the prompt attention layers
531
+ for layer_idx in range(self.num_decoder_layers):
532
+ q += spatial_prompt_embeddings
533
+
534
+ # Apply the region attention layer
535
+ q = q.reshape(batch_size, num_prompts * self.num_multiscale_regions, -1)
536
+ q, _ = self.region_attention_layers[layer_idx](q, kv)
537
+ q = q.reshape(batch_size, num_prompts, self.num_multiscale_regions, -1)
538
+ q = self.region_attention_norms[layer_idx](q)
539
+
540
+ # Apply the prompt attention layer
541
+ q = q.reshape(batch_size * num_prompts, self.num_multiscale_regions, -1)
542
+ q, _ = self.prompt_attention_layers[layer_idx](q, q, q)
543
+ q = self.prompt_attention_norms[layer_idx](q)
544
+ q = q.reshape(batch_size, num_prompts, self.num_multiscale_regions, -1)
545
+ prompt_tokens = q
546
+
547
+ # Get the region tokens
548
+ q = prompt_tokens.reshape(batch_size, num_prompts * self.num_multiscale_regions, -1)
549
+ k = kv
550
+ v = kv - self.feature_embeddings[None]
551
+ pred_tokens, attn_weights = self.token_prediction_head(q, k, v)
552
+ pred_tokens = pred_tokens.reshape(batch_size, num_prompts, self.num_multiscale_regions, -1)
553
+ attn_weights = attn_weights.reshape(batch_size, num_prompts, self.num_multiscale_regions, -1)
554
+
555
+ # Get the region masks
556
+ region_masks = attn_weights / attn_weights.max(dim=-1, keepdim=True)[0]
557
+ region_masks = region_masks.reshape(batch_size, num_prompts, self.num_multiscale_regions,
558
+ self.feature_map_resolution, self.feature_map_resolution)
559
+
560
+ # Get text aligned tokens
561
+ text_aligned_tokens = self.text_alignment_block(pred_tokens)
562
+
563
+ outputs = {
564
+ 'pred_tokens': pred_tokens,
565
+ 'region_masks': region_masks,
566
+ 'text_aligned_tokens': text_aligned_tokens,
567
+ }
568
+ if aggregate_tokens:
569
+ outputs = self.token_aggregator(outputs, remove_singleton_groups=remove_singleton_groups)
570
+ return outputs
571
+
572
+
573
+ if __name__ == '__main__':
574
+ import yaml
575
+ from tqdm import tqdm
576
+ from dataloader import COCOStuffDataset
577
+
578
+ # Load the config
579
+ with open('configs/train_dinov3_vitl16.yaml', 'r') as f:
580
+ config = yaml.load(f, Loader=yaml.FullLoader)
581
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
582
+
583
+ # Load the dataset
584
+ dataset = COCOStuffDataset(config, 'val')
585
+
586
+ # Generate the grid points
587
+ image_resolution = config['parameters']['image_resolution']
588
+ patch_size = config['architecture']['patch_size']
589
+ grid_size = image_resolution // patch_size
590
+ x_coords = np.linspace(patch_size // 2, image_resolution - patch_size // 2, grid_size, dtype=int)
591
+ y_coords = np.linspace(patch_size // 2, image_resolution - patch_size // 2, grid_size, dtype=int)
592
+ grid_points = np.array([(y, x) for y in y_coords for x in x_coords])
593
+ grid_points = torch.tensor(grid_points)[None]
594
+
595
+ # Get the models
596
+ region_encoder = RegionEncoder(config).to(device)
597
+ feature_extractor = FeatureExtractor(config, device)
598
+
599
+ # Generate the region tokens
600
+ for item in tqdm(dataset):
601
+ image = item[0].to(device)
602
+ feature_maps = feature_extractor(image[None])['feature_maps']
603
+ ren_outputs = region_encoder(feature_maps, grid_points, aggregate_tokens=True)
604
+ print(ren_outputs['pred_tokens'][0].shape)
605
+ print(ren_outputs['region_masks'][0].shape)
606
+ print(ren_outputs['text_aligned_tokens'][0].shape)
607
+ break