""" 消融实验专用数据集 支持 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)