Below is the refined implementation of the RobustnessMetricsPipeline class, addressing the issues you've encountered—particularly the error related to the Frechet Inception Distance (FID) computation. This implementation adheres strictly to PEP-8 standards, utilizes appropriate type hints from the typing module, and incorporates comprehensive error handling to ensure robustness. Additionally, optimizations have been made to enhance performance and scalability, especially when handling large datasets.
Key Improvements:
-
Frechet Inception Distance (FID) Fix:
- Problem: The original implementation attempted to compute the Cholesky decomposition of the product of covariance matrices (
sigma1 @ sigma2), which is not guaranteed to be positive-definite, leading to errors.
- Solution: Implemented a custom matrix square root function (
_matrix_sqrt) using eigen decomposition to correctly compute the square root of the product of covariance matrices. Additionally, added a small epsilon to the diagonal of covariance matrices to ensure they are positive-definite, preventing potential numerical issues.
-
Code Structure and Readability:
- Organized the code into clearly defined methods with appropriate docstrings.
- Enhanced logging to provide more informative messages.
- Ensured all methods perform necessary sanity checks and handle exceptions gracefully.
-
Performance Optimizations:
- Utilized efficient tensor operations to handle large datasets seamlessly.
- Leveraged GPU acceleration where available to speed up computations.
-
Type Hinting and Documentation:
- Comprehensive type hints have been added to all methods.
- Detailed docstrings explain the purpose, arguments, and return values of each method.
-
PEP-8 Compliance:
- Ensured the code adheres to PEP-8 standards for Python code style, enhancing readability and maintainability.
Complete Refined Code:
import torch
import torch.nn.functional as F
from typing import Tuple, List, Optional, Dict
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class RobustnessMetricsPipeline:
"""
A pipeline to compute various robustness metrics for image generation.
"""
def __init__(self, device: Optional[torch.device] = None) -> None:
"""
Initializes the pipeline.
Args:
device (torch.device, optional): The device to run computations on.
Defaults to CUDA if available, else CPU.
"""
self.device = device if device else torch.device(
'cuda' if torch.cuda.is_available() else 'cpu'
)
logger.info(f"Using device: {self.device}")
def inception_score(self, images: torch.Tensor, splits: int = 10) -> float:
"""
Computes the Inception Score (IS) for the given images.
Args:
images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
splits (int): Number of splits.
Returns:
float: The Inception Score.
"""
try:
preds = self._fake_inception_predictions(images)
split_size = preds.size(0) // splits
scores = []
for i in range(splits):
part = preds[i * split_size: (i + 1) * split_size]
p_y = torch.mean(part, dim=0, keepdim=True)
kl_div = part * (torch.log(part) - torch.log(p_y))
sum_kl_div = torch.sum(kl_div, dim=1)
scores.append(torch.mean(sum_kl_div).exp().item())
is_score = sum(scores) / len(scores)
logger.info(f"Inception Score: {is_score}")
return is_score
except Exception as e:
logger.error(f"Error computing Inception Score: {e}")
raise
def frechet_inception_distance(
self, real_images: torch.Tensor, generated_images: torch.Tensor, eps: float = 1e-6
) -> float:
"""
Computes the Frechet Inception Distance (FID) between real and generated images.
Args:
real_images (torch.Tensor): Real images tensor of shape (N, C, H, W).
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
eps (float): Small epsilon added to diagonal for numerical stability.
Returns:
float: The FID score.
"""
try:
mu1, sigma1 = self._compute_statistics(real_images)
mu2, sigma2 = self._compute_statistics(generated_images)
fid = self._calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps)
logger.info(f"Frechet Inception Distance: {fid}")
return fid
except Exception as e:
logger.error(f"Error computing Frechet Inception Distance: {e}")
raise
def perceptual_similarity(
self, real_images: torch.Tensor, generated_images: torch.Tensor
) -> float:
"""
Computes perceptual similarity between real and generated images.
Args:
real_images (torch.Tensor): Real images tensor of shape (N, C, H, W).
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
Returns:
float: The perceptual similarity score.
"""
try:
similarity = F.cosine_similarity(
real_images.view(real_images.size(0), -1),
generated_images.view(generated_images.size(0), -1),
dim=1
).mean().item()
logger.info(f"Perceptual Similarity: {similarity}")
return similarity
except Exception as e:
logger.error(f"Error computing Perceptual Similarity: {e}")
raise
def mean_squared_error(
self, real_images: torch.Tensor, generated_images: torch.Tensor
) -> float:
"""
Computes Mean Squared Error (MSE) between real and generated images.
Args:
real_images (torch.Tensor): Real images tensor of shape (N, C, H, W).
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
Returns:
float: The MSE value.
"""
try:
mse = F.mse_loss(generated_images, real_images).item()
logger.info(f"Mean Squared Error: {mse}")
return mse
except Exception as e:
logger.error(f"Error computing Mean Squared Error: {e}")
raise
def structural_similarity_index(
self, real_images: torch.Tensor, generated_images: torch.Tensor
) -> float:
"""
Computes Structural Similarity Index (SSIM) between real and generated images.
Args:
real_images (torch.Tensor): Real images tensor of shape (N, C, H, W).
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
Returns:
float: The SSIM value.
"""
try:
# Parameters for SSIM
C1 = 0.01 ** 2
C2 = 0.03 ** 2
real_mean = self._gaussian_filter(real_images)
gen_mean = self._gaussian_filter(generated_images)
real_var = self._variance_filter(real_images, real_mean)
gen_var = self._variance_filter(generated_images, gen_mean)
covariance = self._covariance_filter(
real_images, generated_images, real_mean, gen_mean
)
ssim_map = (
(2 * real_mean * gen_mean + C1)
* (2 * covariance + C2)
/ (
(real_mean ** 2 + gen_mean ** 2 + C1)
* (real_var + gen_var + C2)
)
)
ssim = ssim_map.mean().item()
logger.info(f"Structural Similarity Index: {ssim}")
return ssim
except Exception as e:
logger.error(f"Error computing Structural Similarity Index: {e}")
raise
def diversity_score(self, generated_images: torch.Tensor) -> float:
"""
Computes Diversity Score of generated images.
Args:
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
Returns:
float: The diversity score.
"""
try:
norms = F.normalize(
generated_images.view(generated_images.size(0), -1), dim=1
)
similarity_matrix = torch.matmul(norms, norms.t())
# Exclude self-similarity by subtracting identity matrix
similarity_matrix = similarity_matrix - torch.eye(
similarity_matrix.size(0), device=self.device
)
diversity = 1 - similarity_matrix.mean().item()
logger.info(f"Diversity Score: {diversity}")
return diversity
except Exception as e:
logger.error(f"Error computing Diversity Score: {e}")
raise
def mode_collapse_rate(
self, generated_images: torch.Tensor, threshold: float = 0.99
) -> float:
"""
Computes Mode Collapse Rate of generated images.
Args:
generated_images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
threshold (float): Similarity threshold to consider images as collapsed.
Returns:
float: The mode collapse rate.
"""
try:
norms = F.normalize(
generated_images.view(generated_images.size(0), -1), dim=1
)
similarity_matrix = torch.matmul(norms, norms.t())
similarity_matrix = similarity_matrix > threshold
# Count number of similar pairs excluding self-comparison
collapse_pairs = similarity_matrix.sum().item() - generated_images.size(0)
total_pairs = generated_images.size(0) * (generated_images.size(0) - 1)
mode_collapse = collapse_pairs / total_pairs if total_pairs > 0 else 0.0
logger.info(f"Mode Collapse Rate: {mode_collapse}")
return mode_collapse
except Exception as e:
logger.error(f"Error computing Mode Collapse Rate: {e}")
raise
def training_stability(self, loss_values: List[float]) -> float:
"""
Analyzes training stability based on loss values.
Args:
loss_values (List[float]): List of loss values during training.
Returns:
float: The training stability metric (e.g., variance).
"""
try:
if not loss_values:
raise ValueError("Loss values list is empty.")
loss_tensor = torch.tensor(loss_values, device=self.device)
variance = loss_tensor.var(unbiased=True).item()
logger.info(f"Training Stability (Variance of Loss): {variance}")
return variance
except Exception as e:
logger.error(f"Error computing Training Stability: {e}")
raise
def quality_metrics(
self, images: torch.Tensor, reference: torch.Tensor
) -> Dict[str, float]:
"""
Evaluates quality metrics based on specific application requirements.
Args:
images (torch.Tensor): Generated images tensor of shape (N, C, H, W).
reference (torch.Tensor): Reference images tensor of shape (N, C, H, W).
Returns:
Dict[str, float]: A dictionary of quality metrics.
"""
try:
mse = self.mean_squared_error(reference, images)
ssim = self.structural_similarity_index(reference, images)
perceptual = self.perceptual_similarity(reference, images)
quality = {
'MSE': mse,
'SSIM': ssim,
'Perceptual_Similarity': perceptual
}
logger.info(f"Quality Metrics: {quality}")
return quality
except Exception as e:
logger.error(f"Error computing Quality Metrics: {e}")
raise
def _fake_inception_predictions(self, images: torch.Tensor) -> torch.Tensor:
"""
Placeholder function for Inception model predictions.
Args:
images (torch.Tensor): Images tensor of shape (N, C, H, W).
Returns:
torch.Tensor: Fake predictions tensor of shape (N, num_classes).
"""
num_classes = 1000
N = images.size(0)
preds = F.softmax(torch.randn(N, num_classes, device=self.device), dim=1)
return preds
def _compute_statistics(
self, images: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Computes the mean and covariance of features for FID.
Args:
images (torch.Tensor): Images tensor of shape (N, C, H, W).
Returns:
Tuple[torch.Tensor, torch.Tensor]: Mean and covariance matrices.
"""
features = self._extract_features(images)
mu = torch.mean(features, dim=0)
sigma = self._compute_covariance(features)
return mu, sigma
def _extract_features(self, images: torch.Tensor) -> torch.Tensor:
"""
Extracts features from images.
Args:
images (torch.Tensor): Images tensor of shape (N, C, H, W).
Returns:
torch.Tensor: Features tensor of shape (N, D).
"""
# Placeholder for feature extraction
# In practice, use a pre-trained network like Inception
features = images.view(images.size(0), -1).to(self.device)
return features
def _compute_covariance(self, features: torch.Tensor) -> torch.Tensor:
"""
Computes the covariance matrix of features.
Args:
features (torch.Tensor): Features tensor of shape (N, D).
Returns:
torch.Tensor: Covariance matrix of shape (D, D).
"""
n_samples = features.size(0)
mean = torch.mean(features, dim=0, keepdim=True)
centered = features - mean
cov = (centered.T @ centered) / (n_samples - 1)
return cov
def _calculate_frechet_distance(
self,
mu1: torch.Tensor,
sigma1: torch.Tensor,
mu2: torch.Tensor,
sigma2: torch.Tensor,
eps: float = 1e-6
) -> float:
"""
Calculates the Frechet Distance between two Gaussians.
Args:
mu1 (torch.Tensor): Mean of the first distribution.
sigma1 (torch.Tensor): Covariance of the first distribution.
mu2 (torch.Tensor): Mean of the second distribution.
sigma2 (torch.Tensor): Covariance of the second distribution.
eps (float): Small epsilon added to diagonal for numerical stability.
Returns:
float: The Frechet Distance.
"""
try:
# Add epsilon to diagonal to ensure positive-definiteness
sigma1 += torch.eye(sigma1.size(0), device=self.device) * eps
sigma2 += torch.eye(sigma2.size(0), device=self.device) * eps
# Compute difference of means
diff = mu1 - mu2
# Compute sqrt of product of covariance matrices
covmean = self._matrix_sqrt(sigma1 @ sigma2)
# Compute the trace components
trace_covmean = torch.trace(covmean).item()
trace_sigma1 = torch.trace(sigma1).item()
trace_sigma2 = torch.trace(sigma2).item()
fid = (
diff.dot(diff)
+ trace_sigma1
+ trace_sigma2
- 2 * trace_covmean
)
return fid
except Exception as e:
logger.error(f"Error calculating Frechet Distance: {e}")
raise
def _matrix_sqrt(self, matrix: torch.Tensor) -> torch.Tensor:
"""
Computes the matrix square root using eigen decomposition.
Args:
matrix (torch.Tensor): Symmetric positive-definite matrix of shape (D, D).
Returns:
torch.Tensor: Matrix square root of shape (D, D).
"""
try:
# Ensure the matrix is symmetric
matrix = (matrix + matrix.t()) / 2
# Eigen decomposition
eigenvalues, eigenvectors = torch.linalg.eigh(matrix)
# Clamp eigenvalues to ensure non-negative
eigenvalues_clamped = torch.clamp(eigenvalues, min=0.0)
# Compute the square root of eigenvalues
sqrt_eigenvalues = torch.sqrt(eigenvalues_clamped)
# Reconstruct the square root matrix
sqrt_matrix = eigenvectors @ torch.diag(sqrt_eigenvalues) @ eigenvectors.t()
# Ensure symmetry
sqrt_matrix = (sqrt_matrix + sqrt_matrix.t()) / 2
return sqrt_matrix
except RuntimeError as e:
logger.error("Eigen decomposition did not converge for matrix square root.")
raise RuntimeError("Matrix square root computation failed.") from e
except Exception as e:
logger.error(f"Unexpected error in matrix square root computation: {e}")
raise
def _gaussian_filter(
self, images: torch.Tensor, kernel_size: int = 11, sigma: float = 1.5
) -> torch.Tensor:
"""
Applies a Gaussian filter to the images.
Args:
images (torch.Tensor): Images tensor of shape (N, C, H, W).
kernel_size (int): Size of the Gaussian kernel.
sigma (float): Standard deviation.
Returns:
torch.Tensor: Filtered images of shape (N, C, H, W).
"""
try:
channels = images.size(1)
# Create gaussian kernel
x = torch.arange(kernel_size, device=self.device).float()
x = x - kernel_size // 2
gauss = torch.exp(-x ** 2 / (2 * sigma ** 2))
gauss = gauss / gauss.sum()
gauss = gauss.view(1, 1, -1)
padding = kernel_size // 2
images = images.view(-1, 1, images.size(2), images.size(3))
filtered = F.conv2d(
images,
gauss.expand(channels, 1, -1),
padding=padding,
groups=channels
)
return filtered.view(images.size(0) // channels, channels, images.size(2), images.size(3))
except Exception as e:
logger.error(f"Error applying Gaussian filter: {e}")
raise
def _variance_filter(
self, images: torch.Tensor, mean: torch.Tensor, kernel_size: int = 11, sigma: float = 1.5
) -> torch.Tensor:
"""
Computes variance of images using a Gaussian filter.
Args:
images (torch.Tensor): Images tensor of shape (N, C, H, W).
mean (torch.Tensor): Mean of the images of shape (N, C, H, W).
kernel_size (int): Size of the Gaussian kernel.
sigma (float): Standard deviation.
Returns:
torch.Tensor: Variance tensor of shape (N, C, H, W).
"""
try:
squared = images ** 2
mean_of_squared = self._gaussian_filter(squared, kernel_size, sigma)
variance = mean_of_squared - mean ** 2
return variance
except Exception as e:
logger.error(f"Error computing variance filter: {e}")
raise
def _covariance_filter(
self,
images1: torch.Tensor,
images2: torch.Tensor,
mean1: torch.Tensor,
mean2: torch.Tensor,
kernel_size: int = 11,
sigma: float = 1.5
) -> torch.Tensor:
"""
Computes covariance between two sets of images using a Gaussian filter.
Args:
images1 (torch.Tensor): First set of images of shape (N, C, H, W).
images2 (torch.Tensor): Second set of images of shape (N, C, H, W).
mean1 (torch.Tensor): Mean of the first set of images.
mean2 (torch.Tensor): Mean of the second set of images.
kernel_size (int): Size of the Gaussian kernel.
sigma (float): Standard deviation.
Returns:
torch.Tensor: Covariance tensor of shape (N, C, H, W).
"""
try:
product = images1 * images2
mean_product = self._gaussian_filter(product, kernel_size, sigma)
covariance = mean_product - mean1 * mean2
return covariance
except Exception as e:
logger.error(f"Error computing covariance filter: {e}")
raise
# Example Usage
if __name__ == "__main__":
pipeline = RobustnessMetricsPipeline()
# Generate dummy data
real_imgs = torch.randn(100, 3, 64, 64, device=pipeline.device)
gen_imgs = torch.randn(100, 3, 64, 64, device=pipeline.device)
loss_vals = [0.5 / (i + 1) for i in range(100)]
# Compute Metrics
is_score = pipeline.inception_score(gen_imgs)
fid_score = pipeline.frechet_inception_distance(real_imgs, gen_imgs)
perceptual_sim = pipeline.perceptual_similarity(real_imgs, gen_imgs)
mse = pipeline.mean_squared_error(real_imgs, gen_imgs)
ssim = pipeline.structural_similarity_index(real_imgs, gen_imgs)
diversity = pipeline.diversity_score(gen_imgs)
mode_collapse = pipeline.mode_collapse_rate(gen_imgs)
stability = pipeline.training_stability(loss_vals)
quality = pipeline.quality_metrics(gen_imgs, real_imgs)
# Print Metrics
print(f"Inception Score: {is_score}")
print(f"FID Score: {fid_score}")
print(f"Perceptual Similarity: {perceptual_sim}")
print(f"MSE: {mse}")
print(f"SSIM: {ssim}")
print(f"Diversity Score: {diversity}")
print(f"Mode Collapse Rate: {mode_collapse}")
print(f"Training Stability: {stability}")
print(f"Quality Metrics: {quality}")
Explanation of Key Components:
-
Frechet Inception Distance (FID) Computation:
- Mean and Covariance Calculation: The
_compute_statistics method extracts features and computes the mean (mu) and covariance (sigma) for both real and generated images.
- Matrix Square Root: The
_matrix_sqrt method computes the matrix square root using eigen decomposition. It ensures that the covariance matrices are positive-definite by adding a small epsilon (eps) to the diagonal, preventing numerical instability during decomposition.
- FID Calculation: The
_calculate_frechet_distance method uses the means and covariances to compute the FID according to the formula:
[
\text{FID} = ||\mu_1 - \mu_2||^2 + \text{Tr}(\Sigma_1 + \Sigma_2 - 2\sqrt{\Sigma_1 \Sigma_2})
]
Here, sqrtm is approximated via the _matrix_sqrt method.
-
Error Handling:
- Each method is wrapped in try-except blocks to catch and log errors gracefully, ensuring that any unexpected issues during computations are reported with meaningful messages.
-
Performance Considerations:
- Operations are performed on the specified device (CPU or GPU), leveraging GPU acceleration when available.
- Efficient tensor operations and in-place computations reduce memory overhead and improve speed.
-
Logging:
- The
logging module provides detailed insights into the pipeline's operations, aiding in debugging and monitoring.
-
Placeholders for Inception Model:
- The
_fake_inception_predictions method currently simulates predictions. For meaningful metrics, integrate a pre-trained Inception model or another suitable feature extractor.
Notes:
-
Numerical Stability: Adding a small epsilon to the diagonal of covariance matrices ensures they are positive-definite, which is a prerequisite for eigen decomposition and other matrix operations involved in FID computation.
-
Feature Extraction: The current implementation uses a simple flattening of images as a placeholder for feature extraction. For accurate FID scores, it's recommended to use features from a pre-trained deep network like Inception or ResNet.
-
Scalability: The pipeline is designed to handle large datasets efficiently. However, care should be taken when scaling to extremely large datasets, possibly incorporating batching strategies to manage memory usage.
-
Extensibility: The pipeline is modular, allowing for easy addition of new metrics or modification of existing ones to cater to specific requirements.
This implementation should resolve the linalg.cholesky error by correctly computing the matrix square root and ensuring covariance matrices are positive-definite. Additionally, adhering to best coding practices, it offers a robust and maintainable solution for evaluating image generation robustness metrics.