


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 							_UpperCamelCase (						A,A,unittest.TestCase						):

   '''simple docstring'''







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

   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         torch.manual_seed(0							)
         __lowerCamelCase     :      Optional[int]       						=						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=_lowerCamelCase       ,  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     :      List[str]       						=						EulerDiscreteScheduler(
             beta_start=0.00_085       ,  beta_end=0.012       ,  steps_offset=1       ,  beta_schedule="""scaled_linear"""       ,  timestep_spacing="""leading"""       ,  )
         torch.manual_seed(0							)
         __lowerCamelCase     :      List[Any]       						=						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     :      Optional[Any]       						=						CLIPTextModel(_lowerCamelCase							)
         __lowerCamelCase     :      str       						=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       ,  local_files_only=_lowerCamelCase							)

         __lowerCamelCase     :      Tuple       						=						CLIPTextModelWithProjection(_lowerCamelCase							)
         __lowerCamelCase     :      Any       						=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       ,  local_files_only=_lowerCamelCase							)

         __lowerCamelCase     :      Tuple       						=						{
             """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  : str       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : Any=0							):






         '''simple docstring'''



         __lowerCamelCase     :      str       						=						floats_tensor((1, 3, 3_2, 3_2)       ,  rng=random.Random(_lowerCamelCase							)							).to(_lowerCamelCase							)
         __lowerCamelCase     :      Dict       						=						image / 2 + 0.5
         if str(_lowerCamelCase							).startswith("""mps"""							):
               __lowerCamelCase     :      List[str]       						=						torch.manual_seed(_lowerCamelCase							)
         else:
               __lowerCamelCase     :      str       						=						torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
         __lowerCamelCase     :      Optional[int]       						=						{
             """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   _snake_case    (  self  : List[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
         __lowerCamelCase     :      Optional[Any]       						=						self.get_dummy_components()
         __lowerCamelCase     :      Optional[Any]       						=						StableDiffusionXLImgaImgPipeline(**_lowerCamelCase							)
         __lowerCamelCase     :      str       						=						sd_pipe.to(_lowerCamelCase							)
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

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

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

         __lowerCamelCase     :      List[Any]       						=						np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165]							)

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

   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         super().test_attention_slicing_forward_pass(expected_max_diff=3E-3							)

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



         super().test_inference_batch_single_identical(expected_max_diff=3E-3							)

   def   _snake_case    (  self  : int							):






         '''simple docstring'''



         pass


   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Dict       						=						self.get_dummy_components()
         __lowerCamelCase     :      Dict       						=						StableDiffusionXLImgaImgPipeline(**_lowerCamelCase							)
         __lowerCamelCase     :      Optional[int]       						=						sd_pipe.to(_lowerCamelCase							)
         __lowerCamelCase     :      List[Any]       						=						sd_pipe.to(_lowerCamelCase							)
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

         # forward without prompt embeds
         __lowerCamelCase     :      Tuple       						=						self.get_dummy_inputs(_lowerCamelCase							)
         __lowerCamelCase     :      str       						=						3 * ["""this is a negative prompt"""]
         __lowerCamelCase     :      Optional[Any]       						=						negative_prompt
         __lowerCamelCase     :      Tuple       						=						3 * [inputs["""prompt"""]]

         __lowerCamelCase     :      int       						=						sd_pipe(**_lowerCamelCase							)
         __lowerCamelCase     :      Dict       						=						output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         __lowerCamelCase     :      List[str]       						=						self.get_dummy_inputs(_lowerCamelCase							)
         __lowerCamelCase     :      Any       						=						3 * ["""this is a negative prompt"""]
         __lowerCamelCase     :      List[str]       						=						3 * [inputs.pop("""prompt"""							)]

         (
             (
             __lowerCamelCase
         )						, (
             __lowerCamelCase
         )						, (
             __lowerCamelCase
         )						, (
             __lowerCamelCase
         )						, 
         )     :      int       						=						sd_pipe.encode_prompt(_lowerCamelCase       ,  negative_prompt=_lowerCamelCase							)

         __lowerCamelCase     :      Optional[Any]       						=						sd_pipe(
             **_lowerCamelCase       ,  prompt_embeds=_lowerCamelCase       ,  negative_prompt_embeds=_lowerCamelCase       ,  pooled_prompt_embeds=_lowerCamelCase       ,  negative_pooled_prompt_embeds=_lowerCamelCase       ,  )
         __lowerCamelCase     :      int       						=						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 							_UpperCamelCase (						unittest.TestCase						):

   '''simple docstring'''







   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()

   def   _snake_case    (  self  : int       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : int="cpu"       ,  _lowerCamelCase  : Optional[Any]=torch.floataa       ,  _lowerCamelCase  : Optional[Any]=0							):






         '''simple docstring'''



         __lowerCamelCase     :      str       						=						torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
         __lowerCamelCase     :      str       						=						np.random.RandomState(_lowerCamelCase							).standard_normal((1, 4, 6_4, 6_4)							)
         __lowerCamelCase     :      Tuple       						=						torch.from_numpy(_lowerCamelCase							).to(device=_lowerCamelCase       ,  dtype=_lowerCamelCase							)
         __lowerCamelCase     :      Union[str, 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  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""							)
         pipe.to(_lowerCamelCase							)
         pipe.set_progress_bar_config(disable=_lowerCamelCase							)

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

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         __lowerCamelCase     :      Optional[Any]       						=						np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]							)
         assert np.abs(image_slice - expected_slice							).max() < 7E-3







import qiskit





def   _UpperCAmelCase       (     UpperCAmelCase      :			int						,	UpperCAmelCase      :			int      ):
      """simple docstring"""




      __lowerCamelCase     :      Dict       						=						qiskit.Aer.get_backend("""aer_simulator"""      )

      __lowerCamelCase     :      Dict       						=						qiskit.QuantumCircuit(4						,	2      )
      # encode inputs in qubits 0 and 1
      if bita == 1:
            qc_ha.x(0      )
      if bita == 1:
            qc_ha.x(1      )
      qc_ha.barrier()

      # use cnots to write XOR of the inputs on qubit2
      qc_ha.cx(0						,	2      )
      qc_ha.cx(1						,	2      )

      # use ccx / toffoli gate to write AND of the inputs on qubit3
      qc_ha.ccx(0						,	1						,	3      )
      qc_ha.barrier()

      # extract outputs
      qc_ha.measure(2						,	0      )  # extract XOR value
      qc_ha.measure(3						,	1      )  # extract AND value

      # Execute the circuit on the qasm simulator
      __lowerCamelCase     :      str       						=						qiskit.execute(UpperCAmelCase						,	UpperCAmelCase						,	shots=1_000      )

      # Return the histogram data of the results of the experiment
      return job.result().get_counts(UpperCAmelCase      )


if __name__ == "__main__":
    __UpperCamelCase    :						List[str]     =							half_adder(1, 1)
    print(F'''Half Adder Output Qubit Counts: {counts}''')



