File size: 10,178 Bytes
c50dde6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
消融实验专用数据集

支持 SAM-GSC 和 JEPA-GSC 的数据加载,提供额外的图像预处理用于实时计算 attention。
"""

import json
import logging
import os
import random
from dataclasses import dataclass
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
from open_clip.transform import det_image_transform, get_scale
from pycocotools.coco import COCO


class AblationGridDistillDataset(Dataset):
    """
    消融实验专用数据集
    
    在 GridDistillDataset 基础上,额外返回用于 SAM 或 I-JEPA 的预处理图像。
    """
    
    def __init__(self,
                 input_filename,
                 transforms,
                 image_root,
                 max_split=16,
                 crop_size=224,
                 args=None,
                 ablation_type="sam"):  # "sam" or "ijepa"
        
        self.coco = COCO(input_filename)
        logging.info('Done loading data.')
        self._init_choices(max_split)
        self.transforms = transforms
        self.image_root = image_root
        self.args = args
        self.ablation_type = ablation_type
        
        image_ids = list(self.coco.imgs.keys())
        train_ratio = args.train_ratio
        if train_ratio < 1.0:
            num_images = int(len(image_ids) * train_ratio)
            random.shuffle(image_ids)
            image_ids = image_ids[:num_images]
        self.image_ids = image_ids
        
        self.max_anns = args.max_boxes
        if not isinstance(crop_size, (tuple, list)):
            crop_size = [crop_size, crop_size]
        self.crop_size = crop_size
        self._init_boxes()
        
        # 计算各模型需要的分辨率
        L = args.det_image_size // args.downsample_factor
        
        # VFM (DINOv2) 分辨率
        if args.use_vfm:
            if args.use_vfm == "dino-B-8":
                vfm_resolution = L * 8
            elif args.use_vfm in ["dinov2-L", "dinov2-B", "sd_dino"]:
                vfm_resolution = L * 14
            elif args.use_vfm in ["sam-B", "sam-L", "dino-B-16"]:
                vfm_resolution = L * 16
            else:
                raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.")
            
            self.vfm_transform = det_image_transform(
                vfm_resolution,
                is_train=False,
                mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225]
            )
        else:
            self.vfm_transform = None
        
        # 消融模型分辨率
        if ablation_type == "sam":
            # SAM patch_size=16
            ablation_resolution = L * 16
            self.ablation_transform = det_image_transform(
                ablation_resolution,
                is_train=False,
                mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225]
            )
        elif ablation_type == "ijepa":
            # I-JEPA patch_size=14
            ablation_resolution = L * 14
            self.ablation_transform = det_image_transform(
                ablation_resolution,
                is_train=False,
                mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225]
            )
        else:
            raise ValueError(f"Unknown ablation type: {ablation_type}")
        
        logging.info(f"Ablation Dataset: VFM resolution={vfm_resolution if args.use_vfm else 'None'}, "
                    f"{ablation_type.upper()} resolution={ablation_resolution}")

    def read_image(self, image_name):
        image_path = os.path.join(self.image_root, image_name)
        try:
            image = Image.open(image_path)
        except:
            print(f"Cannot load {image_path}", flush=True)
            return None
        width, height = image.size
        if width < 10 or height < 10:
            print(f"Invalid image, size {image.size}", flush=True)
            return None
        return image

    def _init_choices(self, M=16):
        choices = []
        for m in range(1, M + 1):
            for n in range((m + 1) // 2, min(m * 2 + 1, M + 1)):
                choices.append((m, n))
        self.choices = choices

    def __len__(self):
        return len(self.image_ids)

    def _init_boxes(self):
        box_templates = {}
        for choice in self.choices:
            M, N = choice
            grid_x, grid_y = torch.meshgrid(
                torch.linspace(0, 1, N + 1),
                torch.linspace(0, 1, M + 1),
                indexing='xy'
            )
            x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1)
            x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1)
            pseudo_boxes = torch.cat([x0y0s, x1y1s], dim=-1).view(-1, 4)
            assert pseudo_boxes.shape[0] == M * N
            box_templates[choice] = pseudo_boxes
        self.box_templates = box_templates

    def _obtain_image_crops(self, image, choice):
        image_crops = []
        img_w, img_h = image.size
        normed_boxes = self.box_templates[choice]
        indices = list(range(len(normed_boxes)))
        random.shuffle(indices)
        indices = indices[:self.max_anns]
        boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h])
        
        for idx in indices:
            box = boxes[idx]
            x0, y0, x1, y1 = box.tolist()
            if self.args.crop_scale > 1.0:
                box_w, box_h = x1 - x0, y1 - y0
                cx, cy = (x1 + x0) / 2, (y1 + y0) / 2
                delta_factor = 0.5 * self.args.crop_scale
                x0 = max(cx - box_w * delta_factor, 0)
                y0 = max(cy - box_h * delta_factor, 0)
                x1 = min(cx + box_w * delta_factor, img_w)
                y1 = min(cy + box_h * delta_factor, img_h)
            vanilla_view = self.transforms[1](image.crop((x0, y0, x1, y1)))
            image_crops.append(vanilla_view)
        
        return torch.stack(image_crops), boxes[indices]

    def __getitem__(self, idx):
        image_id = self.image_ids[idx]
        image_info = self.coco.imgs[image_id]
        
        if 'file_name' in image_info:
            image_name = image_info['file_name']
        else:
            assert 'coco_url' in image_info
            coco_url = image_info['coco_url'].split('/')
            image_name = os.path.join(coco_url[-2], coco_url[-1])
        
        old_image = self.read_image(image_name)
        if old_image is None:
            next_id = random.choice(range(self.__len__()))
            return self.__getitem__(next_id)
        
        # VFM 图像
        if self.vfm_transform:
            vfm_image = self.vfm_transform(old_image)
        else:
            vfm_image = torch.empty(0)
        
        # 消融模型图像 (SAM 或 I-JEPA)
        ablation_image = self.ablation_transform(old_image)
        
        # CLIP 图像
        new_image = self.transforms[0](old_image)
        scale = get_scale(old_image, new_image)
        
        # Boxes 和 crops
        boxes_template = torch.zeros(self.max_anns, 4 + 1)
        image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size)
        image_crops, boxes = self._obtain_image_crops(old_image, random.choice(self.choices))
        
        assert image_crops.shape[0] == boxes.shape[0]
        _, h, w = new_image.shape
        boxes[:, :4] *= scale
        boxes[:, [0, 2]] /= w
        boxes[:, [1, 3]] /= h
        boxes_template[:boxes.shape[0], :4] = boxes
        boxes_template[:boxes.shape[0], 4] = 1.0
        image_crops_template[:boxes.shape[0]] = image_crops
        
        return new_image, boxes_template, image_crops_template, vfm_image, ablation_image


# ============ 数据加载函数 ============

@dataclass
class DataInfo:
    dataloader: DataLoader
    sampler: DistributedSampler = None

    def set_epoch(self, epoch):
        if self.sampler is not None and isinstance(self.sampler, DistributedSampler):
            self.sampler.set_epoch(epoch)


def get_ablation_sam_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
    """获取 SAM 消融实验数据集"""
    assert is_train
    input_filename = args.train_data
    assert input_filename
    
    dataset = AblationGridDistillDataset(
        input_filename=input_filename,
        transforms=preprocess_fn,
        image_root=args.train_image_root,
        crop_size=args.input_size,
        max_split=args.max_split,
        args=args,
        ablation_type="sam"
    )
    
    num_samples = len(dataset)
    sampler = DistributedSampler(dataset) if args.distributed else None
    shuffle = is_train and sampler is None
    batch_size = args.batch_size
    
    dataloader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=shuffle,
        num_workers=args.workers,
        pin_memory=True,
        sampler=sampler,
        drop_last=is_train,
    )
    dataloader.num_samples = num_samples
    dataloader.num_batches = len(dataloader)
    
    return DataInfo(dataloader, sampler)


def get_ablation_ijepa_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
    """获取 I-JEPA 消融实验数据集"""
    assert is_train
    input_filename = args.train_data
    assert input_filename
    
    dataset = AblationGridDistillDataset(
        input_filename=input_filename,
        transforms=preprocess_fn,
        image_root=args.train_image_root,
        crop_size=args.input_size,
        max_split=args.max_split,
        args=args,
        ablation_type="ijepa"
    )
    
    num_samples = len(dataset)
    sampler = DistributedSampler(dataset) if args.distributed else None
    shuffle = is_train and sampler is None
    batch_size = args.batch_size
    
    dataloader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=shuffle,
        num_workers=args.workers,
        pin_memory=True,
        sampler=sampler,
        drop_last=is_train,
    )
    dataloader.num_samples = num_samples
    dataloader.num_batches = len(dataloader)
    
    return DataInfo(dataloader, sampler)