


import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
@slow
@require_torch_gpu
class 		__magic_name__						(unittest.TestCase				):





     '''simple docstring'''



     def 	SCREAMING_SNAKE_CASE__						(					self:int   ):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]   ):
       snake_case__						= StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''   )
       snake_case__						= sd_pipe.to(_a   )
       sd_pipe.set_progress_bar_config(disable=_a   )

       sd_pipe.set_scheduler('''sample_euler'''   )

       snake_case__						= '''A painting of a squirrel eating a burger'''
       snake_case__						= torch.manual_seed(0   )
       snake_case__						= sd_pipe([prompt]     ,		generator=_a     ,		guidance_scale=9.0     ,		num_inference_steps=20     ,		output_type='''np'''   )

       snake_case__						= output.images

       snake_case__						= image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       snake_case__						= np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple   ):
       snake_case__						= StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
       snake_case__						= sd_pipe.to(_a   )
       sd_pipe.set_progress_bar_config(disable=_a   )

       sd_pipe.set_scheduler('''sample_euler'''   )

       snake_case__						= '''A painting of a squirrel eating a burger'''
       snake_case__						= torch.manual_seed(0   )
       snake_case__						= sd_pipe([prompt]     ,		generator=_a     ,		guidance_scale=9.0     ,		num_inference_steps=20     ,		output_type='''np'''   )

       snake_case__						= output.images

       snake_case__						= image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       snake_case__						= np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5e-1







     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]   ):
       snake_case__						= StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
       snake_case__						= sd_pipe.to(_a   )
       sd_pipe.set_progress_bar_config(disable=_a   )

       sd_pipe.set_scheduler('''sample_dpmpp_2m'''   )

       snake_case__						= '''A painting of a squirrel eating a burger'''
       snake_case__						= torch.manual_seed(0   )
       snake_case__						= sd_pipe(
           [prompt]     ,		generator=_a     ,		guidance_scale=7.5     ,		num_inference_steps=15     ,		output_type='''np'''     ,		use_karras_sigmas=_a     ,		)

       snake_case__						= output.images

       snake_case__						= image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       snake_case__						= np.array(
           [0.11381689, 0.12112921, 0.1389457, 0.12549606, 0.1244964, 0.10831517, 0.11562866, 0.10867816, 0.10499048]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2









"""simple docstring"""



import numpy as np


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : np.ndarray			,					snake_case       : np.ndarray			,					snake_case       : float = 1E-1_2			,					snake_case       : int = 100			,					)->		tuple[float, np.ndarray]:






     '''simple docstring'''



     assert np.shape(snake_case				)[0] == np.shape(snake_case				)[1]
     # Ensure proper dimensionality.
     assert np.shape(snake_case				)[0] == np.shape(snake_case				)[0]
     # Ensure inputs are either both complex or both real
     assert np.iscomplexobj(snake_case				) == np.iscomplexobj(snake_case				)
     UpperCAmelCase__						:    str							=							np.iscomplexobj(snake_case				)
     if is_complex:
          # Ensure complex input_matrix is Hermitian
          assert np.array_equal(snake_case			,					input_matrix.conj().T				)

     # Set convergence to False. Will define convergence when we exceed max_iterations
     # or when we have small changes from one iteration to next.

     UpperCAmelCase__						:    Union[str, Any]							=							False
     UpperCAmelCase__						:    List[Any]							=							0
     UpperCAmelCase__						:    Any							=							0
     UpperCAmelCase__						:    List[str]							=							1E1_2

     while not convergence:
          # Multiple matrix by the vector.
          UpperCAmelCase__						:    Optional[Any]							=							np.dot(snake_case			,					snake_case				)
          # Normalize the resulting output vector.
          UpperCAmelCase__						:    Tuple							=							w / np.linalg.norm(snake_case				)
          # Find rayleigh quotient
          # (faster than usual b/c we know vector is normalized already)
          UpperCAmelCase__						:    Any							=							vector.conj().T if is_complex else vector.T
          UpperCAmelCase__						:    List[str]							=							np.dot(snake_case			,					np.dot(snake_case			,					snake_case				)				)

          # Check convergence.
          UpperCAmelCase__						:    Optional[Any]							=							np.abs(lambda_ - lambda_previous				) / lambda_
          iterations += 1

          if error <= error_tol or iterations >= max_iterations:
               UpperCAmelCase__						:    Tuple							=							True

          UpperCAmelCase__						:    Tuple							=							lambda_

     if is_complex:
          UpperCAmelCase__						:    str							=							np.real(lambda_				)

     return lambda_, vector


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     UpperCAmelCase__						:    List[Any]							=							np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]				)
     UpperCAmelCase__						:    Dict							=							np.array([41, 4, 20]				)
     UpperCAmelCase__						:    Union[str, Any]							=							real_input_matrix.astype(np.complexaaa				)
     UpperCAmelCase__						:    Optional[int]							=							np.triu(1J * complex_input_matrix			,					1				)
     complex_input_matrix += imag_matrix
     complex_input_matrix += -1 * imag_matrix.T
     UpperCAmelCase__						:    int							=							np.array([41, 4, 20]				).astype(np.complexaaa				)

     for problem_type in ["real", "complex"]:
          if problem_type == "real":
               UpperCAmelCase__						:    List[str]							=							real_input_matrix
               UpperCAmelCase__						:    Any							=							real_vector
          elif problem_type == "complex":
               UpperCAmelCase__						:    str							=							complex_input_matrix
               UpperCAmelCase__						:    List[Any]							=							complex_vector

          # Our implementation.
          UpperCAmelCase__							,				UpperCAmelCase__						:    Optional[int]							=							power_iteration(snake_case			,					snake_case				)

          # Numpy implementation.

          # Get eigenvalues and eigenvectors using built-in numpy
          # eigh (eigh used for symmetric or hermetian matrices).
          UpperCAmelCase__							,				UpperCAmelCase__						:    List[Any]							=							np.linalg.eigh(snake_case				)
          # Last eigenvalue is the maximum one.
          UpperCAmelCase__						:    str							=							eigen_values[-1]
          # Last column in this matrix is eigenvector corresponding to largest eigenvalue.
          UpperCAmelCase__						:    Optional[int]							=							eigen_vectors[:, -1]

          # Check our implementation and numpy gives close answers.
          assert np.abs(eigen_value - eigen_value_max				) <= 1E-6
          # Take absolute values element wise of each eigenvector.
          # as they are only unique to a minus sign.
          assert np.linalg.norm(np.abs(snake_case				) - np.abs(snake_case				)				) <= 1E-6


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 test_power_iteration()


