File size: 45,470 Bytes
64bce2a | 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 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 | #!/usr/bin/env python
# coding: utf-8
# simple_image_data_modified.py - 支持多层级VGG特征提取
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特征提取的模块"""
# VGG16各层级配置
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()
# ImageNet标准归一化参数
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")
# 预处理pipeline
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):
# 确保是RGB模式
if img.mode != 'RGB':
img = img.convert('RGB')
img_tensor = transform(img)
else:
# 如果已经是tensor,需要resize到224x224
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
# 确保是RGB 3通道
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():
# ImageNet标准归一化
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)) # [N, channels, 1, 1]
batch_features = batch_features.view(batch_features.size(0), -1) # [N, channels]
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 = {}
# 🔑 关键修改:支持多层级VGG特征提取
self.vgg_extractor = None
# 🔑 关键修改:分别存储train和val数据
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文件夹和val文件夹
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
# pdb.set_trace()
# 收集所有类别
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))
# 🔑 关键修改:分别处理train和val数据
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数据集"""
# 复用imagenet100的逻辑
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
# 为CIFAR创建虚拟的类别信息
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
# 假设文件夹结构为: dataset_path/class_name/images
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 # 80% 用于训练,20% 用于验证
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)
# print(cache_dir)
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):
"""获取单张图片的缓存路径 - 包含层级信息"""
# 使用图片路径和层级的hash作为缓存文件名
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)
# 分离图片路径和PIL对象
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'):
# PIL Image对象可能有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)
# Feature dropout(训练时使用)
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切换"""
# 🔑 如果没有传入 is_test_mode,从 args 中推断
if is_test_mode is None:
# 如果args中有epoch信息,可以从中推断
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'):
# 新版本:支持train/val分离
class_info = self.val_class_info if is_test_mode else self.train_class_info
else:
# 原版本:使用混合数据
class_info = self.class_info
import pdb
# pdb.set_trace()
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:
# ImageNet类型数据集或folder
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]
# 检查是否使用VGG特征且启用缓存
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:
# 返回图片路径而不是PIL对象,让VGG特征提取器处理缓存
return block_paths
else:
# 传统模式:加载PIL图片
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)
# 转回PIL Image
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
brightness_factor = 1 + (random.random() - 0.5) * noise_level
image = torch.clamp(image * brightness_factor, 0, 1)
elif rand_val < 0.66: # Contrast
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: # Saturation
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切换"""
# import pdb
# pdb.set_trace()
# 🔑 根据测试模式选择相应的数据信息
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 = []
# print(total_class_combinations,global_batch_id)
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) # 🔑 新增:支持VGG层级选择
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
# 获取epoch的映射
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
# pdb.set_trace()
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:
# 🔑 使用指定层级的VGG特征提取(带缓存)
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)
# 填充到100个样本
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)
# k近邻
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)
# 堆叠所有batch数据
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] # 显示前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层级支持
"""
# os.makedirs(data_dir, exist_ok=True)
# 获取参数
dataset_type = getattr(args, 'dataset_type', 'imagenet100')
use_vgg_features = getattr(args, 'use_vgg_features', False)
vgg_level = getattr(args, 'vgg_level', 29) # 🔑 新增:VGG层级参数
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
# pdb.set_trace()
# 计算特征向量
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 # 🔑 保存层级信息
}
# rsync -acz /hpc/group/chenglab/zl310/spring2025_projects/InterpStableDiffusion/results/interp_res_swissroll /work/jf381/data/icl_jay/interp_res_swissroll
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 |