Datasets:

Modalities:
Image
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 26,063 Bytes
faac361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2051e891-2bcf-42a6-9a1e-f773baff8808",
   "metadata": {},
   "source": [
    "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
    "\n",
    "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Pixel/Solution/Pixel_Solution.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "441c46a0-b20a-4dc1-9227-f659833a7d2f",
   "metadata": {},
   "source": [
    "# Pixel Efficiency: Reference Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2df5ae63",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "from tqdm import tqdm\n",
    "import json\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from datasets import load_from_disk\n",
    "from transformers import CLIPProcessor, CLIPModel\n",
    "from typing import Optional\n",
    "from transformers.models.clip.modeling_clip import CLIPVisionTransformer, CLIPVisionConfig, BaseModelOutputWithPooling\n",
    "\n",
    "\n",
    "# Dataset configuration\n",
    "DATASET_PATH = os.environ.get(\"DATA_PATH\") + \"/test_dataset\"\n",
    "SPLIT = \"test\"\n",
    "\n",
    "# Model Configuration\n",
    "MODEL_PATH = \"./clip-vit-large-patch14\"\n",
    "DEVICE = \"cuda\"\n",
    "BACKGROUND_CLASS = \"other\"\n",
    "\n",
    "# Image and Masking Configuration\n",
    "HEIGHT = 224\n",
    "WIDTH = 224\n",
    "RETAIN_RATIO = 0.0625\n",
    "MEAN_COLOR = (0, 0, 0)\n",
    "STRIDE = 2\n",
    "TOP_K = 3\n",
    "\n",
    "# Load the dataset\n",
    "print(\"Loading dataset...\")\n",
    "dataset_whole = load_from_disk(DATASET_PATH)\n",
    "dataset = dataset_whole[SPLIT]\n",
    "\n",
    "print(f\"Dataset loaded successfully! Total samples: {len(dataset)}\")\n",
    "\n",
    "print(f\"Loading CLIP model and processor: {MODEL_PATH}...\")\n",
    "model = CLIPModel.from_pretrained(MODEL_PATH).to(DEVICE)\n",
    "processor = CLIPProcessor.from_pretrained(MODEL_PATH)\n",
    "print(\"Model and processor loaded successfully.\")\n",
    "\n",
    "\n",
    "def generate_all_rectangular_regions(image_size=224, patch_size=14, retain_ratio=RETAIN_RATIO, max_aspect_ratio=1.2, stride=1):\n",
    "    \"\"\"Generate rectangular regions with optimizations for speed\"\"\"\n",
    "    max_pixels = int(retain_ratio * image_size * image_size)\n",
    "    patches_per_side = image_size // patch_size\n",
    "    patch_area = patch_size * patch_size\n",
    "    target_patches = max_pixels // patch_area\n",
    "    \n",
    "    min_patches = max(1, target_patches - 1)\n",
    "    max_patches = target_patches + 1\n",
    "    \n",
    "    regions = []\n",
    "    region_to_patches = []\n",
    "    \n",
    "    # Pre-compute valid rectangle dimensions\n",
    "    valid_dims = []\n",
    "    for width_patches in range(1, patches_per_side + 1):\n",
    "        for height_patches in range(1, patches_per_side + 1):\n",
    "            total_patches = width_patches * height_patches\n",
    "            if min_patches <= total_patches <= max_patches:\n",
    "                aspect_ratio = max(width_patches, height_patches) / min(width_patches, height_patches)\n",
    "                if aspect_ratio <= max_aspect_ratio:\n",
    "                    valid_dims.append((width_patches, height_patches, total_patches))\n",
    "    \n",
    "    # Generate rectangles using stride for positions\n",
    "    for width_patches, height_patches, total_patches in valid_dims:\n",
    "        for top_patch in range(0, patches_per_side - height_patches + 1, stride):\n",
    "            for left_patch in range(0, patches_per_side - width_patches + 1, stride):\n",
    "                bottom_patch = top_patch + height_patches\n",
    "                right_patch = left_patch + width_patches\n",
    "                \n",
    "                pixel_coords = (\n",
    "                    top_patch * patch_size,\n",
    "                    left_patch * patch_size,\n",
    "                    bottom_patch * patch_size,\n",
    "                    right_patch * patch_size\n",
    "                )\n",
    "                regions.append(pixel_coords)\n",
    "                \n",
    "                covered_patches = []\n",
    "                for p_row in range(top_patch, bottom_patch):\n",
    "                    for p_col in range(left_patch, right_patch):\n",
    "                        patch_idx = p_row * patches_per_side + p_col\n",
    "                        covered_patches.append(patch_idx)\n",
    "                region_to_patches.append(covered_patches)\n",
    "    \n",
    "    return regions, region_to_patches\n",
    "\n",
    "\n",
    "class MaskCLIPVisionTransformer(CLIPVisionTransformer):\n",
    "    \"\"\"Modified CLIP Vision Transformer that supports mask tokens for all possible rectangular regions\"\"\"\n",
    "    \n",
    "    def __init__(self, config: CLIPVisionConfig, retain_ratio=RETAIN_RATIO):\n",
    "        super().__init__(config)\n",
    "        self.retain_ratio = retain_ratio\n",
    "        self.num_patches = (config.image_size // config.patch_size) ** 2\n",
    "        \n",
    "        self.regions, self.region_to_patches = generate_all_rectangular_regions(\n",
    "            image_size=config.image_size, \n",
    "            patch_size=config.patch_size, \n",
    "            retain_ratio=retain_ratio,\n",
    "            max_aspect_ratio=1.2,\n",
    "            stride=STRIDE\n",
    "        )\n",
    "        self.num_mask_tokens = len(self.regions)\n",
    "        \n",
    "        self.mask_tokens = nn.Parameter(torch.randn(1, self.num_mask_tokens, config.hidden_size))\n",
    "        \n",
    "    def create_mask_attention_matrix(self, batch_size):\n",
    "        \"\"\"Create attention mask matrix for all rectangular regions\"\"\"\n",
    "        N = self.num_patches\n",
    "        M = self.num_mask_tokens\n",
    "        total_tokens = N + 1 + M\n",
    "        \n",
    "        attention_mask = torch.zeros(total_tokens, total_tokens, dtype=torch.bool, device=self.mask_tokens.device)\n",
    "        \n",
    "        # Class token and image patches do NOT attend to mask tokens\n",
    "        attention_mask[:N+1, N+1:] = True\n",
    "        \n",
    "        # Each mask token attends to its specific image patches (not CLS)\n",
    "        attention_mask[N+1:, 1:N+1] = True\n",
    "        \n",
    "        # Then allow each mask token to attend to its assigned patches\n",
    "        for mask_idx in range(M):\n",
    "            covered_patches = self.region_to_patches[mask_idx]\n",
    "            for patch_idx in covered_patches:\n",
    "                token_pos = 1 + patch_idx\n",
    "                attention_mask[N + 1 + mask_idx, token_pos] = False\n",
    "        \n",
    "        # Mask tokens do NOT attend to each other\n",
    "        attention_mask[N+1:, N+1:] = True\n",
    "        # Allow self-attention for each mask token\n",
    "        for i in range(M):\n",
    "            attention_mask[N + 1 + i, N + 1 + i] = False\n",
    "        \n",
    "        return attention_mask\n",
    "    \n",
    "    def forward(\n",
    "        self,\n",
    "        pixel_values: Optional[torch.FloatTensor] = None,\n",
    "        output_attentions: Optional[bool] = None,\n",
    "        output_hidden_states: Optional[bool] = None,\n",
    "        interpolate_pos_encoding: Optional[bool] = False,\n",
    "        use_mask_tokens: bool = False,\n",
    "    ) -> BaseModelOutputWithPooling:\n",
    "        \"\"\"Forward pass with optional mask tokens\"\"\"\n",
    "        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n",
    "        output_hidden_states = (\n",
    "            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n",
    "        )\n",
    "\n",
    "        if pixel_values is None:\n",
    "            raise ValueError(\"You have to specify pixel_values\")\n",
    "\n",
    "        # Get embeddings (patches + class token)\n",
    "        hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)\n",
    "        hidden_states = self.pre_layrnorm(hidden_states)\n",
    "        \n",
    "        if use_mask_tokens:\n",
    "            # Add mask tokens to the sequence\n",
    "            batch_size = hidden_states.shape[0]\n",
    "            \n",
    "            cls_token_embedding = hidden_states[:, 0:1, :]\n",
    "            mask_tokens_expanded = cls_token_embedding.expand(batch_size, self.num_mask_tokens, -1)\n",
    "            \n",
    "            if mask_tokens_expanded.device != hidden_states.device:\n",
    "                mask_tokens_expanded = mask_tokens_expanded.to(hidden_states.device)\n",
    "                \n",
    "            hidden_states = torch.cat([hidden_states, mask_tokens_expanded], dim=1)\n",
    "            \n",
    "            # Create custom attention mask\n",
    "            attention_mask = self.create_mask_attention_matrix(batch_size)\n",
    "            \n",
    "            seq_len = hidden_states.shape[1]\n",
    "            attention_mask_4d = attention_mask.unsqueeze(0).unsqueeze(0).expand(batch_size, 1, -1, -1)\n",
    "            attention_mask_4d = attention_mask_4d.float()\n",
    "            attention_mask_4d = attention_mask_4d.masked_fill(attention_mask_4d == 1, float('-inf'))\n",
    "            attention_mask_4d = attention_mask_4d.masked_fill(attention_mask_4d == 0, 0.0)\n",
    "        else:\n",
    "            attention_mask_4d = None\n",
    "\n",
    "        # Process through encoder layers\n",
    "        encoder_outputs = self.encoder(\n",
    "            inputs_embeds=hidden_states,\n",
    "            attention_mask=attention_mask_4d,\n",
    "            causal_attention_mask=None,\n",
    "            output_attentions=output_attentions,\n",
    "            output_hidden_states=output_hidden_states,\n",
    "        )\n",
    "\n",
    "        last_hidden_state = encoder_outputs.last_hidden_state\n",
    "        \n",
    "        if use_mask_tokens:\n",
    "            # Extract different token types\n",
    "            class_token_output = last_hidden_state[:, 0]\n",
    "            mask_tokens_output = last_hidden_state[:, self.num_patches + 1:]\n",
    "            \n",
    "            # Apply post layer norm\n",
    "            pooled_output = self.post_layernorm(class_token_output)\n",
    "            mask_tokens_output = self.post_layernorm(mask_tokens_output)\n",
    "            \n",
    "            return {\n",
    "                'last_hidden_state': last_hidden_state,\n",
    "                'pooler_output': pooled_output,\n",
    "                'mask_tokens_output': mask_tokens_output,\n",
    "                'hidden_states': encoder_outputs.hidden_states,\n",
    "                'attentions': encoder_outputs.attentions,\n",
    "            }\n",
    "        else:\n",
    "            # Standard CLIP behavior\n",
    "            pooled_output = last_hidden_state[:, 0, :]\n",
    "            pooled_output = self.post_layernorm(pooled_output)\n",
    "\n",
    "            return BaseModelOutputWithPooling(\n",
    "                last_hidden_state=last_hidden_state,\n",
    "                pooler_output=pooled_output,\n",
    "                hidden_states=encoder_outputs.hidden_states,\n",
    "                attentions=encoder_outputs.attentions,\n",
    "            )\n",
    "\n",
    "\n",
    "def apply_mask_with_mean(image, mask, mean_rgb=MEAN_COLOR):\n",
    "    \"\"\"Apply arbitrary binary mask to image, replacing masked areas with mean values\"\"\"\n",
    "    img_array = np.array(image).copy()\n",
    "\n",
    "    if isinstance(mask, Image.Image):\n",
    "        mask_array = np.array(mask.convert('L')) > 127\n",
    "    else:\n",
    "        mask_array = mask > 0\n",
    "\n",
    "    mask_3d = np.stack([mask_array] * 3, axis=2)\n",
    "    mean_values = np.array([int(m * 255) for m in mean_rgb])\n",
    "    img_array = np.where(mask_3d, img_array, mean_values.reshape(1, 1, 3))\n",
    "\n",
    "    return Image.fromarray(img_array.astype(np.uint8))\n",
    "\n",
    "\n",
    "def compute_vision_features_once(model, image, mask_vision_model):\n",
    "    \"\"\"\n",
    "    Compute vision features once for efficient reuse across multiple mask selection functions.\n",
    "    This eliminates redundant forward passes.\n",
    "    \"\"\"\n",
    "    image_inputs = processor(images=image, return_tensors=\"pt\").to(DEVICE)\n",
    "    \n",
    "    with torch.no_grad():\n",
    "        vision_outputs = mask_vision_model(\n",
    "            pixel_values=image_inputs['pixel_values'],\n",
    "            use_mask_tokens=True\n",
    "        )\n",
    "        \n",
    "        full_image_features = vision_outputs['pooler_output']\n",
    "        if hasattr(model, 'visual_projection') and model.visual_projection is not None:\n",
    "            full_image_features = model.visual_projection(full_image_features)\n",
    "        \n",
    "        mask_tokens_features = vision_outputs['mask_tokens_output']\n",
    "        if hasattr(model, 'visual_projection') and model.visual_projection is not None:\n",
    "            batch_size, num_tokens, embed_dim = mask_tokens_features.shape\n",
    "            mask_tokens_features = mask_tokens_features.view(-1, embed_dim)\n",
    "            mask_tokens_features = model.visual_projection(mask_tokens_features)\n",
    "            mask_tokens_features = mask_tokens_features.view(batch_size, num_tokens, -1)\n",
    "        \n",
    "        full_image_features = full_image_features / full_image_features.norm(dim=-1, keepdim=True)\n",
    "        mask_tokens_features = mask_tokens_features / mask_tokens_features.norm(dim=-1, keepdim=True)\n",
    "    \n",
    "    return vision_outputs, full_image_features, mask_tokens_features\n",
    "\n",
    "\n",
    "def find_best_mask_region_calibrated(model, image, class_names, mask_vision_model, text_features, \n",
    "                                   vision_outputs=None, full_image_features=None, mask_tokens_features=None, \n",
    "                                   return_detailed=False):\n",
    "    \"\"\"Find the best mask region using MaskCLIP approach with calibration for black-pixel masking\"\"\"\n",
    "    num_mask_tokens = mask_vision_model.num_mask_tokens\n",
    "    \n",
    "    # Use pre-computed features if provided, otherwise compute them\n",
    "    if vision_outputs is None or full_image_features is None or mask_tokens_features is None:\n",
    "        image_inputs = processor(images=image, return_tensors=\"pt\").to(DEVICE)\n",
    "        \n",
    "        with torch.no_grad():\n",
    "            vision_outputs = mask_vision_model(\n",
    "                pixel_values=image_inputs['pixel_values'],\n",
    "                use_mask_tokens=True\n",
    "            )\n",
    "            \n",
    "            full_image_features = vision_outputs['pooler_output']\n",
    "            if hasattr(model, 'visual_projection') and model.visual_projection is not None:\n",
    "                full_image_features = model.visual_projection(full_image_features)\n",
    "            \n",
    "            mask_tokens_features = vision_outputs['mask_tokens_output']\n",
    "            if hasattr(model, 'visual_projection') and model.visual_projection is not None:\n",
    "                batch_size, num_tokens, embed_dim = mask_tokens_features.shape\n",
    "                mask_tokens_features = mask_tokens_features.view(-1, embed_dim)\n",
    "                mask_tokens_features = model.visual_projection(mask_tokens_features)\n",
    "                mask_tokens_features = mask_tokens_features.view(batch_size, num_tokens, -1)\n",
    "            \n",
    "            full_image_features = full_image_features / full_image_features.norm(dim=-1, keepdim=True)\n",
    "            mask_tokens_features = mask_tokens_features / mask_tokens_features.norm(dim=-1, keepdim=True)\n",
    "    \n",
    "    # Compute similarity between full image and text\n",
    "    full_image_similarities = torch.matmul(full_image_features, text_features.T)\n",
    "    full_image_prediction = torch.argmax(full_image_similarities, dim=-1)\n",
    "    predicted_class_idx = full_image_prediction.item()\n",
    "    \n",
    "    # Compute similarities for each mask token\n",
    "    mask_similarities = torch.matmul(mask_tokens_features.squeeze(0), text_features.T)\n",
    "    mask_predictions = torch.argmax(mask_similarities, dim=-1)\n",
    "    \n",
    "    # Get candidates that predict the same class as full image, sorted by confidence\n",
    "    matching_masks = (mask_predictions == predicted_class_idx)\n",
    "    \n",
    "    if matching_masks.any():\n",
    "        candidate_indices = torch.where(matching_masks)[0]\n",
    "        candidate_confidences = mask_similarities[candidate_indices, predicted_class_idx]\n",
    "        sorted_indices = torch.argsort(candidate_confidences, descending=True)\n",
    "        sorted_candidates = candidate_indices[sorted_indices]\n",
    "    else:\n",
    "        # If no exact matches, use all candidates sorted by confidence for predicted class\n",
    "        candidate_confidences = mask_similarities[:, predicted_class_idx]\n",
    "        sorted_candidates = torch.topk(candidate_confidences, len(candidate_confidences)).indices\n",
    "    \n",
    "    # OPTIMIZATION: If TOP_K=1, skip calibration and return best candidate directly\n",
    "    if TOP_K == 1:\n",
    "        return sorted_candidates[0].item()\n",
    "    \n",
    "    # CALIBRATION STEP: Test top K candidates, return immediately when one is correct\n",
    "    calibration_results = []\n",
    "    candidates_to_test = sorted_candidates[:TOP_K]\n",
    "    \n",
    "    for i, candidate_idx in enumerate(candidates_to_test):\n",
    "        candidate_idx_item = candidate_idx.item()\n",
    "        \n",
    "        # Create masked image for this candidate\n",
    "        coordinates = mask_idx_to_coordinates(candidate_idx_item, mask_vision_model)\n",
    "        mask = generate_mask_from_coordinates(image, coordinates)\n",
    "        masked_image = apply_mask_with_mean(image, mask)\n",
    "        \n",
    "        # Test with actual forward pass\n",
    "        with torch.no_grad():\n",
    "            masked_image_inputs = processor(images=masked_image, return_tensors=\"pt\").to(DEVICE)\n",
    "            masked_image_features = model.get_image_features(**masked_image_inputs)\n",
    "            masked_image_features = masked_image_features / masked_image_features.norm(dim=-1, keepdim=True)\n",
    "            \n",
    "            masked_similarities = torch.matmul(masked_image_features, text_features.T)\n",
    "            masked_prediction = torch.argmax(masked_similarities, dim=-1).item()\n",
    "            masked_confidence = masked_similarities[0, predicted_class_idx].item()\n",
    "        \n",
    "        # If this candidate predicts correctly, return it immediately (early exit optimization)\n",
    "        if masked_prediction == predicted_class_idx:\n",
    "            return candidate_idx_item\n",
    "        \n",
    "        # Store failed calibration result\n",
    "        calibration_results.append((candidate_idx_item, masked_confidence))\n",
    "    \n",
    "    # If we reach here, all TOP_K candidates failed calibration\n",
    "    # Fall back to the next best candidate from sorted list WITHOUT additional calibration\n",
    "    if len(sorted_candidates) > TOP_K:\n",
    "        return sorted_candidates[TOP_K].item()\n",
    "    else:\n",
    "        # If no more candidates available, return the best failed calibration result\n",
    "        if calibration_results:\n",
    "            return max(calibration_results, key=lambda x: x[1])[0]\n",
    "        else:\n",
    "            # Ultimate fallback: return the best mask token prediction\n",
    "            return sorted_candidates[0].item()\n",
    "\n",
    "\n",
    "def mask_idx_to_coordinates(mask_idx, mask_vision_model):\n",
    "    \"\"\"Convert mask token index to image coordinates using the pre-computed regions\"\"\"\n",
    "    if mask_idx >= len(mask_vision_model.regions):\n",
    "        raise ValueError(f\"mask_idx {mask_idx} is out of range. Only {len(mask_vision_model.regions)} regions available.\")\n",
    "    \n",
    "    top, left, bottom, right = mask_vision_model.regions[mask_idx]\n",
    "    return ((top, left), (bottom, right))\n",
    "\n",
    "\n",
    "def generate_mask_from_coordinates(image, coordinates):\n",
    "    \"\"\"Generate a binary mask from crop coordinates\"\"\"\n",
    "    H, W = 224, 224\n",
    "    mask = np.zeros((H, W), dtype=np.int8)\n",
    "    \n",
    "    (top, left), (bottom, right) = coordinates\n",
    "    mask[top:bottom, left:right] = 1\n",
    "    \n",
    "    return mask\n",
    "\n",
    "\n",
    "# Create the MaskCLIP model\n",
    "print(\"Creating MaskCLIP model...\")\n",
    "mask_vision_model = MaskCLIPVisionTransformer(model.vision_model.config, retain_ratio=RETAIN_RATIO)\n",
    "mask_vision_model.load_state_dict(model.vision_model.state_dict(), strict=False)\n",
    "mask_vision_model = mask_vision_model.to(DEVICE)\n",
    "mask_vision_model.eval()\n",
    "print(\"MaskCLIP model created successfully.\")\n",
    "\n",
    "dataset_eval = load_from_disk(DATASET_PATH)\n",
    "dataset_eval = dataset_eval[SPLIT]\n",
    "\n",
    "# Get class names from training dataset for consistent evaluation  \n",
    "train_dataset = load_from_disk(\"/bohr/train-yzfn/v1/train_dataset\")[\"train\"] # TODO: This part needs changing!\n",
    "class_names_eval = list(set([item['name'] for item in train_dataset])) + [BACKGROUND_CLASS]\n",
    "\n",
    "# Prepare text features once for efficiency\n",
    "print(\"Preparing text features...\")\n",
    "text_inputs_eval = processor(text=class_names_eval, return_tensors=\"pt\", padding=True).to(DEVICE)\n",
    "with torch.no_grad():\n",
    "    text_features_eval = model.get_text_features(**text_inputs_eval)\n",
    "    text_features_eval = text_features_eval / text_features_eval.norm(dim=-1, keepdim=True)\n",
    "print(\"Text features prepared.\")\n",
    "\n",
    "# Main evaluation loop\n",
    "masks = {}\n",
    "total_correct = 0\n",
    "total_processed = 0\n",
    "\n",
    "for item in tqdm(dataset_eval):\n",
    "    image = item['image']\n",
    "    total_processed += 1\n",
    "\n",
    "    try:\n",
    "        # Compute vision features once for efficiency (eliminates redundant forward passes)\n",
    "        vision_outputs, full_image_features, mask_tokens_features = compute_vision_features_once(\n",
    "            model, image, mask_vision_model\n",
    "        )\n",
    "        \n",
    "        # Get prediction from pre-computed features\n",
    "        full_image_similarities = torch.matmul(full_image_features, text_features_eval.T)\n",
    "        predicted_class_idx = torch.argmax(full_image_similarities, dim=-1).item()\n",
    "            \n",
    "        best_mask_idx = find_best_mask_region_calibrated(\n",
    "            model, image, class_names_eval, mask_vision_model, text_features_eval,\n",
    "            vision_outputs=vision_outputs, full_image_features=full_image_features, \n",
    "            mask_tokens_features=mask_tokens_features\n",
    "        )\n",
    "        \n",
    "        coordinates = mask_idx_to_coordinates(best_mask_idx, mask_vision_model)\n",
    "        \n",
    "        # Validate the mask\n",
    "        mask = generate_mask_from_coordinates(image, coordinates)\n",
    "        assert mask.shape == (224, 224), \"Mask should be 224x224\"\n",
    "        assert mask.sum() <= RETAIN_RATIO * 224 * 224, \"You should leave only 6.25% of pixels\"\n",
    "\n",
    "        \n",
    "        # Save the coordinates\n",
    "        idx = item['idx']\n",
    "        masks[idx] = coordinates\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"Error processing image {item['idx']}: {e}\")\n",
    "        # Fallback to a small center region if there's an error\n",
    "        if len(mask_vision_model.regions) > 0:\n",
    "            region_sizes = [(r[2]-r[0])*(r[3]-r[1]) for r in mask_vision_model.regions]\n",
    "            min_region_idx = region_sizes.index(min(region_sizes))\n",
    "            fallback_coords = mask_idx_to_coordinates(min_region_idx, mask_vision_model)\n",
    "        else:\n",
    "            fallback_coords = ((84, 84), (140, 140))\n",
    "        masks[item['idx']] = fallback_coords\n",
    "\n",
    "# Save as JSONL (one JSON object per line) - much safer than pickle\n",
    "with open('submission.jsonl', 'w') as f:\n",
    "    for idx, coordinates in masks.items():\n",
    "        json.dump({\"idx\": idx, \"coordinates\": coordinates}, f)\n",
    "        f.write('\\n')\n",
    "\n",
    "print(\"Masks saved to masks.jsonl\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}