
import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 	lowerCamelCase						(    A_				,					A_				,					unittest.TestCase    ):
     UpperCAmelCase__							:				List[Any] 	=						StableDiffusionXLPipeline
     UpperCAmelCase__							:				Union[str, Any] 	=						TEXT_TO_IMAGE_PARAMS
     UpperCAmelCase__							:				Optional[int] 	=						TEXT_TO_IMAGE_BATCH_PARAMS
     UpperCAmelCase__							:				str 	=						TEXT_TO_IMAGE_IMAGE_PARAMS
     UpperCAmelCase__							:				Union[str, Any] 	=						TEXT_TO_IMAGE_IMAGE_PARAMS





     def 						UpperCAmelCase(self :       Optional[int]  )		->		Tuple:
         torch.manual_seed(0  )
         snake_case						=   UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)							,       layers_per_block=2							,       sample_size=3_2							,       in_channels=4							,       out_channels=4							,       down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")							,       up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")							,       attention_head_dim=(2, 4)							,       use_linear_projection=_A							,       addition_embed_type="text_time"							,       addition_time_embed_dim=8							,       transformer_layers_per_block=(1, 2)							,       projection_class_embeddings_input_dim=8_0							,       cross_attention_dim=6_4							,       )
         snake_case						=   EulerDiscreteScheduler(
             beta_start=0.0_00_85							,       beta_end=0.0_12							,       steps_offset=1							,       beta_schedule="scaled_linear"							,       timestep_spacing="leading"							,       )
         torch.manual_seed(0  )
         snake_case						=   AutoencoderKL(
             block_out_channels=[3_2, 6_4]							,       in_channels=3							,       out_channels=3							,       down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]							,       up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]							,       latent_channels=4							,       sample_size=1_2_8							,       )
         torch.manual_seed(0  )
         snake_case						=   CLIPTextConfig(
             bos_token_id=0							,       eos_token_id=2							,       hidden_size=3_2							,       intermediate_size=3_7							,       layer_norm_eps=1E-05							,       num_attention_heads=4							,       num_hidden_layers=5							,       pad_token_id=1							,       vocab_size=1_0_0_0							,       hidden_act="gelu"							,       projection_dim=3_2							,       )
         snake_case						=   CLIPTextModel(_A  )
         snake_case						=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							,       local_files_only=_A  )

         snake_case						=   CLIPTextModelWithProjection(_A  )
         snake_case						=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							,       local_files_only=_A  )

         snake_case						=   {
             "unet": unet,
             "scheduler": scheduler,
             "vae": vae,
             "text_encoder": text_encoder,
             "tokenizer": tokenizer,
             "text_encoder_2": text_encoder_a,
             "tokenizer_2": tokenizer_a,
             # "safety_checker": None,
             # "feature_extractor": None,
         }
         return components





     def 						UpperCAmelCase(self :       Optional[Any]							,       _A :       int							,       _A :       Dict=0  )		->		Any:
         if str(_A  ).startswith("mps"  ):
             snake_case						=   torch.manual_seed(_A  )
         else:
             snake_case						=   torch.Generator(device=_A  ).manual_seed(_A  )
         snake_case						=   {
             "prompt": "A painting of a squirrel eating a burger",
             "generator": generator,
             "num_inference_steps": 2,
             "guidance_scale": 5.0,
             "output_type": "numpy",
         }
         return inputs





     def 						UpperCAmelCase(self :       Union[str, Any]  )		->		int:
         snake_case						=   "cpu"  # ensure determinism for the device-dependent torch.Generator
         snake_case						=   self.get_dummy_components()
         snake_case						=   StableDiffusionXLPipeline(**_A  )
         snake_case						=   sd_pipe.to(_A  )
         sd_pipe.set_progress_bar_config(disable=_A  )

         snake_case						=   self.get_dummy_inputs(_A  )
         snake_case						=   sd_pipe(**_A  ).images
         snake_case						=   image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         snake_case						=   np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]  )

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





     def 						UpperCAmelCase(self :       int  )		->		Dict:
         snake_case						=   self.get_dummy_components()
         snake_case						=   StableDiffusionXLPipeline(**_A  )
         snake_case						=   sd_pipe.to(_A  )
         snake_case						=   sd_pipe.to(_A  )
         sd_pipe.set_progress_bar_config(disable=_A  )

         # forward without prompt embeds
         snake_case						=   self.get_dummy_inputs(_A  )
         snake_case						=   3 * ["this is a negative prompt"]
         snake_case						=   negative_prompt
         snake_case						=   3 * [inputs["prompt"]]

         snake_case						=   sd_pipe(**_A  )
         snake_case						=   output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         snake_case						=   self.get_dummy_inputs(_A  )
         snake_case						=   3 * ["this is a negative prompt"]
         snake_case						=   3 * [inputs.pop("prompt"  )]

         (
             (
             snake_case
         )	,				(
             snake_case
         )	,				(
             snake_case
         )	,				(
             snake_case
         )	,				
         )						=   sd_pipe.encode_prompt(_A							,       negative_prompt=_A  )

         snake_case						=   sd_pipe(
             **_A							,       prompt_embeds=_A							,       negative_prompt_embeds=_A							,       pooled_prompt_embeds=_A							,       negative_pooled_prompt_embeds=_A							,       )
         snake_case						=   output.images[0, -3:, -3:, -1]

         # make sure that it's equal
         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()  ).max() < 1E-4





     def 						UpperCAmelCase(self :       str  )		->		Tuple:
         super().test_attention_slicing_forward_pass(expected_max_diff=3E-3  )





     def 						UpperCAmelCase(self :       Tuple  )		->		str:
         super().test_inference_batch_single_identical(expected_max_diff=3E-3  )







@slow
@require_torch_gpu
class 	lowerCamelCase						(    unittest.TestCase    ):





     def 						UpperCAmelCase(self :       str  )		->		Union[str, Any]:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def 						UpperCAmelCase(self :       Union[str, Any]							,       _A :       Optional[Any]							,       _A :       List[str]="cpu"							,       _A :       Any=torch.floataa							,       _A :       Any=0  )		->		int:
         snake_case						=   torch.Generator(device=_A  ).manual_seed(_A  )
         snake_case						=   np.random.RandomState(_A  ).standard_normal((1, 4, 6_4, 6_4)  )
         snake_case						=   torch.from_numpy(_A  ).to(device=_A							,       dtype=_A  )
         snake_case						=   {
             "prompt": "a photograph of an astronaut riding a horse",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 3,
             "guidance_scale": 7.5,
             "output_type": "numpy",
         }
         return inputs





     def 						UpperCAmelCase(self :       str  )		->		Dict:
         snake_case						=   DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"  )
         pipe.to(_A  )
         pipe.set_progress_bar_config(disable=_A  )

         snake_case						=   self.get_inputs(_A  )
         snake_case						=   pipe(**_A  ).images
         snake_case						=   image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         snake_case						=   np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]  )
         assert np.abs(image_slice - expected_slice  ).max() < 7E-3



import logging

# standard libraries
import sys

import numpy as np
import pytest  # type: ignore

# Custom/local libraries
from matrix import matrix_operation as matop

_A       =					[[12, 10], [3, 9]]
_A       =					[[3, 4], [7, 4]]
_A       =					[[3, 0, 2], [2, 0, -2], [0, 1, 1]]
_A       =					[[3, 0, -2], [2, 0, 2], [0, 1, 1]]
_A       =					[[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]]
_A       =					[1]
_A       =					[2]

_A       =					logging.getLogger()
_A       =					logging.DEBUG
_A       =					logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ("mat1", "mat2")					,						[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]						)
def 		lowercase_     (  A__					,						A__						)				->				Dict:
    """simple docstring"""

    if (np.array(A__						)).shape < (2, 2) or (np.array(A__						)).shape < (2, 2):
        with pytest.raises(A__						):
            logger.info(F'\n\t{test_addition.__name__} returned integer'						)
            matop.add(A__					,						A__						)
    elif (np.array(A__						)).shape == (np.array(A__						)).shape:
        logger.info(F'\n\t{test_addition.__name__} with same matrix dims'						)
        snake_case						=   (np.array(A__						) + np.array(A__						)).tolist()
        snake_case						=   matop.add(A__					,						A__						)
        assert theo == act
    else:
        with pytest.raises(A__						):
            logger.info(F'\n\t{test_addition.__name__} with different matrix dims'						)
            matop.add(A__					,						A__						)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ("mat1", "mat2")					,						[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]						)
def 		lowercase_     (  A__					,						A__						)				->				List[Any]:
    """simple docstring"""

    if (np.array(A__						)).shape < (2, 2) or (np.array(A__						)).shape < (2, 2):
        with pytest.raises(A__						):
            logger.info(F'\n\t{test_subtraction.__name__} returned integer'						)
            matop.subtract(A__					,						A__						)
    elif (np.array(A__						)).shape == (np.array(A__						)).shape:
        logger.info(F'\n\t{test_subtraction.__name__} with same matrix dims'						)
        snake_case						=   (np.array(A__						) - np.array(A__						)).tolist()
        snake_case						=   matop.subtract(A__					,						A__						)
        assert theo == act
    else:
        with pytest.raises(A__						):
            logger.info(F'\n\t{test_subtraction.__name__} with different matrix dims'						)
            assert matop.subtract(A__					,						A__						)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ("mat1", "mat2")					,						[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]						)
def 		lowercase_     (  A__					,						A__						)				->				Union[str, Any]:
    """simple docstring"""

    if (np.array(A__						)).shape < (2, 2) or (np.array(A__						)).shape < (2, 2):
        logger.info(F'\n\t{test_multiplication.__name__} returned integer'						)
        with pytest.raises(A__						):
            matop.add(A__					,						A__						)
    elif (np.array(A__						)).shape == (np.array(A__						)).shape:
        logger.info(F'\n\t{test_multiplication.__name__} meets dim requirements'						)
        snake_case						=   (np.matmul(A__					,						A__						)).tolist()
        snake_case						=   matop.multiply(A__					,						A__						)
        assert theo == act
    else:
        with pytest.raises(A__						):
            logger.info(
                F'\n\t{test_multiplication.__name__} does not meet dim requirements'						)
            assert matop.subtract(A__					,						A__						)



@pytest.mark.mat_ops
def 		lowercase_     (  )				->				int:
    """simple docstring"""

    snake_case						=   (3.5 * np.array(A__						)).tolist()
    snake_case						=   matop.scalar_multiply(A__					,						3.5						)
    assert theo == act



@pytest.mark.mat_ops
def 		lowercase_     (  )				->				Any:
    """simple docstring"""

    snake_case						=   (np.identity(5						)).tolist()
    snake_case						=   matop.identity(5						)
    assert theo == act





@pytest.mark.mat_ops
@pytest.mark.parametrize("mat"					,						[mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]						)
def 		lowercase_     (  A__						)				->				List[str]:
    """simple docstring"""

    if (np.array(A__						)).shape < (2, 2):
        with pytest.raises(A__						):
            logger.info(F'\n\t{test_transpose.__name__} returned integer'						)
            matop.transpose(A__						)
    else:
        snake_case						=   (np.transpose(A__						)).tolist()
        snake_case						=   matop.transpose(A__					,						return_map=A__						)
        assert theo == act

