


import gc
import random
import unittest

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

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

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 				snake_case__(							_SCREAMING_SNAKE_CASE,						_SCREAMING_SNAKE_CASE,						unittest.TestCase							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  str					=							StableDiffusionXLImgaImgPipeline
						SCREAMING_SNAKE_CASE__      :  List[str]					=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
						SCREAMING_SNAKE_CASE__      :  Any					=							PipelineTesterMixin.required_optional_params - {"latents"}
						SCREAMING_SNAKE_CASE__      :  str					=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
						SCREAMING_SNAKE_CASE__      :  Optional[Any]					=							IMAGE_TO_IMAGE_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__      :  Tuple					=							IMAGE_TO_IMAGE_IMAGE_PARAMS




						def 						lowercase_ (				self							)					->    List[str]:
										torch.manual_seed(0							)
										lowerCAmelCase_ :      Tuple    				=				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   ,						)
										lowerCAmelCase_ :      Optional[int]    				=				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							)
										lowerCAmelCase_ :      int    				=				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							)
										lowerCAmelCase_ :      Tuple    				=				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   ,						)
										lowerCAmelCase_ :      int    				=				CLIPTextModel(A_							)
										lowerCAmelCase_ :      Union[str, Any]    				=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   ,						local_files_only=A_							)

										lowerCAmelCase_ :      Dict    				=				CLIPTextModelWithProjection(A_							)
										lowerCAmelCase_ :      Tuple    				=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   ,						local_files_only=A_							)

										lowerCAmelCase_ :      int    				=				{
										    '''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 						lowercase_ (				self   ,						__lowercase   ,						__lowercase=0							)					->    Optional[Any]:
										lowerCAmelCase_ :      List[str]    				=				floats_tensor((1, 3, 3_2, 3_2)   ,						rng=random.Random(A_							)							).to(A_							)
										lowerCAmelCase_ :      Optional[Any]    				=				image / 2 + 0.5
										if str(A_							).startswith('''mps'''							):
														lowerCAmelCase_ :      List[str]    				=				torch.manual_seed(A_							)
										else:
														lowerCAmelCase_ :      List[Any]    				=				torch.Generator(device=A_							).manual_seed(A_							)
										lowerCAmelCase_ :      Tuple    				=				{
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''image''': image,
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 5.0,
										    '''output_type''': '''numpy''',
										    '''strength''': 0.75,
										}
										return inputs




						def 						lowercase_ (				self							)					->    Optional[Any]:
										lowerCAmelCase_ :      Any    				=				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowerCAmelCase_ :      int    				=				self.get_dummy_components()
										lowerCAmelCase_ :      Any    				=				StableDiffusionXLImgaImgPipeline(**A_							)
										lowerCAmelCase_ :      Any    				=				sd_pipe.to(A_							)
										sd_pipe.set_progress_bar_config(disable=A_							)

										lowerCAmelCase_ :      Any    				=				self.get_dummy_inputs(A_							)
										lowerCAmelCase_ :      int    				=				sd_pipe(**A_							).images
										lowerCAmelCase_ :      List[Any]    				=				image[0, -3:, -3:, -1]

										assert image.shape == (1, 3_2, 3_2, 3)

										lowerCAmelCase_ :      Union[str, Any]    				=				np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]							)

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




						def 						lowercase_ (				self							)					->    Optional[Any]:
										super().test_attention_slicing_forward_pass(expected_max_diff=3e-3							)




						def 						lowercase_ (				self							)					->    Optional[Any]:
										super().test_inference_batch_single_identical(expected_max_diff=3e-3							)




						def 						lowercase_ (				self							)					->    Optional[Any]:
										pass




						def 						lowercase_ (				self							)					->    str:
										lowerCAmelCase_ :      Optional[Any]    				=				self.get_dummy_components()
										lowerCAmelCase_ :      Optional[Any]    				=				StableDiffusionXLImgaImgPipeline(**A_							)
										lowerCAmelCase_ :      Any    				=				sd_pipe.to(A_							)
										lowerCAmelCase_ :      List[Any]    				=				sd_pipe.to(A_							)
										sd_pipe.set_progress_bar_config(disable=A_							)

										# forward without prompt embeds
										lowerCAmelCase_ :      Union[str, Any]    				=				self.get_dummy_inputs(A_							)
										lowerCAmelCase_ :      Tuple    				=				3 * ['''this is a negative prompt''']
										lowerCAmelCase_ :      List[Any]    				=				negative_prompt
										lowerCAmelCase_ :      Tuple    				=				3 * [inputs['''prompt''']]

										lowerCAmelCase_ :      List[str]    				=				sd_pipe(**A_							)
										lowerCAmelCase_ :      Union[str, Any]    				=				output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										lowerCAmelCase_ :      Any    				=				self.get_dummy_inputs(A_							)
										lowerCAmelCase_ :      int    				=				3 * ['''this is a negative prompt''']
										lowerCAmelCase_ :      str    				=				3 * [inputs.pop('''prompt'''							)]

										(
										    (
										    lowerCAmelCase_						
										)				,  (
										    lowerCAmelCase_						
										)				,  (
										    lowerCAmelCase_						
										)				,  (
										    lowerCAmelCase_						
										)				,  						
										) :      Any    				=				sd_pipe.encode_prompt(A_   ,						negative_prompt=A_							)

										lowerCAmelCase_ :      int    				=				sd_pipe(
										    **A_   ,						prompt_embeds=A_   ,						negative_prompt_embeds=A_   ,						pooled_prompt_embeds=A_   ,						negative_pooled_prompt_embeds=A_   ,						)
										lowerCAmelCase_ :      str    				=				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







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







						'''simple docstring'''




						def 						lowercase_ (				self							)					->    Tuple:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




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

										lowerCAmelCase_ :      str    				=				self.get_inputs(A_							)
										lowerCAmelCase_ :      int    				=				pipe(**A_							).images
										lowerCAmelCase_ :      int    				=				image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										lowerCAmelCase_ :      List[str]    				=				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 math

import qiskit



def 			lowerCAmelCase (		lowerCAmelCase_ = 1 ,   lowerCAmelCase_ = 1 ,   lowerCAmelCase_ = 1 )-> qiskit.result.counts.Counts:
				if (
				    isinstance(lowerCAmelCase_ ,   lowerCAmelCase_ )
				    or isinstance(lowerCAmelCase_ ,   lowerCAmelCase_ )
				    or isinstance(lowerCAmelCase_ ,   lowerCAmelCase_ )
				):
								raise TypeError('''inputs must be integers.''' )

				if (input_a < 0) or (input_a < 0) or (carry_in < 0):
								raise ValueError('''inputs must be positive.''' )

				if (
				    (math.floor(lowerCAmelCase_ ) != input_a)
				    or (math.floor(lowerCAmelCase_ ) != input_a)
				    or (math.floor(lowerCAmelCase_ ) != carry_in)
				):
								raise ValueError('''inputs must be exact integers.''' )

				if (input_a > 2) or (input_a > 2) or (carry_in > 2):
								raise ValueError('''inputs must be less or equal to 2.''' )

				# build registers
				lowerCAmelCase_ :      str    				=				qiskit.QuantumRegister(4 ,   '''qr''' )
				lowerCAmelCase_ :      str    				=				qiskit.ClassicalRegister(2 ,   '''cr''' )
				# list the entries
				lowerCAmelCase_ :      Any    				=				[input_a, input_a, carry_in]

				lowerCAmelCase_ :      int    				=				qiskit.QuantumCircuit(lowerCAmelCase_ ,   lowerCAmelCase_ )

				for i in range(0 ,   3 ):
								if entry[i] == 2:
												quantum_circuit.h(lowerCAmelCase_ )  # for hadamard entries
								elif entry[i] == 1:
												quantum_circuit.x(lowerCAmelCase_ )  # for 1 entries
								elif entry[i] == 0:
												quantum_circuit.i(lowerCAmelCase_ )  # for 0 entries

    # build the circuit
				quantum_circuit.ccx(0 ,   1 ,   3 )  # ccx = toffoli gate
				quantum_circuit.cx(0 ,   1 )
				quantum_circuit.ccx(1 ,   2 ,   3 )
				quantum_circuit.cx(1 ,   2 )
				quantum_circuit.cx(0 ,   1 )

				quantum_circuit.measure([2, 3] ,   lowerCAmelCase_ )  # measure the last two qbits

				lowerCAmelCase_ :      Tuple    				=				qiskit.Aer.get_backend('''aer_simulator''' )
				lowerCAmelCase_ :      Union[str, Any]    				=				qiskit.execute(lowerCAmelCase_ ,   lowerCAmelCase_ ,   shots=1_000 )

				return job.result().get_counts(lowerCAmelCase_ )


if __name__ == "__main__":
						print(f"""Total sum count for state is: {quantum_full_adder(1, 1, 1)}""")