






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 				__a				(	SCREAMING_SNAKE_CASE__			,						SCREAMING_SNAKE_CASE__			,						unittest.TestCase    ):





		'''simple docstring'''



		UpperCAmelCase__   :					Union[str, Any]					     =    StableDiffusionXLPipeline
		UpperCAmelCase__   :					Tuple					     =    TEXT_TO_IMAGE_PARAMS
		UpperCAmelCase__   :					List[Any]					     =    TEXT_TO_IMAGE_BATCH_PARAMS
		UpperCAmelCase__   :					str					     =    TEXT_TO_IMAGE_IMAGE_PARAMS
		UpperCAmelCase__   :					Optional[Any]					     =    TEXT_TO_IMAGE_IMAGE_PARAMS


		def 	__snake_case      (    self							):
						torch.manual_seed(0							)
						SCREAMING_SNAKE_CASE_ :						int    				= UNetaDConditionModel(
						    block_out_channels=(32, 64)			,     layers_per_block=2			,     sample_size=32			,     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=80			,     cross_attention_dim=64			,     )
						SCREAMING_SNAKE_CASE_ :						str    				= 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							)
						SCREAMING_SNAKE_CASE_ :						Tuple    				= AutoencoderKL(
						    block_out_channels=[32, 64]			,     in_channels=3			,     out_channels=3			,     down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']			,     up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']			,     latent_channels=4			,     sample_size=128			,     )
						torch.manual_seed(0							)
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= CLIPTextConfig(
						    bos_token_id=0			,     eos_token_id=2			,     hidden_size=32			,     intermediate_size=37			,     layer_norm_eps=1E-05			,     num_attention_heads=4			,     num_hidden_layers=5			,     pad_token_id=1			,     vocab_size=1000			,     hidden_act='gelu'			,     projection_dim=32			,     )
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= CLIPTextModel(a_							)
						SCREAMING_SNAKE_CASE_ :						Tuple    				= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			,     local_files_only=a_							)

						SCREAMING_SNAKE_CASE_ :						int    				= CLIPTextModelWithProjection(a_							)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			,     local_files_only=a_							)

						SCREAMING_SNAKE_CASE_ :						List[Any]    				= {
						    '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 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__=0							):



						if str(a_							).startswith('mps'							):
										SCREAMING_SNAKE_CASE_ :						int    				= torch.manual_seed(a_							)
						else:
										SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= torch.Generator(device=a_							).manual_seed(a_							)
						SCREAMING_SNAKE_CASE_ :						Tuple    				= {
						    '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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Dict    				= 'cpu'  # ensure determinism for the device-dependent torch.Generator
						SCREAMING_SNAKE_CASE_ :						Any    				= self.get_dummy_components()
						SCREAMING_SNAKE_CASE_ :						List[str]    				= StableDiffusionXLPipeline(**a_							)
						SCREAMING_SNAKE_CASE_ :						Any    				= sd_pipe.to(a_							)
						sd_pipe.set_progress_bar_config(disable=a_							)

						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.get_dummy_inputs(a_							)
						SCREAMING_SNAKE_CASE_ :						Tuple    				= sd_pipe(**a_							).images
						SCREAMING_SNAKE_CASE_ :						int    				= image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= 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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Any    				= self.get_dummy_components()
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= StableDiffusionXLPipeline(**a_							)
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= sd_pipe.to(a_							)
						SCREAMING_SNAKE_CASE_ :						Dict    				= sd_pipe.to(a_							)
						sd_pipe.set_progress_bar_config(disable=a_							)

						# forward without prompt embeds
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.get_dummy_inputs(a_							)
						SCREAMING_SNAKE_CASE_ :						Any    				= 3 * ['this is a negative prompt']
						SCREAMING_SNAKE_CASE_ :						List[str]    				= negative_prompt
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= 3 * [inputs['prompt']]

						SCREAMING_SNAKE_CASE_ :						List[Any]    				= sd_pipe(**a_							)
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= output.images[0, -3:, -3:, -1]

						# forward with prompt embeds
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.get_dummy_inputs(a_							)
						SCREAMING_SNAKE_CASE_ :						List[str]    				= 3 * ['this is a negative prompt']
						SCREAMING_SNAKE_CASE_ :						Tuple    				= 3 * [inputs.pop('prompt'							)]

						(
						    (
						    SCREAMING_SNAKE_CASE_		
						)				,							(
						    SCREAMING_SNAKE_CASE_		
						)				,							(
						    SCREAMING_SNAKE_CASE_		
						)				,							(
						    SCREAMING_SNAKE_CASE_		
						)				,									
						) :						Union[str, Any]    				= sd_pipe.encode_prompt(a_			,     negative_prompt=a_							)

						SCREAMING_SNAKE_CASE_ :						Tuple    				= sd_pipe(
						    **a_			,     prompt_embeds=a_			,     negative_prompt_embeds=a_			,     pooled_prompt_embeds=a_			,     negative_pooled_prompt_embeds=a_			,     )
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= 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 	__snake_case      (    self							):
						super().test_attention_slicing_forward_pass(expected_max_diff=3E-3							)






		def 	__snake_case      (    self							):
						super().test_inference_batch_single_identical(expected_max_diff=3E-3							)






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





		'''simple docstring'''



		def 	__snake_case      (    self							):
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__="cpu"			,     UpperCamelCase__=torch.floataa			,     UpperCamelCase__=0							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= torch.Generator(device=a_							).manual_seed(a_							)
						SCREAMING_SNAKE_CASE_ :						str    				= np.random.RandomState(a_							).standard_normal((1, 4, 64, 64)							)
						SCREAMING_SNAKE_CASE_ :						str    				= torch.from_numpy(a_							).to(device=a_			,     dtype=a_							)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= {
						    '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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						str    				= DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'							)
						pipe.to(a_							)
						pipe.set_progress_bar_config(disable=a_							)

						SCREAMING_SNAKE_CASE_ :						int    				= self.get_inputs(a_							)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= pipe(**a_							).images
						SCREAMING_SNAKE_CASE_ :						Any    				= image[0, -3:, -3:, -1].flatten()

						assert image.shape == (1, 512, 512, 3)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= 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



'''simple docstring'''

from __future__ import annotations



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					list[list[int]]     ,		_UpperCamelCase   :					list[list[int]] )		->       list[int]:





   '''simple docstring'''







   assert len(_UpperCamelCase ) == len(_UpperCamelCase )

   UpperCamelCase__			    =    len(_UpperCamelCase )
   UpperCamelCase__			    =    list(range(_UpperCamelCase ) )
   UpperCamelCase__			    =    [-1] * n  # who the donor has donated to
   UpperCamelCase__			    =    [-1] * n  # who the recipient has received from
   UpperCamelCase__			    =    [0] * n

   while unmatched_donors:
      UpperCamelCase__			    =    unmatched_donors[0]
      UpperCamelCase__			    =    donor_pref[donor]
      UpperCamelCase__			    =    donor_preference[num_donations[donor]]
      num_donations[donor] += 1
      UpperCamelCase__			    =    recipient_pref[recipient]
      UpperCamelCase__			    =    rec_record[recipient]

      if prev_donor != -1:
         if rec_preference.index(_UpperCamelCase ) > rec_preference.index(_UpperCamelCase ):
            UpperCamelCase__			    =    donor
            UpperCamelCase__			    =    recipient
            unmatched_donors.append(_UpperCamelCase )
            unmatched_donors.remove(_UpperCamelCase )
      else:
         UpperCamelCase__			    =    donor
         UpperCamelCase__			    =    recipient
         unmatched_donors.remove(_UpperCamelCase )
   return donor_record