#!/usr/bin/env python3 # vgg_cache_builder_multilevel.py - 支持多层级VGG特征缓存 import os import sys import torch import numpy as np from PIL import Image import torchvision.transforms as transforms from torchvision.models import vgg16 import torch.nn.functional as F from tqdm import tqdm import argparse import hashlib import time from collections import defaultdict import threading from concurrent.futures import ThreadPoolExecutor import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, classification_report from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import warnings warnings.filterwarnings('ignore') class MultiLevelVGGCacheBuilder: """支持多层级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, dataset_path, base_cache_dir, device='cuda', batch_size=16, levels_to_cache=None): self.dataset_path = dataset_path self.base_cache_dir = base_cache_dir self.device = device self.batch_size = batch_size self.vgg_features = None self.normalize = None self.vgg_input_size = 224 # 设置要缓存的层级 if levels_to_cache is None: self.levels_to_cache = list(self.VGG_LEVELS.keys()) # 默认缓存所有层级 else: self.levels_to_cache = levels_to_cache # 初始化VGG模型 self._init_vgg_model() # 扫描数据集 self.class_info = {} self.total_blocks_per_class = {} self._scan_dataset() 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"Will cache levels: {self.levels_to_cache}") for level in self.levels_to_cache: level_info = self.VGG_LEVELS[level] print(f" Level {level}: {level_info['name']} ({level_info['channels']} channels)") def _scan_dataset(self): """扫描ImageNet100数据集""" print(f"Scanning dataset: {self.dataset_path}") # 找到所有train文件夹和val文件夹 train_folders = [] val_folder = None 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() print(f"Found {len(train_folders)} train folders and {'1' if val_folder else '0'} val folder") # 收集所有类别 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)) print(f"Found {len(all_classes)} classes") # 为每个类别收集图片路径 for class_idx, class_name in enumerate(all_classes): all_paths = [] # 从所有train文件夹收集 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] all_paths.extend(paths) # 从val文件夹收集(如果存在) 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] all_paths.extend(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) // 50) # 50 images per block if class_idx < 10: # 只显示前10个类别避免输出过长 print(f"Class {class_idx:2d} ({class_name}): {len(all_paths):4d} images, {self.total_blocks_per_class[class_idx]:2d} blocks") def get_cache_dir_for_level(self, level): """获取指定层级的缓存目录""" level_info = self.VGG_LEVELS[level] cache_dir = f"{self.base_cache_dir}_vgg_level{level}_{level_info['name']}" return cache_dir def get_image_cache_path(self, image_path, level): """获取单张图片在指定层级的缓存路径""" cache_dir = self.get_cache_dir_for_level(level) content = f"{image_path}_level{level}" path_hash = hashlib.md5(content.encode()).hexdigest() return os.path.join(cache_dir, f"{path_hash}.pt") def extract_features_at_level(self, image_paths, level): """在指定层级批量提取VGG特征""" 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'] # 预处理pipeline transform = transforms.Compose([ transforms.Resize((self.vgg_input_size, self.vgg_input_size)), transforms.ToTensor() ]) # 分批处理 all_features = [] valid_paths = [] for i in tqdm(range(0, len(image_paths), self.batch_size), desc=f"Extracting level {level} features", leave=False): batch_paths = image_paths[i:i + self.batch_size] batch_images = [] batch_valid_paths = [] # 加载这一批图片 for img_path in batch_paths: try: img = Image.open(img_path).convert('RGB') img_tensor = transform(img) # 确保是RGB 3通道 if img_tensor.shape[0] != 3: if img_tensor.shape[0] == 1: img_tensor = img_tensor.repeat(3, 1, 1) else: img_tensor = img_tensor[:3] batch_images.append(img_tensor) batch_valid_paths.append(img_path) except Exception as e: print(f"Error loading {img_path}: {e}") continue if not batch_images: continue # 转换为批处理张量 batch_tensor = torch.stack(batch_images).to(self.device) with torch.no_grad(): # ImageNet标准归一化 normalized_batch = torch.stack([self.normalize(img) for img in batch_tensor]) # 前向传播到指定层 x = normalized_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] all_features.extend(batch_features.cpu()) valid_paths.extend(batch_valid_paths) return all_features, valid_paths def cache_level_features(self, image_paths, level, overwrite=False): """缓存指定层级的VGG特征""" cache_dir = self.get_cache_dir_for_level(level) os.makedirs(cache_dir, exist_ok=True) level_info = self.VGG_LEVELS[level] print(f"\n🔧 Caching VGG Level {level} features ({level_info['name']}, {level_info['channels']} channels)") print(f"📁 Cache directory: {cache_dir}") # 检查哪些图片还没有缓存 uncached_paths = [] cached_count = 0 print("🔍 Checking existing cache...") for img_path in tqdm(image_paths, desc="Checking cache", leave=False): cache_path = self.get_image_cache_path(img_path, level) if overwrite or not os.path.exists(cache_path): uncached_paths.append(img_path) else: cached_count += 1 print(f"✅ Found {cached_count} already cached images for level {level}") print(f"🚀 Need to process {len(uncached_paths)} images for level {level}") if not uncached_paths: print(f"🎉 All images are already cached for level {level}!") return # 提取特征 print(f"⚙️ Extracting VGG level {level} features for {len(uncached_paths)} images...") start_time = time.time() features, valid_paths = self.extract_features_at_level(uncached_paths, level) extraction_time = time.time() - start_time print(f"⏱️ Feature extraction completed in {extraction_time:.2f} seconds") print(f"✅ Successfully processed {len(valid_paths)}/{len(uncached_paths)} images") # 保存特征到缓存 print(f"💾 Saving level {level} features to cache...") saved_count = 0 failed_count = 0 for feature, img_path in tqdm(zip(features, valid_paths), desc=f"Saving level {level} cache", total=len(features), leave=False): cache_path = self.get_image_cache_path(img_path, level) try: torch.save(feature, cache_path) saved_count += 1 except Exception as e: print(f"❌ Failed to save cache for {img_path}: {e}") failed_count += 1 print(f"💾 Level {level} cache saved: {saved_count} files, {failed_count} failed") # 计算缓存大小 total_size = 0 cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')] for cache_file in cache_files: total_size += os.path.getsize(os.path.join(cache_dir, cache_file)) print(f"📊 Level {level} cache size: {total_size / (1024 * 1024):.1f} MB ({len(cache_files)} files)") def cache_all_levels(self, max_epochs=50, batch_size=200, overwrite=False): """为所有层级缓存前max_epochs个epoch需要的特征""" print(f"\n🚀 Starting multi-level VGG cache building for {len(self.levels_to_cache)} levels") print(f"🎯 Levels to cache: {self.levels_to_cache}") print(f"📈 Analyzing first {max_epochs} epochs with batch_size={batch_size}") # 获取需要的图片 required_images = self.get_images_for_epochs(max_epochs, batch_size) print(f"📊 Analysis complete:") print(f" Total unique images needed: {len(required_images):,}") print(f" Total classes: {len(self.class_info)}") # 为每个层级构建缓存 overall_start_time = time.time() for i, level in enumerate(self.levels_to_cache): level_start_time = time.time() print(f"\n{'='*60}") print(f"🔧 Processing Level {level} ({i+1}/{len(self.levels_to_cache)})") print(f"{'='*60}") try: self.cache_level_features(required_images, level, overwrite=overwrite) level_time = time.time() - level_start_time print(f"✅ Level {level} completed in {level_time:.2f} seconds") except Exception as e: print(f"❌ Error processing level {level}: {e}") continue overall_time = time.time() - overall_start_time print(f"\n🎉 Multi-level cache building completed!") print(f"⏱️ Total time: {overall_time:.2f} seconds") print(f"📊 Average time per level: {overall_time/len(self.levels_to_cache):.2f} seconds") # 生成缓存报告 self.generate_cache_report() def get_images_for_epochs(self, max_epochs, batch_size): """获取前max_epochs个epoch需要的所有图片路径""" all_image_paths = set() print(f"🔍 Analyzing first {max_epochs} epochs with batch_size={batch_size}...") for epoch in tqdm(range(max_epochs), desc="Analyzing epochs"): batch_mappings = self.get_epoch_mapping(epoch, batch_size) for mapping in batch_mappings: class1, class2 = mapping['class1'], mapping['class2'] block1, block2 = mapping['block1'], mapping['block2'] # 获取class1的图片 if class1 in self.class_info: class1_paths = self.class_info[class1]['image_paths'] start_idx = block1 * 50 end_idx = min(start_idx + 50, len(class1_paths)) if start_idx < len(class1_paths): selected_paths = class1_paths[start_idx:end_idx] all_image_paths.update(selected_paths) # 获取class2的图片 if class2 in self.class_info: class2_paths = self.class_info[class2]['image_paths'] start_idx = block2 * 50 end_idx = min(start_idx + 50, len(class2_paths)) if start_idx < len(class2_paths): selected_paths = class2_paths[start_idx:end_idx] all_image_paths.update(selected_paths) return list(all_image_paths) def get_epoch_mapping(self, epoch, batch_size, class_combination_seed=42): """获取epoch的类别组合映射""" num_classes = len(self.class_info) # 计算总的类别组合数 (C1, C2) where C1 != C2 total_class_combinations = num_classes * (num_classes - 1) batch_mappings = [] for batch_idx in range(batch_size): global_batch_id = epoch * batch_size + batch_idx # 确定当前是第几轮遍历(第几块) 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 % self.total_blocks_per_class.get(class1, 1) block2 = block_round % self.total_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 }) return batch_mappings def generate_cache_report(self): """生成缓存报告""" print(f"\n📋 MULTI-LEVEL VGG CACHE REPORT") print(f"{'='*60}") print(f"📁 Base cache directory: {self.base_cache_dir}") print(f"📊 Dataset: {self.dataset_path}") print(f"🎯 Cached levels: {self.levels_to_cache}") print() total_cache_size = 0 total_files = 0 for level in self.levels_to_cache: cache_dir = self.get_cache_dir_for_level(level) level_info = self.VGG_LEVELS[level] if os.path.exists(cache_dir): cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')] level_size = sum(os.path.getsize(os.path.join(cache_dir, f)) for f in cache_files) total_cache_size += level_size total_files += len(cache_files) print(f"📦 Level {level} ({level_info['name']}):") print(f" 📁 Directory: {cache_dir}") print(f" 🔢 Channels: {level_info['channels']}") print(f" 📄 Files: {len(cache_files):,}") print(f" 💾 Size: {level_size / (1024 * 1024):.1f} MB") print() else: print(f"❌ Level {level} cache not found: {cache_dir}") print() print(f"📊 TOTAL SUMMARY:") print(f" 📄 Total files: {total_files:,}") print(f" 💾 Total size: {total_cache_size / (1024 * 1024):.1f} MB") print(f" 💽 Total size: {total_cache_size / (1024 * 1024 * 1024):.2f} GB") print() # 保存报告到文件 report_path = os.path.join(os.path.dirname(self.base_cache_dir), 'multilevel_vgg_cache_report.txt') with open(report_path, 'w') as f: f.write(f"Multi-Level VGG Cache Report\n") f.write(f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n") f.write(f"Dataset: {self.dataset_path}\n") f.write(f"Base cache directory: {self.base_cache_dir}\n") f.write(f"Cached levels: {self.levels_to_cache}\n\n") for level in self.levels_to_cache: cache_dir = self.get_cache_dir_for_level(level) level_info = self.VGG_LEVELS[level] if os.path.exists(cache_dir): cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')] level_size = sum(os.path.getsize(os.path.join(cache_dir, f)) for f in cache_files) f.write(f"Level {level} ({level_info['name']}):\n") f.write(f" Directory: {cache_dir}\n") f.write(f" Channels: {level_info['channels']}\n") f.write(f" Files: {len(cache_files):,}\n") f.write(f" Size: {level_size / (1024 * 1024):.1f} MB\n\n") f.write(f"Total Summary:\n") f.write(f" Total files: {total_files:,}\n") f.write(f" Total size: {total_cache_size / (1024 * 1024):.1f} MB\n") f.write(f" Total size: {total_cache_size / (1024 * 1024 * 1024):.2f} GB\n") print(f"📄 Report saved to: {report_path}") def validate_level_cache(self, level, test_images=100): """验证指定层级的缓存是否正常工作""" print(f"\n🔍 Validating Level {level} Cache") print(f"{'='*40}") cache_dir = self.get_cache_dir_for_level(level) level_info = self.VGG_LEVELS[level] if not os.path.exists(cache_dir): print(f"❌ Cache directory not found: {cache_dir}") return False # 获取一些测试图片 all_images = [] for class_info in self.class_info.values(): all_images.extend(class_info['image_paths'][:10]) # 每个类别取10张 test_images = min(test_images, len(all_images)) test_paths = all_images[:test_images] print(f"🧪 Testing with {test_images} images...") # 测试缓存加载 cached_count = 0 failed_count = 0 expected_channels = level_info['channels'] for img_path in tqdm(test_paths, desc="Validating cache", leave=False): cache_path = self.get_image_cache_path(img_path, level) if os.path.exists(cache_path): try: feature = torch.load(cache_path, map_location='cpu') # 验证特征形状 if feature.shape == (expected_channels,): cached_count += 1 else: print(f"⚠️ Wrong feature shape for {img_path}: {feature.shape}, expected ({expected_channels},)") failed_count += 1 except Exception as e: print(f"❌ Failed to load cache for {img_path}: {e}") failed_count += 1 else: failed_count += 1 success_rate = cached_count / test_images * 100 print(f"✅ Validation Results:") print(f" 📊 Success rate: {success_rate:.1f}% ({cached_count}/{test_images})") print(f" ❌ Failed: {failed_count}") print(f" 🔢 Expected channels: {expected_channels}") return success_rate > 95 # 认为95%以上成功率为通过 def validate_all_caches(self, test_images=100): """验证所有层级的缓存""" print(f"\n🔍 VALIDATING ALL LEVEL CACHES") print(f"{'='*50}") validation_results = {} for level in self.levels_to_cache: validation_results[level] = self.validate_level_cache(level, test_images) print(f"\n📊 VALIDATION SUMMARY:") all_passed = True for level, passed in validation_results.items(): status = "✅ PASS" if passed else "❌ FAIL" print(f" Level {level}: {status}") if not passed: all_passed = False overall_status = "✅ ALL PASSED" if all_passed else "❌ SOME FAILED" print(f"\n🎯 Overall: {overall_status}") return validation_results def clean_level_cache(self, level): """清理指定层级的缓存""" cache_dir = self.get_cache_dir_for_level(level) if os.path.exists(cache_dir): import shutil shutil.rmtree(cache_dir) print(f"🧹 Cleaned level {level} cache: {cache_dir}") else: print(f"❌ Cache directory not found: {cache_dir}") def clean_all_caches(self): """清理所有层级的缓存""" print(f"🧹 Cleaning all level caches...") for level in self.levels_to_cache: self.clean_level_cache(level) print(f"🧹 All caches cleaned!") def main(): parser = argparse.ArgumentParser(description="Build multi-level VGG feature caches for ImageNet100") parser.add_argument("--dataset_path", type=str, required=True, help="Path to ImageNet100 dataset") parser.add_argument("--base_cache_dir", type=str, help="Base cache directory (default: dataset_path + '_multilevel_vgg')") parser.add_argument("--max_epochs", type=int, default=50, help="Number of epochs to analyze (default: 50)") parser.add_argument("--batch_size", type=int, default=200, help="Batch size for training (default: 200)") parser.add_argument("--vgg_batch_size", type=int, default=16, help="Batch size for VGG inference (default: 16)") parser.add_argument("--device", type=str, default="cuda", help="Device to use (default: cuda)") parser.add_argument("--overwrite", action="store_true", help="Overwrite existing cache files") parser.add_argument("--levels", type=str, default="3,8,15,22,29", help="Comma-separated VGG levels to cache (default: 3,8,15,22,29)") # 操作选项 parser.add_argument("--analyze_only", action="store_true", help="Only analyze which images are needed, don't extract features") parser.add_argument("--validate_only", action="store_true", help="Only validate existing caches") parser.add_argument("--clean_cache", action="store_true", help="Clean all existing caches") parser.add_argument("--report_only", action="store_true", help="Only generate cache report") args = parser.parse_args() # 设置基础缓存目录 if args.base_cache_dir is None: args.base_cache_dir = f"{args.dataset_path}_multilevel_vgg" # 解析要缓存的层级 try: levels_to_cache = [int(x.strip()) for x in args.levels.split(',')] # 验证层级是否有效 invalid_levels = [l for l in levels_to_cache if l not in MultiLevelVGGCacheBuilder.VGG_LEVELS] if invalid_levels: print(f"❌ Invalid levels: {invalid_levels}") print(f"✅ Available levels: {list(MultiLevelVGGCacheBuilder.VGG_LEVELS.keys())}") sys.exit(1) except ValueError: print(f"❌ Invalid levels format: {args.levels}") print(f"✅ Use format like: 3,8,15,22,29") sys.exit(1) print("=== Multi-Level VGG Feature Cache Builder ===") print(f"📁 Dataset path: {args.dataset_path}") print(f"📁 Base cache directory: {args.base_cache_dir}") print(f"🎯 Levels to cache: {levels_to_cache}") print(f"📈 Max epochs: {args.max_epochs}") print(f"📊 Training batch size: {args.batch_size}") print(f"🔧 VGG batch size: {args.vgg_batch_size}") print(f"💻 Device: {args.device}") print() # 检查数据集路径 if not os.path.exists(args.dataset_path): print(f"❌ Dataset path does not exist: {args.dataset_path}") sys.exit(1) # 创建缓存构建器 builder = MultiLevelVGGCacheBuilder( dataset_path=args.dataset_path, base_cache_dir=args.base_cache_dir, device=args.device, batch_size=args.vgg_batch_size, levels_to_cache=levels_to_cache ) # 执行不同的操作 if args.clean_cache: print("🧹 Cleaning all caches...") builder.clean_all_caches() return if args.validate_only: print("🔍 Validating existing caches...") builder.validate_all_caches() return if args.report_only: print("📋 Generating cache report...") builder.generate_cache_report() return if args.analyze_only: required_images = builder.get_images_for_epochs(args.max_epochs, args.batch_size) print(f"📊 Analysis complete:") print(f" Total unique images needed: {len(required_images):,}") total_images = sum(info['total_images'] for info in builder.class_info.values()) coverage = len(required_images) / total_images * 100 print(f" Coverage: {len(required_images):,}/{total_images:,} ({coverage:.1f}%)") print(f" Will create {len(levels_to_cache)} cache directories") return # 构建所有层级的缓存 print("🚀 Starting multi-level cache building...") start_time = time.time() builder.cache_all_levels( max_epochs=args.max_epochs, batch_size=args.batch_size, overwrite=args.overwrite ) total_time = time.time() - start_time print(f"\n🎉 Multi-level cache building completed in {total_time:.2f} seconds") # 验证缓存 print("\n🔍 Validating built caches...") builder.validate_all_caches() if __name__ == "__main__": main() # python vgg_cache_builder.py \ # --dataset_path "/work/jf381/data/icl_jay/imagenet100" \ # --max_epochs 100 \ # --batch_size 200 \ # --levels "3,8,15,22,29" \ # --device cuda