| |
| |
|
|
| |
|
|
| import os |
| import torch |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| from tqdm import tqdm |
| import torchvision.transforms as transforms |
| import torchvision.datasets as datasets |
| from torchvision.models import vgg16 |
| import torch.nn.functional as F |
| import random |
| from collections import defaultdict |
| import json |
| import warnings |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| import threading |
| import multiprocessing as mp |
| import time |
| import hashlib |
|
|
| class VGGMultiLevelExtractor: |
| """支持多层级VGG特征提取的模块""" |
| |
| |
| VGG_LEVELS = { |
| 3: {'name': 'MaxPool_Block1', 'channels': 64, 'layer_idx': 3}, |
| 8: {'name': 'MaxPool_Block2', 'channels': 128, 'layer_idx': 8}, |
| 15: {'name': 'MaxPool_Block3', 'channels': 256, 'layer_idx': 15}, |
| 22: {'name': 'MaxPool_Block4', 'channels': 512, 'layer_idx': 22}, |
| 29: {'name': 'MaxPool_Block5', 'channels': 512, 'layer_idx': 29} |
| } |
| |
| def __init__(self, device='cuda'): |
| self.device = device |
| self.vgg_model = None |
| self.normalize = None |
| self.vgg_input_size = 224 |
| self._init_vgg_model() |
| |
| def _init_vgg_model(self): |
| """初始化VGG模型""" |
| print(f"Loading VGG16 model on {self.device}...") |
| full_vgg = vgg16(pretrained=True) |
| self.vgg_features = full_vgg.features.to(self.device) |
| self.vgg_features.eval() |
| |
| |
| self.normalize = transforms.Normalize( |
| mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| |
| print("VGG16 model loaded successfully!") |
| print(f"Available levels: {list(self.VGG_LEVELS.keys())}") |
| |
| def extract_features_at_level(self, images, level=29): |
| """在指定层级提取VGG特征 |
| |
| Args: |
| images: 图片列表(PIL Images或路径) |
| level: VGG层级(3, 8, 15, 22, 29) |
| |
| Returns: |
| torch.Tensor: 提取的特征,形状为 [N, channels] |
| """ |
| if level not in self.VGG_LEVELS: |
| raise ValueError(f"Unsupported level {level}. Available: {list(self.VGG_LEVELS.keys())}") |
| |
| level_info = self.VGG_LEVELS[level] |
| layer_idx = level_info['layer_idx'] |
| expected_channels = level_info['channels'] |
| |
| print(f"Extracting features at level {level} ({level_info['name']}) - {expected_channels} channels") |
| |
| |
| transform = transforms.Compose([ |
| transforms.Resize((self.vgg_input_size, self.vgg_input_size)), |
| transforms.ToTensor() |
| ]) |
| |
| |
| img_tensors = [] |
| for img in images: |
| if img is None: |
| continue |
| |
| if isinstance(img, str): |
| |
| img = Image.open(img).convert('RGB') |
| |
| if isinstance(img, Image.Image): |
| |
| if img.mode != 'RGB': |
| img = img.convert('RGB') |
| img_tensor = transform(img) |
| else: |
| |
| if img.dim() == 3: |
| img_tensor = F.interpolate(img.unsqueeze(0), |
| size=(self.vgg_input_size, self.vgg_input_size), |
| mode='bilinear', align_corners=False).squeeze(0) |
| else: |
| img_tensor = img |
| |
| |
| if img_tensor.shape[0] == 1: |
| img_tensor = img_tensor.repeat(3, 1, 1) |
| elif img_tensor.shape[0] != 3: |
| img_tensor = img_tensor[:3] |
| |
| img_tensors.append(img_tensor) |
| |
| if not img_tensors: |
| return torch.zeros(0, expected_channels, device=self.device) |
| |
| batch_tensor = torch.stack(img_tensors).to(self.device) |
| |
| with torch.no_grad(): |
| |
| normalized_batch = torch.stack([self.normalize(img) for img in batch_tensor]) |
| |
| |
| process_batch_size = 16 |
| features_list = [] |
| |
| for i in range(0, len(normalized_batch), process_batch_size): |
| batch = normalized_batch[i:i+process_batch_size] |
| |
| |
| x = batch |
| for idx, layer in enumerate(self.vgg_features): |
| x = layer(x) |
| if idx == layer_idx: |
| break |
| |
| |
| batch_features = F.adaptive_avg_pool2d(x, (1, 1)) |
| batch_features = batch_features.view(batch_features.size(0), -1) |
| |
| features_list.append(batch_features) |
| |
| if features_list: |
| features = torch.cat(features_list, dim=0) |
| else: |
| features = torch.zeros(0, expected_channels, device=self.device) |
| |
| print(f"Extracted features shape: {features.shape}") |
| return features |
|
|
| class SimpleImageDataLoader: |
| def __init__(self, dataset_type='imagenet100', dataset_path=None, samples_per_block=50): |
| self.dataset_type = dataset_type |
| self.dataset_path = dataset_path |
| self.samples_per_block = samples_per_block |
| self.class_info = {} |
| self.total_blocks_per_class = {} |
| |
| |
| self.vgg_extractor = None |
| |
| |
| self.train_class_info = {} |
| self.val_class_info = {} |
| self.train_blocks_per_class = {} |
| self.val_blocks_per_class = {} |
| |
| |
| self._scan_dataset() |
|
|
| def _scan_dataset(self): |
| """扫描数据集,获取每个类别的图片路径和块数""" |
| print(f"Scanning {self.dataset_type} dataset...") |
| |
| if self.dataset_type == 'imagenet100': |
| self._scan_imagenet100() |
| elif self.dataset_type == 'imagenet10': |
| self._scan_imagenet10() |
| elif self.dataset_type in ['cifar10', 'cifar100']: |
| self._scan_cifar() |
| elif self.dataset_type == 'folder': |
| self._scan_folder() |
| |
| print(f"Found {len(self.class_info)} classes") |
| for class_idx, info in list(self.class_info.items())[:5]: |
| print(f" Class {class_idx}: {info['total_images']} images, {self.total_blocks_per_class[class_idx]} blocks") |
| if len(self.class_info) > 5: |
| print(f" ... and {len(self.class_info) - 5} more classes") |
|
|
| def _scan_imagenet100(self): |
| """修改后的ImageNet100扫描 - 分别存储train和val""" |
| print(f"Scanning {self.dataset_type} dataset...") |
| |
| |
| train_folders = [] |
| val_folder = None |
| print(self.dataset_path) |
| if os.path.exists(self.dataset_path): |
| for item in os.listdir(self.dataset_path): |
| item_path = os.path.join(self.dataset_path, item) |
| if os.path.isdir(item_path): |
| if item.startswith('train.X'): |
| train_folders.append(item_path) |
| elif item == 'val.X': |
| val_folder = item_path |
| |
| train_folders.sort() |
| import pdb |
| |
| |
| all_classes = set() |
| for train_folder in train_folders: |
| if os.path.exists(train_folder): |
| classes = [f for f in os.listdir(train_folder) |
| if os.path.isdir(os.path.join(train_folder, f)) and f.startswith('n')] |
| all_classes.update(classes) |
| |
| all_classes = sorted(list(all_classes)) |
| |
| |
| for class_idx, class_name in enumerate(all_classes): |
| train_paths = [] |
| val_paths = [] |
| |
| |
| for train_folder in train_folders: |
| class_path = os.path.join(train_folder, class_name) |
| if os.path.exists(class_path): |
| files = [f for f in os.listdir(class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| files.sort() |
| paths = [os.path.join(class_path, f) for f in files] |
| train_paths.extend(paths) |
| |
| |
| if val_folder: |
| val_class_path = os.path.join(val_folder, class_name) |
| if os.path.exists(val_class_path): |
| files = [f for f in os.listdir(val_class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| files.sort() |
| paths = [os.path.join(val_class_path, f) for f in files] |
| val_paths.extend(paths) |
| |
| |
| self.train_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': train_paths, |
| 'total_images': len(train_paths) |
| } |
| self.train_blocks_per_class[class_idx] = max(1, len(train_paths) // self.samples_per_block) |
| |
| self.val_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': val_paths, |
| 'total_images': len(val_paths) |
| } |
| self.val_blocks_per_class[class_idx] = max(1, len(val_paths) // self.samples_per_block) |
| |
| |
| all_paths = train_paths + val_paths |
| self.class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': all_paths, |
| 'total_images': len(all_paths) |
| } |
| self.total_blocks_per_class[class_idx] = max(1, len(all_paths) // self.samples_per_block) |
| |
| print(f"Found {len(all_classes)} classes") |
| print(f"Train images per class (first 3): {[self.train_class_info[i]['total_images'] for i in range(min(3, len(all_classes)))]}") |
| print(f"Val images per class (first 3): {[self.val_class_info[i]['total_images'] for i in range(min(3, len(all_classes)))]}") |
| |
| def _scan_imagenet10(self): |
| """扫描ImageNet10数据集""" |
| |
| self._scan_imagenet100() |
| |
| def _scan_cifar(self): |
| """扫描CIFAR数据集""" |
| try: |
| if self.dataset_type == 'cifar10': |
| dataset = datasets.CIFAR10(self.dataset_path or './data', train=True, download=True) |
| num_classes = 10 |
| else: |
| dataset = datasets.CIFAR100(self.dataset_path or './data', train=True, download=True) |
| num_classes = 100 |
| |
| |
| for class_idx in range(num_classes): |
| class_indices = [i for i, (_, label) in enumerate(dataset) if label == class_idx] |
| |
| self.class_info[class_idx] = { |
| 'class_name': f'cifar_class_{class_idx}', |
| 'image_paths': class_indices, |
| 'total_images': len(class_indices) |
| } |
| self.total_blocks_per_class[class_idx] = max(1, len(class_indices) // self.samples_per_block) |
| |
| except Exception as e: |
| print(f"Error scanning CIFAR dataset: {e}") |
| |
| def _scan_folder(self): |
| """扫描文件夹结构的数据集 - 手动分割train/val""" |
| if not os.path.exists(self.dataset_path): |
| print(f"Dataset path does not exist: {self.dataset_path}") |
| return |
| |
| |
| class_folders = [f for f in os.listdir(self.dataset_path) |
| if os.path.isdir(os.path.join(self.dataset_path, f))] |
| class_folders.sort() |
| |
| |
| train_ratio = 0.8 |
| |
| for class_idx, class_name in enumerate(class_folders): |
| class_path = os.path.join(self.dataset_path, class_name) |
| files = [f for f in os.listdir(class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| files.sort() |
| image_paths = [os.path.join(class_path, f) for f in files] |
| |
| |
| total_images = len(image_paths) |
| train_split_idx = int(total_images * train_ratio) |
| |
| |
| train_paths = image_paths[:train_split_idx] |
| val_paths = image_paths[train_split_idx:] |
| |
| |
| self.train_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': train_paths, |
| 'total_images': len(train_paths) |
| } |
| self.train_blocks_per_class[class_idx] = max(1, len(train_paths) // self.samples_per_block) |
| |
| self.val_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': val_paths, |
| 'total_images': len(val_paths) |
| } |
| self.val_blocks_per_class[class_idx] = max(1, len(val_paths) // self.samples_per_block) |
| |
| |
| self.class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': image_paths, |
| 'total_images': len(image_paths) |
| } |
| self.total_blocks_per_class[class_idx] = max(1, len(image_paths) // self.samples_per_block) |
| |
| print(f"Found {len(class_folders)} classes") |
| print(f"Train/Val split ratio: {train_ratio:.1f}/{1-train_ratio:.1f}") |
| if class_folders: |
| print(f"Train images per class (first 3): {[self.train_class_info[i]['total_images'] for i in range(min(3, len(class_folders)))]}") |
| print(f"Val images per class (first 3): {[self.val_class_info[i]['total_images'] for i in range(min(3, len(class_folders)))]}") |
| def _get_current_class_info(self, is_test_mode=False): |
| """根据是否为测试模式返回相应的class_info""" |
| if is_test_mode: |
| return self.val_class_info, self.val_blocks_per_class |
| else: |
| return self.train_class_info, self.train_blocks_per_class |
| |
| def _get_vgg_cache_dir(self, args, level=29): |
| """获取VGG特征缓存目录 - 支持多层级""" |
| if not args or not hasattr(args, 'dataset_path'): |
| return None |
| |
| base_path = getattr(args, 'dataset_path', '') |
| if not base_path: |
| return None |
|
|
| cache_components = [f'vgg_level{level}'] |
|
|
| if hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| cache_components.append(f"noise{args.embedding_noise_level}") |
|
|
| if hasattr(args, 'normalize_features') and args.normalize_features: |
| cache_components.append("norm") |
|
|
| cache_suffix = '_'.join(cache_components) |
| |
| cache_dir = f"{base_path}_{cache_suffix}" |
| cache_dir = cache_dir.replace('/hpc/group/chenglab/zl310/spring2025_projects/InterpStableDiffusion/results/interp_res_slerp','/work/jf381/data/icl_jay/interp_res_slerp') |
| return cache_dir |
| |
| def get_vgg_features(self, images, device='cuda', args=None, level=29): |
| """获取VGG特征 - 支持多层级和缓存机制""" |
| if self.vgg_extractor is None: |
| self.vgg_extractor = VGGMultiLevelExtractor(device=device) |
| |
| if not images: |
| expected_channels = VGGMultiLevelExtractor.VGG_LEVELS[level]['channels'] |
| return torch.zeros(0, expected_channels, device=device) |
| |
| |
| cache_dir = self._get_vgg_cache_dir(args, level) |
| if cache_dir: |
| return self._get_vgg_features_with_cache(images, device, args, cache_dir, level) |
| else: |
| return self._extract_vgg_features(images, device, args, level) |
| |
| def _get_image_cache_path(self, image_path, cache_dir, level=29): |
| """获取单张图片的缓存路径 - 包含层级信息""" |
| |
| content = f"{image_path}_level{level}" |
| path_hash = hashlib.md5(content.encode()).hexdigest() |
| return os.path.join(cache_dir, f"{path_hash}.pt") |
| |
| def _get_vgg_features_with_cache(self, images, device, args, cache_dir, level=29): |
| """带缓存的VGG特征提取 - 支持多层级""" |
| os.makedirs(cache_dir, exist_ok=True) |
| |
| |
| image_paths = [] |
| pil_images = [] |
| |
| for img in images: |
| if isinstance(img, str): |
| |
| image_paths.append(img) |
| try: |
| pil_img = Image.open(img).convert('RGB') |
| pil_images.append(pil_img) |
| except: |
| pil_images.append(None) |
| elif hasattr(img, 'filename'): |
| |
| image_paths.append(getattr(img, 'filename', '')) |
| pil_images.append(img) |
| else: |
| |
| image_paths.append('') |
| pil_images.append(img) |
| |
| |
| cached_features = [] |
| uncached_indices = [] |
| uncached_images = [] |
| |
| for i, (img_path, pil_img) in enumerate(zip(image_paths, pil_images)): |
| if img_path and os.path.exists(img_path): |
| cache_path = self._get_image_cache_path(img_path, cache_dir, level) |
| |
| if os.path.exists(cache_path): |
| try: |
| |
| cached_feature = torch.load(cache_path, map_location=device) |
| cached_features.append((i, cached_feature)) |
| continue |
| except: |
| pass |
| |
| |
| uncached_indices.append(i) |
| uncached_images.append(pil_img) |
| |
| |
| if uncached_images: |
| level_name = VGGMultiLevelExtractor.VGG_LEVELS[level]['name'] |
| print(f"Computing VGG level {level} ({level_name}) features for {len(uncached_images)} uncached images...") |
| new_features = self._extract_vgg_features(uncached_images, device, args, level) |
| |
| |
| for j, (original_idx, feature) in enumerate(zip(uncached_indices, new_features)): |
| img_path = image_paths[original_idx] |
| if img_path and os.path.exists(img_path): |
| cache_path = self._get_image_cache_path(img_path, cache_dir, level) |
| try: |
| torch.save(feature.cpu(), cache_path) |
| except Exception as e: |
| print(f"Failed to cache feature for {img_path}: {e}") |
| else: |
| expected_channels = VGGMultiLevelExtractor.VGG_LEVELS[level]['channels'] |
| new_features = torch.zeros(0, expected_channels, device=device) |
| |
| |
| expected_channels = VGGMultiLevelExtractor.VGG_LEVELS[level]['channels'] |
| all_features = torch.zeros(len(images), expected_channels, device=device) |
| |
| |
| for original_idx, cached_feature in cached_features: |
| all_features[original_idx] = cached_feature.to(device) |
| |
| |
| new_feature_idx = 0 |
| for original_idx in uncached_indices: |
| if new_feature_idx < len(new_features): |
| all_features[original_idx] = new_features[new_feature_idx] |
| new_feature_idx += 1 |
| |
| return all_features |
| |
| def _extract_vgg_features(self, images, device, args, level=29): |
| """实际的VGG特征提取逻辑 - 支持多层级""" |
| |
| features = self.vgg_extractor.extract_features_at_level(images, level) |
| |
| |
| if args and hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| noise = torch.randn_like(features) * args.embedding_noise_level |
| features = features + noise |
| |
| |
| if args and hasattr(args, 'normalize_features') and args.normalize_features: |
| features = F.normalize(features, p=2, dim=1) |
| |
| |
| if args and hasattr(args, 'feature_dropout') and args.feature_dropout > 0: |
| if hasattr(self.vgg_extractor, 'training') and self.vgg_extractor.training: |
| features = F.dropout(features, p=args.feature_dropout, training=True) |
| |
| return features |
|
|
| def load_images_for_class_block(self, class_idx, block_idx, args=None, is_test_mode=None): |
| """加载指定类别和块的图片 - 支持train/val切换""" |
| |
| |
| if is_test_mode is None: |
| |
| if args and hasattr(args, 'current_epoch'): |
| is_test_mode = args.current_epoch >= 99999 |
| else: |
| is_test_mode = False |
| |
| |
| if hasattr(self, 'train_class_info') and hasattr(self, 'val_class_info'): |
| |
| class_info = self.val_class_info if is_test_mode else self.train_class_info |
| else: |
| |
| class_info = self.class_info |
| import pdb |
| |
| if class_idx not in class_info: |
| return [] |
| |
| class_data = class_info[class_idx] |
| |
| if self.dataset_type in ['cifar10', 'cifar100']: |
| return self._load_cifar_block(class_idx, block_idx, is_test_mode) |
| else: |
| |
| image_paths = class_data['image_paths'] |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(image_paths)) |
| |
| if start_idx >= len(image_paths): |
| |
| start_idx = max(0, len(image_paths) - self.samples_per_block) |
| end_idx = len(image_paths) |
| |
| block_paths = image_paths[start_idx:end_idx] |
| |
| |
| use_vgg = getattr(args, 'use_vgg_features', False) if args else False |
| cache_dir = self._get_vgg_cache_dir(args, getattr(args, 'vgg_level', 29)) if args else None |
| |
| if use_vgg and cache_dir: |
| |
| return block_paths |
| else: |
| |
| images = [] |
| for img_path in block_paths: |
| try: |
| img = Image.open(img_path).convert('RGB') |
| |
| |
| if args and hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| aug_type = getattr(args, 'image_aug_type', 'pixel') |
| img_tensor = self.apply_image_augmentation(img, args.image_noise_level, aug_type) |
| |
| img = transforms.ToPILImage()(img_tensor) |
| |
| images.append(img) |
| except Exception as e: |
| print(f"Error loading {img_path}: {e}") |
| continue |
| |
| return images |
|
|
| def _load_cifar_block(self, class_idx, block_idx, is_test_mode=False): |
| """加载CIFAR数据集的指定块""" |
| try: |
| if self.dataset_type == 'cifar10': |
| dataset = datasets.CIFAR10(self.dataset_path or './data', train=not is_test_mode, download=True) |
| else: |
| dataset = datasets.CIFAR100(self.dataset_path or './data', train=not is_test_mode, download=True) |
| |
| |
| class_indices = [i for i, (_, label) in enumerate(dataset) if label == class_idx] |
| |
| |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(class_indices)) |
| |
| if start_idx >= len(class_indices): |
| start_idx = max(0, len(class_indices) - self.samples_per_block) |
| end_idx = len(class_indices) |
| |
| selected_indices = class_indices[start_idx:end_idx] |
| |
| |
| images = [] |
| for idx in selected_indices: |
| img, _ = dataset[idx] |
| images.append(img) |
| |
| return images |
| |
| except Exception as e: |
| print(f"Error loading CIFAR block: {e}") |
| return [] |
|
|
| def apply_image_augmentation(self, image, noise_level=0.0, aug_type='pixel'): |
| """图像增强函数""" |
| if noise_level <= 0: |
| return image |
| |
| if isinstance(image, Image.Image): |
| image = transforms.ToTensor()(image) |
| |
| if aug_type == 'pixel': |
| |
| noise = torch.randn_like(image) * noise_level |
| image = torch.clamp(image + noise, 0, 1) |
| elif aug_type == 'color': |
| |
| rand_val = random.random() |
| if rand_val < 0.33: |
| brightness_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp(image * brightness_factor, 0, 1) |
| elif rand_val < 0.66: |
| mean_val = image.mean() |
| contrast_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp((image - mean_val) * contrast_factor + mean_val, 0, 1) |
| else: |
| if image.shape[0] == 3: |
| gray = 0.299 * image[0] + 0.587 * image[1] + 0.114 * image[2] |
| saturation_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp(gray.unsqueeze(0) + (image - gray.unsqueeze(0)) * saturation_factor, 0, 1) |
| |
| return image |
|
|
| def get_epoch_mapping(self, epoch, batch_size, class_combination_seed=42, is_test_mode=False): |
| """修改后的epoch映射 - 支持train/val切换""" |
| |
| |
| |
| class_info, blocks_per_class = self._get_current_class_info(is_test_mode) |
| num_classes = len(class_info) |
| |
| |
| random.seed(class_combination_seed + epoch) |
| np.random.seed(class_combination_seed + epoch) |
| |
| |
| total_class_combinations = num_classes * (num_classes - 1) |
| |
| |
| max_blocks = max(blocks_per_class.values()) if blocks_per_class else 1 |
| |
| batch_mappings = [] |
| |
| for batch_idx in range(batch_size): |
| global_batch_id = epoch * batch_size + batch_idx |
| print(total_class_combinations,global_batch_id) |
| |
| block_round = global_batch_id // total_class_combinations |
| |
| |
| combination_idx = global_batch_id % total_class_combinations |
| |
| |
| class1 = combination_idx // (num_classes - 1) |
| class2_offset = combination_idx % (num_classes - 1) |
| class2 = class2_offset if class2_offset < class1 else class2_offset + 1 |
| |
| |
| block1 = block_round % blocks_per_class.get(class1, 1) |
| block2 = block_round % blocks_per_class.get(class2, 1) |
| |
| batch_mappings.append({ |
| 'batch_idx': batch_idx, |
| 'global_batch_id': global_batch_id, |
| 'class1': class1, |
| 'class2': class2, |
| 'block1': block1, |
| 'block2': block2, |
| 'block_round': block_round, |
| 'is_test_mode': is_test_mode |
| }) |
| |
| return batch_mappings |
|
|
| def generate_batch_data(self, epoch, batch_size, device='cuda', args=None): |
| use_vgg_features = getattr(args, 'use_vgg_features', False) |
| vgg_level = getattr(args, 'vgg_level', 29) |
| downsample_size = getattr(args, 'downsample_size', 32) |
| scale_rbf = getattr(args, 'scale_rbf', 1.0) |
| k_nn = getattr(args, 'k_nn', 10) |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) |
| n_samples_per_class = getattr(args, 'n_samples_per_class', 50) |
| |
| |
| is_test_mode = epoch >= 99999 |
| |
| |
| batch_mappings = self.get_epoch_mapping(epoch, batch_size, class_combination_seed, is_test_mode) |
| |
| data_source = "VALIDATION" if is_test_mode else "TRAINING" |
| level_info = VGGMultiLevelExtractor.VGG_LEVELS[vgg_level] |
| print(f"Loading epoch {epoch} from {data_source} set...") |
| if use_vgg_features: |
| print(f"Using VGG level {vgg_level} ({level_info['name']}) with {level_info['channels']} channels") |
| |
| all_raw_data = [] |
| all_labels = [] |
| all_laplacians = [] |
| all_adjacencies = [] |
| |
| for mapping in tqdm(batch_mappings, desc=f"Loading {data_source} epoch {epoch}"): |
| class1, class2 = mapping['class1'], mapping['class2'] |
| block1, block2 = mapping['block1'], mapping['block2'] |
| |
| |
| images1 = self.load_images_for_class_block(class1, block1, args, is_test_mode) |
| images2 = self.load_images_for_class_block(class2, block2, args, is_test_mode) |
| |
| |
| if len(images1) > n_samples_per_class: |
| images1 = images1[:n_samples_per_class] |
| if len(images2) > n_samples_per_class: |
| images2 = images2[:n_samples_per_class] |
| |
| |
| all_images = images1 + images2 |
| all_batch_labels = [0] * len(images1) + [1] * len(images2) |
| import pdb |
| |
| if len(all_images) == 0: |
| |
| if use_vgg_features: |
| img_dim = level_info['channels'] |
| else: |
| img_dim = 32 * 32 * 3 |
| raw_data = torch.zeros(100, img_dim, device=device) |
| labels = torch.randint(0, 2, (100,), dtype=torch.long, device=device) |
| laplacian = torch.eye(100, device=device) |
| adjacency = torch.eye(100, device=device) * 1e-6 |
| else: |
| |
| if use_vgg_features: |
| |
| print(f"Extracting VGG level {vgg_level} features for batch (class {class1} & {class2})...") |
| raw_data = self.get_vgg_features(all_images, device, args, level=vgg_level) |
| else: |
| |
| processed_images = [] |
| for img in all_images: |
| if isinstance(img, str): |
| |
| img = Image.open(img).convert('RGB') |
| |
| if isinstance(img, Image.Image): |
| if downsample_size and downsample_size != img.size[0]: |
| img = img.resize((downsample_size, downsample_size), Image.LANCZOS) |
| img_tensor = transforms.ToTensor()(img) |
| else: |
| img_tensor = img |
| |
| if img_tensor.shape[0] == 3: |
| img_tensor = transforms.functional.rgb_to_grayscale(img_tensor) |
| |
| processed_images.append(img_tensor) |
| |
| if processed_images: |
| img_data_tensor = torch.stack(processed_images) |
| raw_data = img_data_tensor.view(img_data_tensor.shape[0], -1).to(device) |
| else: |
| raw_data = torch.zeros(0, 32*32, device=device) |
| |
| |
| current_size = raw_data.shape[0] |
| if current_size < 100: |
| padding_size = 100 - current_size |
| feature_dim = raw_data.shape[1] |
| padding_data = torch.zeros(padding_size, feature_dim, device=device) |
| raw_data = torch.cat([raw_data, padding_data], dim=0) |
| |
| padding_labels = torch.randint(0, 2, (padding_size,), dtype=torch.long, device=device) |
| all_batch_labels.extend(padding_labels.tolist()) |
| elif current_size > 100: |
| raw_data = raw_data[:100] |
| all_batch_labels = all_batch_labels[:100] |
| |
| labels = torch.tensor(all_batch_labels, dtype=torch.long, device=device) |
| |
| |
| distances = torch.cdist(raw_data, raw_data, p=2) |
| adjacency = torch.exp(-scale_rbf * distances ** 2) |
| |
| |
| adjacency_copy = adjacency.clone() |
| adjacency_copy.fill_diagonal_(0.0) |
| _, nn_indices = torch.topk(adjacency_copy, k_nn, dim=1) |
| |
| |
| adj_matrix = torch.zeros_like(adjacency, device=device) |
| batch_indices = torch.arange(100, device=device).unsqueeze(1).expand(-1, k_nn) |
| adj_matrix[batch_indices, nn_indices] = adjacency[batch_indices, nn_indices] |
| adj_matrix[nn_indices, batch_indices] = adjacency[nn_indices, batch_indices] |
| adj_matrix.fill_diagonal_(1e-6) |
| adjacency = adj_matrix |
| |
| |
| degree = adjacency.sum(dim=1) |
| degree = torch.clamp(degree, min=1e-10) |
| D_inv_sqrt = torch.diag(degree.pow(-0.5)).to(device) |
| laplacian = torch.eye(100, device=device) - D_inv_sqrt @ adjacency @ D_inv_sqrt |
| |
| all_raw_data.append(raw_data) |
| all_labels.append(labels) |
| all_laplacians.append(laplacian) |
| all_adjacencies.append(adjacency) |
| |
| |
| final_raw_data = torch.stack(all_raw_data, dim=0) |
| final_labels = torch.stack(all_labels, dim=0) |
| final_laplacians = torch.stack(all_laplacians, dim=0) |
| final_adjacencies = torch.stack(all_adjacencies, dim=0) |
| |
| return final_raw_data, final_laplacians, final_labels, final_adjacencies |
|
|
| |
| def clean_vgg_cache(dataset_path, level=29, noise_level=None): |
| """清理VGG特征缓存""" |
| cache_components = [f'vgg_level{level}'] |
| if noise_level is not None: |
| cache_components.append(f"noise{noise_level}") |
| |
| cache_dir = f"{dataset_path}_{'_'.join(cache_components)}" |
| |
| if os.path.exists(cache_dir): |
| import shutil |
| shutil.rmtree(cache_dir) |
| print(f"Cleaned VGG level {level} cache: {cache_dir}") |
| else: |
| print(f"Cache directory does not exist: {cache_dir}") |
|
|
| def get_vgg_cache_info(dataset_path, level=29, noise_level=None): |
| """获取VGG缓存信息""" |
| cache_components = [f'vgg_level{level}'] |
| if noise_level is not None: |
| cache_components.append(f"noise{noise_level}") |
| |
| cache_dir = f"{dataset_path}_{'_'.join(cache_components)}" |
| |
| if not os.path.exists(cache_dir): |
| return {"exists": False, "path": cache_dir, "level": level} |
| |
| |
| cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')] |
| total_size = sum(os.path.getsize(os.path.join(cache_dir, f)) for f in cache_files) |
| |
| level_info = VGGMultiLevelExtractor.VGG_LEVELS[level] |
| |
| return { |
| "exists": True, |
| "path": cache_dir, |
| "level": level, |
| "level_name": level_info['name'], |
| "channels": level_info['channels'], |
| "num_files": len(cache_files), |
| "total_size_mb": total_size / (1024 * 1024), |
| "files": cache_files[:10] |
| } |
|
|
| |
| def get_or_generate_data_image( |
| epoch, |
| batch_size, |
| n_samples, |
| scale_rbf, |
| k_nn, |
| device, |
| label_percent, |
| context_size, |
| k_feat, |
| data_dir="./cached_data", |
| image_dir="./data", |
| force=False, |
| downsample_size=32, |
| scale_factor=1.0, |
| pixel_scale_factor=None, |
| manifold_list=None, |
| prod_threshold=None, |
| args=None |
| ): |
| """ |
| 主数据生成函数 - 保持原有接口兼容性,新增VGG层级支持 |
| """ |
| |
| |
| |
| dataset_type = getattr(args, 'dataset_type', 'imagenet100') |
| use_vgg_features = getattr(args, 'use_vgg_features', False) |
| vgg_level = getattr(args, 'vgg_level', 29) |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) |
| test_class_combination_seed = getattr(args, 'test_class_combination_seed', 12345) |
| |
| |
| is_test = epoch >= 99999 |
| seed_to_use = test_class_combination_seed if is_test else class_combination_seed |
| |
| |
| cache_components = [ |
| f"epoch_{epoch}", |
| f"mode_{'test' if is_test else 'train'}", |
| f"bs{batch_size}", |
| f"seed{seed_to_use}", |
| f"dataset{dataset_type}", |
| f"vgg_level{vgg_level}" if use_vgg_features else "pixel", |
| f"ds{downsample_size}" if downsample_size else "nods", |
| f"scale{scale_factor}" if scale_factor != 1.0 else "noscale", |
| f"scale_rbf{scale_rbf}" |
| ] |
| |
| |
| if hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| cache_components.append(f"imgnoise{args.image_noise_level}_{getattr(args, 'image_aug_type', 'pixel')}") |
| |
| if hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| cache_components.append(f"embnoise{args.embedding_noise_level}") |
| |
| cache_file = os.path.join(data_dir, f"data_{'_'.join(cache_components)}.pt") |
| print(f"Cache file: {cache_file}") |
| |
| |
| if not force and os.path.exists(cache_file): |
| try: |
| print(f"Loading cached data from {cache_file}") |
| cached_data = torch.load(cache_file, map_location=device) |
| |
| raw_data = cached_data['raw_data'].to(device) |
| real_lap = cached_data['real_lap'].to(device) |
| labels_tensor = cached_data['labels_tensor'].to(device) |
| real_adj = cached_data['real_adj'].to(device) |
| real_ev = cached_data['real_ev'].to(device) |
| |
| |
| n_labeled = int(100 * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(100, device=device)[:n_labeled] for _ in range(batch_size)]) |
| context_indices = torch.stack([torch.randperm(n_labeled, device=device)[:context_size] for _ in range(batch_size)]) |
| |
| all_indices = torch.arange(n_labeled, device=device).expand(batch_size, n_labeled) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool, device=device) |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size) |
| |
| return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev |
| |
| except Exception as e: |
| print(f"Failed to load cached data: {e}") |
| |
| |
| if args: |
| args_copy = type(args)() |
| for attr in dir(args): |
| if not attr.startswith('_'): |
| setattr(args_copy, attr, getattr(args, attr)) |
| args_copy.class_combination_seed = seed_to_use |
| args = args_copy |
| |
| loader = SimpleImageDataLoader( |
| dataset_type=dataset_type, |
| dataset_path=image_dir, |
| samples_per_block=getattr(args, 'n_samples_per_class', 50) if args else 50 |
| ) |
| |
| |
| start_time = time.time() |
| if use_vgg_features: |
| level_info = VGGMultiLevelExtractor.VGG_LEVELS[vgg_level] |
| print(f"Generating data for epoch {epoch} using VGG level {vgg_level} ({level_info['name']})...") |
| else: |
| print(f"Generating data for epoch {epoch}...") |
| |
| raw_data, real_lap, labels_tensor, real_adj = loader.generate_batch_data( |
| epoch=epoch, |
| batch_size=batch_size, |
| device=device, |
| args=args |
| ) |
| import pdb |
| |
| |
| real_eigs = [] |
| for b in range(batch_size): |
| try: |
| _, vecs = torch.linalg.eigh(real_lap[b]) |
| real_eigs.append(vecs[:, :k_feat]) |
| except Exception: |
| real_eigs.append(torch.eye(100, k_feat, device=device)) |
| |
| real_ev = torch.stack(real_eigs, dim=0) |
| |
| |
| n_labeled = int(100 * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(100, device=device)[:n_labeled] for _ in range(batch_size)]) |
| context_indices = torch.stack([torch.randperm(n_labeled, device=device)[:context_size] for _ in range(batch_size)]) |
| |
| all_indices = torch.arange(n_labeled, device=device).expand(batch_size, n_labeled) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool, device=device) |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size) |
| |
| generation_time = time.time() - start_time |
| print(f"Data generation completed in {generation_time:.2f} seconds") |
| |
| |
| cached_data = { |
| 'raw_data': raw_data.cpu(), |
| 'real_lap': real_lap.cpu(), |
| 'labels_tensor': labels_tensor.cpu(), |
| 'real_adj': real_adj.cpu(), |
| 'real_ev': real_ev.cpu(), |
| 'generation_time': generation_time, |
| 'dataset_type': dataset_type, |
| 'epoch': epoch, |
| 'seed_used': seed_to_use, |
| 'vgg_level': vgg_level if use_vgg_features else None |
| } |
| |
| try: |
| torch.save(cached_data, cache_file) |
| print(f"Data cached to {cache_file}") |
| except Exception as e: |
| print(f"Failed to cache data: {e}") |
| |
| return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev |