carin-jf381-data / ICL_code /ICL_Jay /data /vgg_cache_builder.py
jasonfan's picture
2026-03-19: ICL code
64bce2a verified
#!/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