
"""simple docstring"""


import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()



class 	__a	(   _lowerCAmelCase     ,  _lowerCAmelCase     ,  unittest.TestCase						):
       UpperCamelCase_		:       Any				=      VQModel
       UpperCamelCase_		:       Dict				=      '''sample'''






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				List[str]=(32, 32)      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		4
              UpperCamelCase       			=		3

              UpperCamelCase       			=		floats_tensor((batch_size, num_channels) + sizes      ).to(UpperCAmelCase_      )

              return {"sample": image}






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				int      )->	List[Any]:







              """simple docstring"""
              return (3, 32, 32)






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Tuple:







              """simple docstring"""
              return (3, 32, 32)






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		{
                  "block_out_channels": [32, 64],
                  "in_channels": 3,
                  "out_channels": 3,
                  "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
                  "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
                  "latent_channels": 3,
              }
              UpperCamelCase       			=		self.dummy_input
              return init_dict, inputs_dict






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	List[Any]:







              """simple docstring"""
              pass






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	str:







              """simple docstring"""
              pass






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase       			=		VQModel.from_pretrained("fusing/vqgan-dummy"							,   output_loading_info=UpperCAmelCase_      )
              self.assertIsNotNone(UpperCAmelCase_      )
              self.assertEqual(len(loading_info["missing_keys"]      )							,   0      )

              model.to(UpperCAmelCase_      )
              UpperCamelCase       			=		model(**self.dummy_input      )

              assert image is not None, "Make sure output is not None"






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		VQModel.from_pretrained("fusing/vqgan-dummy"      )
              model.to(UpperCAmelCase_      ).eval()

              torch.manual_seed(0      )
              if torch.cuda.is_available():
                     torch.cuda.manual_seed_all(0      )

              UpperCamelCase       			=		torch.randn(1							,   model.config.in_channels							,   model.config.sample_size							,   model.config.sample_size      )
              UpperCamelCase       			=		image.to(UpperCAmelCase_      )
              with torch.no_grad():
                     UpperCamelCase       			=		model(UpperCAmelCase_      ).sample

              UpperCamelCase       			=		output[0, -1, -3:, -3:].flatten().cpu()
              # fmt: off
              UpperCamelCase       			=		torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143]      )
              # fmt: on
              self.assertTrue(torch.allclose(UpperCAmelCase_							,   UpperCAmelCase_							,   atol=1e-3      )      )







"""simple docstring"""


import numpy as np



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_ = 1E-12		,   UpperCAmelCase_ = 1_00		,   )->				tuple[float, np.ndarray]:







       """simple docstring"""
       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_					)
       UpperCamelCase       			=		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.

       UpperCamelCase       			=		False
       UpperCamelCase       			=		0
       UpperCamelCase       			=		0
       UpperCamelCase       			=		1E12

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

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

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

              UpperCamelCase       			=		lambda_

       if is_complex:
              UpperCamelCase       			=		np.real(lambda_					)

       return lambda_, vector



def 						lowerCamelCase__      (				)->				None:







       """simple docstring"""
       UpperCamelCase       			=		np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]					)
       UpperCamelCase       			=		np.array([41, 4, 20]					)
       UpperCamelCase       			=		real_input_matrix.astype(np.complexaaa					)
       UpperCamelCase       			=		np.triu(1j * complex_input_matrix		,   1					)
       complex_input_matrix += imag_matrix
       complex_input_matrix += -1 * imag_matrix.T
       UpperCamelCase       			=		np.array([41, 4, 20]					).astype(np.complexaaa					)

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

              # Our implementation.
              UpperCamelCase			,							UpperCamelCase       			=		power_iteration(UpperCAmelCase_		,   UpperCAmelCase_					)

              # Numpy implementation.

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





