

'''simple docstring'''







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


__lowerCamelCase									=     False


class        A__   (   unittest.TestCase      ):
    pass


@nightly
@require_torch_gpu
class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   VersatileDiffusionTextToImagePipeline.from_pretrained("""shi-labs/versatile-diffusion"""							)
           # remove text_unet
           pipe.remove_unused_weights()
           pipe.to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

           A_						       =   """A painting of a squirrel eating a burger """
           A_						       =   torch.manual_seed(0							)
           A_						       =   pipe(
               prompt=UpperCamelCase__		,					generator=UpperCamelCase__		,					guidance_scale=7.5		,					num_inference_steps=2		,					output_type="""numpy"""							).images

           with tempfile.TemporaryDirectory() as tmpdirname:
                  pipe.save_pretrained(UpperCamelCase__							)
                  A_						       =   VersatileDiffusionTextToImagePipeline.from_pretrained(UpperCamelCase__							)
           pipe.to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

           A_						       =   generator.manual_seed(0							)
           A_						       =   pipe(
               prompt=UpperCamelCase__		,					generator=UpperCamelCase__		,					guidance_scale=7.5		,					num_inference_steps=2		,					output_type="""numpy"""							).images

           assert np.abs(image - new_image							).sum() < 1e-5, "Models don't have the same forward pass"







    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   VersatileDiffusionTextToImagePipeline.from_pretrained(
               """shi-labs/versatile-diffusion"""		,					torch_dtype=torch.floataa							)
           pipe.to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

           A_						       =   """A painting of a squirrel eating a burger """
           A_						       =   torch.manual_seed(0							)
           A_						       =   pipe(
               prompt=UpperCamelCase__		,					generator=UpperCamelCase__		,					guidance_scale=7.5		,					num_inference_steps=50		,					output_type="""numpy"""							).images

           A_						       =   image[0, 253:256, 253:256, -1]

           assert image.shape == (1, 512, 512, 3)
           A_						       =   np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]							)

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



'''simple docstring'''







import numpy as np
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__ = 1e-12,							UpperCAmelCase__ = 1_00,							)      ->      tuple[float, np.ndarray]:
       assert np.shape(UpperCAmelCase__					)[0] == np.shape(UpperCAmelCase__					)[1]
       # Ensure proper dimensionality.
       assert np.shape(UpperCAmelCase__					)[0] == np.shape(UpperCAmelCase__					)[0]
       # Ensure inputs are either both complex or both real
       assert np.iscomplexobj(UpperCAmelCase__					) == np.iscomplexobj(UpperCAmelCase__					)
       A_						       =   np.iscomplexobj(UpperCAmelCase__					)
       if is_complex:
              # Ensure complex input_matrix is Hermitian
              assert np.array_equal(UpperCAmelCase__,							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.

       A_						       =   False
       A_						       =   0
       A_						       =   0
       A_						       =   1e12

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

              # Check convergence.
              A_						       =   np.abs(lambda_ - lambda_previous					) / lambda_
              iterations += 1

              if error <= error_tol or iterations >= max_iterations:
                     A_						       =   True

              A_						       =   lambda_

       if is_complex:
              A_						       =   np.real(lambda_					)

       return lambda_, vector
def    UpperCAmelCase__     (   )      ->      None:
       A_						       =   np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]					)
       A_						       =   np.array([41, 4, 20]					)
       A_						       =   real_input_matrix.astype(np.complexaaa					)
       A_						       =   np.triu(1j * complex_input_matrix,							1					)
       complex_input_matrix += imag_matrix
       complex_input_matrix += -1 * imag_matrix.T
       A_						       =   np.array([41, 4, 20]					).astype(np.complexaaa					)

       for problem_type in ["real", "complex"]:
              if problem_type == "real":
                     A_						       =   real_input_matrix
                     A_						       =   real_vector
              elif problem_type == "complex":
                     A_						       =   complex_input_matrix
                     A_						       =   complex_vector

              # Our implementation.
              A_       ,      A_						       =   power_iteration(UpperCAmelCase__,							UpperCAmelCase__					)

              # Numpy implementation.

              # Get eigenvalues and eigenvectors using built-in numpy
              # eigh (eigh used for symmetric or hermetian matrices).
              A_       ,      A_						       =   np.linalg.eigh(UpperCAmelCase__					)
              # Last eigenvalue is the maximum one.
              A_						       =   eigen_values[-1]
              # Last column in this matrix is eigenvector corresponding to largest eigenvalue.
              A_						       =   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(UpperCAmelCase__					) - np.abs(UpperCAmelCase__					)					) <= 1e-6


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      test_power_iteration()
