abcxyz / eval_code /metric.py
phuckstnk63's picture
Upload repository files
9a85a36 verified
Raw History Blame Contribute Delete
17.9 kB
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import scipy
from torchvision.models import inception_v3
from tqdm import tqdm
######### MODEL CLASS ##########
class InceptionFeatureExtractor(nn.Module):
"""Modified InceptionV3 for extracting features for FID and IS computation"""
def __init__(self, resize_input=True, normalize_input=True, return_features="both"):
super().__init__()
# Load pretrained InceptionV3
inception = inception_v3(pretrained=True, transform_input=False)
inception.eval()
# Remove the final classification layer
# We'll extract features from different layers for FID vs IS
self.resize_input = resize_input
self.normalize_input = normalize_input
# Copy all layers except the final fc layer
self.Conv2d_1a_3x3 = inception.Conv2d_1a_3x3
self.Conv2d_2a_3x3 = inception.Conv2d_2a_3x3
self.Conv2d_2b_3x3 = inception.Conv2d_2b_3x3
self.maxpool1 = inception.maxpool1
self.Conv2d_3b_1x1 = inception.Conv2d_3b_1x1
self.Conv2d_4a_3x3 = inception.Conv2d_4a_3x3
self.maxpool2 = inception.maxpool2
self.Mixed_5b = inception.Mixed_5b
self.Mixed_5c = inception.Mixed_5c
self.Mixed_5d = inception.Mixed_5d
self.Mixed_6a = inception.Mixed_6a
self.Mixed_6b = inception.Mixed_6b
self.Mixed_6c = inception.Mixed_6c
self.Mixed_6d = inception.Mixed_6d
self.Mixed_6e = inception.Mixed_6e
self.Mixed_7a = inception.Mixed_7a
self.Mixed_7b = inception.Mixed_7b
self.Mixed_7c = inception.Mixed_7c
self.avgpool = inception.avgpool
self.dropout = inception.dropout
if return_features == "is":
self.fc = inception.fc # Keep for IS score
self.return_features = return_features
def get_features(self, x):
"""
Args:
x: Input tensor of shape (N, 3, H, W)
return_features: 'fid', 'is', or 'both'
Returns:
If 'fid': features for FID computation (N, 2048)
If 'is': logits for IS computation (N, 1000)
If 'both': tuple (fid_features, is_logits)
"""
if self.resize_input:
x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)
if self.normalize_input:
# Normalize to [-1, 1] range expected by InceptionV3
x = (x - 0.5) * 2.0
# Forward pass through the network
x = self.Conv2d_1a_3x3(x)
x = self.Conv2d_2a_3x3(x)
x = self.Conv2d_2b_3x3(x)
x = self.maxpool1(x)
x = self.Conv2d_3b_1x1(x)
x = self.Conv2d_4a_3x3(x)
x = self.maxpool2(x)
x = self.Mixed_5b(x)
x = self.Mixed_5c(x)
x = self.Mixed_5d(x)
x = self.Mixed_6a(x)
x = self.Mixed_6b(x)
x = self.Mixed_6c(x)
x = self.Mixed_6d(x)
x = self.Mixed_6e(x)
x = self.Mixed_7a(x)
x = self.Mixed_7b(x)
x = self.Mixed_7c(x)
# Global average pooling
x = self.avgpool(x)
x = self.dropout(x)
x = torch.flatten(x, 1)
# This is our 2048-dimensional feature for FID
fid_features = x.clone()
if self.return_features == 'fid':
return fid_features
# Forward through final layer for IS
x = self.fc(x)
is_logits = x
if self.return_features == 'is':
return is_logits
else: # return_features == 'both'
return fid_features, is_logits
def get_predictions(self, x):
"""
Args:
x: Input tensor of shape (N, 3, H, W)
return_features: 'fid', 'is', or 'both'
Returns:
If 'fid': features for FID computation (N, 2048)
If 'is': logits for IS computation (N, 1000)
If 'both': tuple (fid_features, is_logits)
"""
if self.resize_input:
x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)
if self.normalize_input:
# Normalize to [-1, 1] range expected by InceptionV3
x = (x - 0.5) * 2.0
# Forward pass through the network
x = self.Conv2d_1a_3x3(x)
x = self.Conv2d_2a_3x3(x)
x = self.Conv2d_2b_3x3(x)
x = self.maxpool1(x)
x = self.Conv2d_3b_1x1(x)
x = self.Conv2d_4a_3x3(x)
x = self.maxpool2(x)
x = self.Mixed_5b(x)
x = self.Mixed_5c(x)
x = self.Mixed_5d(x)
x = self.Mixed_6a(x)
x = self.Mixed_6b(x)
x = self.Mixed_6c(x)
x = self.Mixed_6d(x)
x = self.Mixed_6e(x)
x = self.Mixed_7a(x)
x = self.Mixed_7b(x)
x = self.Mixed_7c(x)
# Global average pooling
x = self.avgpool(x)
x = self.dropout(x)
x = torch.flatten(x, 1)
# This is our 2048-dimensional feature for FID
fid_features = x.clone()
if self.return_features == 'fid':
return fid_features
# Forward through final layer for IS
x = self.fc(x)
is_logits = x
if self.return_features == 'is':
return F.softmax(is_logits, dim=1)
else: # return_features == 'both'
return fid_features, is_logits
class FIDInceptionModel(torch.nn.Module):
"""Inception model for FID calculation."""
def __init__(self, device='cuda'):
super(FIDInceptionModel, self).__init__()
self.device = device
self.model = inception_v3(pretrained=True, transform_input=False)
self.model.fc = torch.nn.Identity() # Remove final classification layer
self.model.avgpool = torch.nn.Identity() # Remove average pooling
self.model.eval()
self.model.to(device)
def get_features(self, images):
"""Extract features from images."""
with torch.no_grad():
features = self.model(images)
breakpoint()
return features
class ISInceptionModel(torch.nn.Module):
"""Inception model for Inception Score calculation."""
def __init__(self, device='cuda'):
super(ISInceptionModel, self).__init__()
self.device = device
self.model = inception_v3(pretrained=True, transform_input=False)
self.model.eval()
self.model.to(device)
def get_predictions(self, images):
"""Get class predictions from images."""
with torch.no_grad():
predictions = F.softmax(self.model(images), dim=1)
return predictions
def get_features(self, images):
"""Get raw logits from images (for chunked processing compatibility)."""
with torch.no_grad():
logits = self.model(images)
return logits
########## FID and IS calculation functions ##########
def calculate_fid(features_real, features_fake):
"""
Calculate FID score between real and fake image features using GPU acceleration.
Args:
features_real: Features from real images (torch.Tensor)
features_fake: Features from fake images (torch.Tensor)
Returns:
FID score
"""
# Ensure inputs are on GPU and in torch
if isinstance(features_real, np.ndarray):
features_real = torch.from_numpy(features_real).cuda()
if isinstance(features_fake, np.ndarray):
features_fake = torch.from_numpy(features_fake).cuda()
mu_real = torch.mean(features_real, dim=0)
mu_fake = torch.mean(features_fake, dim=0)
# Calculate covariance matrices
features_real_centered = features_real - mu_real.unsqueeze(0)
features_fake_centered = features_fake - mu_fake.unsqueeze(0)
sigma_real = (features_real_centered.T @ features_real_centered) / (features_real.size(0) - 1)
sigma_fake = (features_fake_centered.T @ features_fake_centered) / (features_fake.size(0) - 1)
m1, m2 = mu_real.cpu().numpy(), mu_fake.cpu().numpy()
c1, c2 = sigma_real.cpu().numpy(), sigma_fake.cpu().numpy()
diff = m1 - m2
offset = np.eye(c1.shape[0]) * 1e-6
# prevent semi-PSD
covmean, _ = scipy.linalg.sqrtm((c1 + offset) @ (c2 + offset), disp=False)
# numeric error might give slight imaginary part
if np.iscomplexobj(covmean):
if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
m = np.max(np.abs(covmean.imag))
raise ValueError('Imaginary component {}'.format(m))
covmean = covmean.real
tr_covmean = np.trace(covmean)
return diff.dot(diff) + np.trace(c1) + np.trace(c2) - 2 * tr_covmean
def calculate_inception_score(predictions, splits=10):
"""
Calculate Inception Score.
Args:
predictions: Class predictions from inception model
splits: Number of splits for calculation
Returns:
Mean and std of inception score
"""
# Convert to numpy
if isinstance(predictions, torch.Tensor):
predictions = predictions.cpu().numpy()
# Split predictions into groups
split_size = len(predictions) // splits
scores = []
for i in range(splits):
start_idx = i * split_size
end_idx = start_idx + split_size
split_preds = predictions[start_idx:end_idx]
# Calculate mean prediction for this split
mean_pred = np.mean(split_preds, axis=0)
# Calculate KL divergence
kl_div = np.sum(split_preds * np.log(split_preds / mean_pred), axis=1)
score = np.exp(np.mean(kl_div))
scores.append(score)
return np.mean(scores), np.std(scores)
########## Memory management functions ##########
def clear_memory():
"""Clear both GPU and CPU memory."""
import gc
# Clear GPU memory
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Clear CPU memory
gc.collect()
def get_memory_usage():
"""Get current memory usage for both GPU and CPU."""
import psutil
# CPU memory
cpu_memory = psutil.virtual_memory()
cpu_used_gb = cpu_memory.used / (1024**3)
cpu_total_gb = cpu_memory.total / (1024**3)
# GPU memory
gpu_used_gb = 0
gpu_total_gb = 0
if torch.cuda.is_available():
gpu_used_gb = torch.cuda.memory_allocated() / (1024**3)
gpu_total_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
return {
'cpu_used_gb': cpu_used_gb,
'cpu_total_gb': cpu_total_gb,
'cpu_percent': cpu_memory.percent,
'gpu_used_gb': gpu_used_gb,
'gpu_total_gb': gpu_total_gb,
'gpu_percent': (gpu_used_gb / gpu_total_gb * 100) if gpu_total_gb > 0 else 0
}
def print_memory_usage(label=""):
"""Print current memory usage."""
memory = get_memory_usage()
print(f"{label} Memory Usage:")
print(f" CPU: {memory['cpu_used_gb']:.1f}/{memory['cpu_total_gb']:.1f} GB ({memory['cpu_percent']:.1f}%)")
if torch.cuda.is_available():
print(f" GPU: {memory['gpu_used_gb']:.1f}/{memory['gpu_total_gb']:.1f} GB ({memory['gpu_percent']:.1f}%)")
def force_memory_cleanup():
"""Force aggressive memory cleanup."""
import gc
print("Performing aggressive memory cleanup...")
# Clear GPU memory
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Reset peak memory stats
torch.cuda.reset_peak_memory_stats()
# Force garbage collection multiple times
for i in range(3):
gc.collect()
print_memory_usage("After cleanup")
########## Extract Feature Utils Functions ##########
def extract_features_chunked(model, dataset, device, batch_size=32, chunk_size=5000, cache_dir=None, cache_prefix=""):
"""
Extract features from a large dataset by processing it in chunks.
Args:
model: The model to extract features from
dataset: The dataset to process
device: Device to use
batch_size: Batch size for processing
chunk_size: Number of samples per chunk
cache_dir: Directory to save chunked features
cache_prefix: Prefix for cache files
Returns:
Concatenated features from all chunks
"""
assert model.get_features is not None, "Model must have a get_features method"
features = []
total_samples = len(dataset)
num_chunks = (total_samples + chunk_size - 1) // chunk_size
print(f"Processing {total_samples} samples in {num_chunks} chunks of size {chunk_size}")
print_memory_usage("Initial")
for chunk_idx in range(num_chunks):
start_idx = chunk_idx * chunk_size
end_idx = min((chunk_idx + 1) * chunk_size, total_samples)
# Check if chunk is cached
if cache_dir:
chunk_cache_path = os.path.join(cache_dir, f"{cache_prefix}_chunk_{chunk_idx:03d}.npy")
else:
chunk_cache_path = None
if chunk_cache_path and os.path.exists(chunk_cache_path):
print(f"Loading chunk {chunk_idx + 1}/{num_chunks} from cache...")
chunk_features = np.load(chunk_cache_path)
features.append(chunk_features)
continue
print(f"Processing chunk {chunk_idx + 1}/{num_chunks} (samples {start_idx}-{end_idx})...")
# Create subset for this chunk
from torch.utils.data import Subset
chunk_dataset = Subset(dataset, range(start_idx, end_idx))
chunk_dataloader = DataLoader(chunk_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
# Extract features for this chunk
chunk_features = []
model.eval()
with torch.no_grad():
for batch_idx, batch in enumerate(tqdm(chunk_dataloader, desc=f"Chunk {chunk_idx + 1}", leave=False)):
batch = batch.to(device)
batch_features = model.get_features(batch)
# Convert to numpy and move to CPU immediately to free GPU memory
batch_features_np = batch_features.cpu().numpy()
chunk_features.append(batch_features_np)
# Clear memory periodically (every 5 batches)
if batch_idx % 5 == 0:
clear_memory()
# Delete batch tensors to free memory immediately
del batch, batch_features
chunk_features = np.concatenate(chunk_features, axis=0)
# Save chunk to cache
if chunk_cache_path:
np.save(chunk_cache_path, chunk_features)
print(f"Saved chunk {chunk_idx + 1} features to cache")
features.append(chunk_features)
# Clear memory after each chunk
clear_memory()
# Delete chunk dataloader to free memory
del chunk_dataloader, chunk_dataset
# Print memory usage after chunk
print_memory_usage(f"After chunk {chunk_idx + 1}")
return np.concatenate(features, axis=0)
def extract_features(model, dataloader, device, max_samples=None):
"""Extract features from images using the given model."""
features = []
model.eval()
sample_count = 0
with torch.no_grad():
for batch_idx, batch in enumerate(tqdm(dataloader, desc="Extracting features")):
batch = batch.to(device)
batch_features = model.get_features(batch)
# Convert to numpy and move to CPU immediately to free GPU memory
batch_features_np = batch_features.cpu().numpy()
features.append(batch_features_np)
sample_count += batch_features_np.shape[0]
# Clear memory periodically (every 10 batches)
if batch_idx % 10 == 0:
clear_memory()
# Delete batch tensors to free memory immediately
del batch, batch_features
# Limit number of samples if specified
if max_samples and sample_count >= max_samples:
print(f"Reached maximum sample limit: {max_samples}")
break
# Final memory clear
clear_memory()
return np.concatenate(features, axis=0)
def get_predictions(model, dataloader, device, max_samples=None):
"""Get predictions from images using the given model."""
predictions = []
model.eval()
sample_count = 0
with torch.no_grad():
for batch_idx, batch in enumerate(tqdm(dataloader, desc="Getting predictions")):
batch = batch.to(device)
batch_predictions = model.get_predictions(batch)
# Convert to numpy and move to CPU immediately to free GPU memory
batch_predictions_np = batch_predictions.cpu().numpy()
predictions.append(batch_predictions_np)
sample_count += batch_predictions_np.shape[0]
# Clear memory periodically (every 10 batches)
if batch_idx % 10 == 0:
clear_memory()
# Delete batch tensors to free memory immediately
del batch, batch_predictions
# Limit number of samples if specified
if max_samples and sample_count >= max_samples:
print(f"Reached maximum sample limit: {max_samples}")
break
# Final memory clear
clear_memory()
return np.concatenate(predictions, axis=0)