|
| 1 | +# ----------------------------------------------------------------------------- |
| 2 | +# |
| 3 | +# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. |
| 4 | +# SPDX-License-Identifier: BSD-3-Clause |
| 5 | +# |
| 6 | +# ----------------------------------------------------------------------------- |
| 7 | + |
| 8 | +""" |
| 9 | +Common utilities for diffusion pipeline testing. |
| 10 | +Provides essential functions for MAD validation, image validation |
| 11 | +hash verification, and other testing utilities. |
| 12 | +""" |
| 13 | + |
| 14 | +import os |
| 15 | +from typing import Any, Dict, Tuple, Union |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +import torch |
| 19 | +from PIL import Image |
| 20 | + |
| 21 | + |
| 22 | +class DiffusersTestUtils: |
| 23 | + """Essential utilities for diffusion pipeline testing""" |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def validate_image_generation( |
| 27 | + image: Image.Image, expected_size: Tuple[int, int], min_variance: float = 1.0 |
| 28 | + ) -> Dict[str, Any]: |
| 29 | + """ |
| 30 | + Validate generated image properties. |
| 31 | + Args: |
| 32 | + image: Generated PIL Image |
| 33 | + expected_size: Expected (width, height) tuple |
| 34 | + min_variance: Minimum pixel variance to ensure image is not blank |
| 35 | +
|
| 36 | + Returns: |
| 37 | + Dict containing validation results |
| 38 | + Raises: |
| 39 | + AssertionError: If image validation fails |
| 40 | + """ |
| 41 | + # Basic image validation |
| 42 | + assert isinstance(image, Image.Image), f"Expected PIL Image, got {type(image)}" |
| 43 | + assert image.size == expected_size, f"Expected size {expected_size}, got {image.size}" |
| 44 | + assert image.mode in ["RGB", "RGBA"], f"Unexpected image mode: {image.mode}" |
| 45 | + |
| 46 | + # Variance check (ensure image is not blank) |
| 47 | + img_array = np.array(image) |
| 48 | + image_variance = float(img_array.std()) |
| 49 | + assert image_variance > min_variance, f"Generated image appears blank (variance: {image_variance:.2f})" |
| 50 | + |
| 51 | + return { |
| 52 | + "size": image.size, |
| 53 | + "mode": image.mode, |
| 54 | + "variance": image_variance, |
| 55 | + "mean_pixel_value": float(img_array.mean()), |
| 56 | + "min_pixel": int(img_array.min()), |
| 57 | + "max_pixel": int(img_array.max()), |
| 58 | + "valid": True, |
| 59 | + } |
| 60 | + |
| 61 | + @staticmethod |
| 62 | + def check_file_exists(file_path: str, file_type: str = "file") -> bool: |
| 63 | + """ |
| 64 | + Check if file exists and log result. |
| 65 | + Args: |
| 66 | + file_path: Path to check |
| 67 | + file_type: Description of file type for logging |
| 68 | + Returns: |
| 69 | + bool: True if file exists |
| 70 | + """ |
| 71 | + exists = os.path.exists(file_path) |
| 72 | + status = "✅" if exists else "❌" |
| 73 | + print(f"{status} {file_type}: {file_path}") |
| 74 | + return exists |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def print_test_header(title: str, config: Dict[str, Any]) -> None: |
| 78 | + """ |
| 79 | + Print formatted test header with configuration details. |
| 80 | +
|
| 81 | + Args: |
| 82 | + title: Test title |
| 83 | + config: Test configuration dictionary |
| 84 | + """ |
| 85 | + print(f"\n{'=' * 80}") |
| 86 | + print(f"{title}") |
| 87 | + print(f"{'=' * 80}") |
| 88 | + |
| 89 | + if "model_setup" in config: |
| 90 | + setup = config["model_setup"] |
| 91 | + for k, v in setup.items(): |
| 92 | + print(f"{k} : {v}") |
| 93 | + |
| 94 | + if "functional_testing" in config: |
| 95 | + func = config["functional_testing"] |
| 96 | + print(f"Test Prompt: {func.get('test_prompt', 'N/A')}") |
| 97 | + print(f"Inference Steps: {func.get('num_inference_steps', 'N/A')}") |
| 98 | + print(f"Guidance Scale: {func.get('guidance_scale', 'N/A')}") |
| 99 | + |
| 100 | + print(f"{'=' * 80}") |
| 101 | + |
| 102 | + |
| 103 | +class MADValidator: |
| 104 | + """Specialized class for MAD validation - always enabled, always reports, always fails on exceed""" |
| 105 | + |
| 106 | + def __init__(self, tolerances: Dict[str, float] = None): |
| 107 | + """ |
| 108 | + Initialize MAD validator. |
| 109 | + MAD validation is always enabled, always reports values, and always fails if tolerance is exceeded. |
| 110 | +
|
| 111 | + Args: |
| 112 | + tolerances: Dictionary of module_name -> tolerance mappings |
| 113 | + """ |
| 114 | + self.tolerances = tolerances |
| 115 | + self.results = {} |
| 116 | + |
| 117 | + def calculate_mad( |
| 118 | + self, tensor1: Union[torch.Tensor, np.ndarray], tensor2: Union[torch.Tensor, np.ndarray] |
| 119 | + ) -> float: |
| 120 | + """ |
| 121 | + Calculate Max Absolute Deviation between two tensors. |
| 122 | +
|
| 123 | + Args: |
| 124 | + tensor1: First tensor (PyTorch or NumPy) |
| 125 | + tensor2: Second tensor (PyTorch or NumPy) |
| 126 | +
|
| 127 | + Returns: |
| 128 | + float: Maximum absolute difference between tensors |
| 129 | + """ |
| 130 | + if isinstance(tensor1, torch.Tensor): |
| 131 | + tensor1 = tensor1.detach().numpy() |
| 132 | + if isinstance(tensor2, torch.Tensor): |
| 133 | + tensor2 = tensor2.detach().numpy() |
| 134 | + |
| 135 | + return float(np.max(np.abs(tensor1 - tensor2))) |
| 136 | + |
| 137 | + def validate_module_mad( |
| 138 | + self, |
| 139 | + pytorch_output: Union[torch.Tensor, np.ndarray], |
| 140 | + qaic_output: Union[torch.Tensor, np.ndarray], |
| 141 | + module_name: str, |
| 142 | + step_info: str = "", |
| 143 | + ) -> bool: |
| 144 | + """ |
| 145 | + Validate MAD for a specific module. |
| 146 | + Always validates, always reports, always fails if tolerance exceeded. |
| 147 | +
|
| 148 | + Args: |
| 149 | + pytorch_output: PyTorch reference output |
| 150 | + qaic_output: QAIC inference output |
| 151 | + module_name: Name of the module |
| 152 | + step_info: Additional step information for logging |
| 153 | +
|
| 154 | + Returns: |
| 155 | + bool: True if validation passed |
| 156 | +
|
| 157 | + Raises: |
| 158 | + AssertionError: If MAD exceeds tolerance |
| 159 | + """ |
| 160 | + mad_value = self.calculate_mad(pytorch_output, qaic_output) |
| 161 | + |
| 162 | + # Always report MAD value |
| 163 | + step_str = f" {step_info}" if step_info else "" |
| 164 | + print(f"🔍 {module_name.upper()} MAD{step_str}: {mad_value:.8f}") |
| 165 | + |
| 166 | + # Always validate - fail if tolerance exceeded |
| 167 | + tolerance = self.tolerances.get(module_name, 1e-2) |
| 168 | + if mad_value > tolerance: |
| 169 | + raise AssertionError(f"{module_name} MAD {mad_value:.6f} exceeds tolerance {tolerance:.6f}") |
| 170 | + |
| 171 | + # Store result |
| 172 | + if module_name not in self.results: |
| 173 | + self.results[module_name] = [] |
| 174 | + self.results[module_name].append({"mad": mad_value, "step_info": step_info, "tolerance": tolerance}) |
| 175 | + return True |
0 commit comments