| |
| |
|
|
| 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็นๅพ็ผๅญ็ๆๅปบๅจ""" |
| |
| |
| 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 |
| |
| |
| 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() |
| |
| |
| 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_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 = [] |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| if class_idx < 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'] |
| |
| |
| 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) |
| |
| |
| 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(): |
| |
| 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)) |
| batch_features = batch_features.view(batch_features.size(0), -1) |
| |
| 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'] |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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]) |
| |
| 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 |
| |
| 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() |
|
|
| |
| |
| |
| |
| |
| |