






"""simple docstring"""
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_ (      snake_case_    ,		snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							List[str]					=      StableDiffusionXLPipeline
      lowerCamelCase__			:							Optional[Any]					=      TEXT_TO_IMAGE_PARAMS
      lowerCamelCase__			:							List[str]					=      TEXT_TO_IMAGE_BATCH_PARAMS
      lowerCamelCase__			:							Dict					=      TEXT_TO_IMAGE_IMAGE_PARAMS
      lowerCamelCase__			:							str					=      TEXT_TO_IMAGE_IMAGE_PARAMS




      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     Optional[Any]								=		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__	:     Dict								=		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[str]								=		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__	:     Union[str, Any]								=		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__	:     List[Any]								=		CLIPTextModel(lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		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__	:     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      a__				(self,	lowerCamelCase_,	lowerCamelCase_=0   ):

       '''simple docstring'''



       if str(lowerCamelCase_   ).startswith('mps'   ):
        lowerCamelCase__	:     List[Any]								=		torch.manual_seed(lowerCamelCase_   )
       else:
        lowerCamelCase__	:     Dict								=		torch.Generator(device=lowerCamelCase_   ).manual_seed(lowerCamelCase_   )
       lowerCamelCase__	:     int								=		{
           '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      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		'cpu'  # ensure determinism for the device-dependent torch.Generator
       lowerCamelCase__	:     Any								=		self.get_dummy_components()
       lowerCamelCase__	:     Union[str, Any]								=		StableDiffusionXLPipeline(**lowerCamelCase_   )
       lowerCamelCase__	:     Any								=		sd_pipe.to(lowerCamelCase_   )
       sd_pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       lowerCamelCase__	:     str								=		self.get_dummy_inputs(lowerCamelCase_   )
       lowerCamelCase__	:     List[str]								=		sd_pipe(**lowerCamelCase_   ).images
       lowerCamelCase__	:     Union[str, Any]								=		image[0, -3:, -3:, -1]

       assert image.shape == (1, 6_4, 6_4, 3)
       lowerCamelCase__	:     List[Any]								=		np.array([0.5_873, 0.6_128, 0.4_797, 0.5_122, 0.5_674, 0.4_639, 0.5_227, 0.5_149, 0.4_747]   )

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




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		self.get_dummy_components()
       lowerCamelCase__	:     Tuple								=		StableDiffusionXLPipeline(**lowerCamelCase_   )
       lowerCamelCase__	:     Any								=		sd_pipe.to(lowerCamelCase_   )
       lowerCamelCase__	:     Optional[int]								=		sd_pipe.to(lowerCamelCase_   )
       sd_pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       # forward without prompt embeds
       lowerCamelCase__	:     Tuple								=		self.get_dummy_inputs(lowerCamelCase_   )
       lowerCamelCase__	:     Optional[Any]								=		3 * ['this is a negative prompt']
       lowerCamelCase__	:     Dict								=		negative_prompt
       lowerCamelCase__	:     Optional[int]								=		3 * [inputs['prompt']]

       lowerCamelCase__	:     int								=		sd_pipe(**lowerCamelCase_   )
       lowerCamelCase__	:     int								=		output.images[0, -3:, -3:, -1]

       # forward with prompt embeds
       lowerCamelCase__	:     Dict								=		self.get_dummy_inputs(lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		3 * ['this is a negative prompt']
       lowerCamelCase__	:     List[Any]								=		3 * [inputs.pop('prompt'   )]

       (
           (
           lowerCamelCase__
       )							,	(
           lowerCamelCase__
       )							,	(
           lowerCamelCase__
       )							,	(
           lowerCamelCase__
       )							,	
       )	:     Dict								=		sd_pipe.encode_prompt(lowerCamelCase_,	negative_prompt=lowerCamelCase_   )

       lowerCamelCase__	:     Union[str, Any]								=		sd_pipe(
           **lowerCamelCase_,	prompt_embeds=lowerCamelCase_,	negative_prompt_embeds=lowerCamelCase_,	pooled_prompt_embeds=lowerCamelCase_,	negative_pooled_prompt_embeds=lowerCamelCase_,	)
       lowerCamelCase__	:     Union[str, 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      a__				(self   ):

       '''simple docstring'''



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





      def      a__				(self   ):

       '''simple docstring'''



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



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







      '''simple docstring'''

      def      a__				(self   ):

       '''simple docstring'''



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




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_="cpu",	lowerCamelCase_=torch.floataa,	lowerCamelCase_=0   ):

       '''simple docstring'''



       lowerCamelCase__	:     Dict								=		torch.Generator(device=lowerCamelCase_   ).manual_seed(lowerCamelCase_   )
       lowerCamelCase__	:     Optional[Any]								=		np.random.RandomState(lowerCamelCase_   ).standard_normal((1, 4, 6_4, 6_4)   )
       lowerCamelCase__	:     Union[str, Any]								=		torch.from_numpy(lowerCamelCase_   ).to(device=lowerCamelCase_,	dtype=lowerCamelCase_   )
       lowerCamelCase__	:     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      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'   )
       pipe.to(lowerCamelCase_   )
       pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       lowerCamelCase__	:     Dict								=		self.get_inputs(lowerCamelCase_   )
       lowerCamelCase__	:     Tuple								=		pipe(**lowerCamelCase_   ).images
       lowerCamelCase__	:     Optional[int]								=		image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 5_1_2, 5_1_2, 3)
       lowerCamelCase__	:     Union[str, 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









"""simple docstring"""
from transformers import HfArgumentParser, PyTorchBenchmark, PyTorchBenchmarkArguments






def 			lowerCamelCase_    (		):
 lowerCamelCase__	:     Tuple								=		HfArgumentParser(_lowerCamelCase							)
 try:
  lowerCamelCase__	:     Dict								=		parser.parse_args_into_dataclasses()[0]
 except ValueError as e:
  lowerCamelCase__	:     Optional[int]								=		'Arg --no_{0} is no longer used, please use --no-{0} instead.'
  lowerCamelCase__	:     Optional[Any]								=		' '.join(str(_lowerCamelCase							).split(' '							)[:-1]							)
  lowerCamelCase__	:     int								=		''
  lowerCamelCase__	:     Optional[int]								=		eval(str(_lowerCamelCase							).split(' '							)[-1]							)
  lowerCamelCase__	:     Tuple								=		[]
  for arg in depreciated_args:
   # arg[2:] removes '--'
   if arg[2:] in PyTorchBenchmarkArguments.deprecated_args:
    # arg[5:] removes '--no_'
    full_error_msg += arg_error_msg.format(arg[5:]							)
   else:
    wrong_args.append(_lowerCamelCase							)
  if len(_lowerCamelCase							) > 0:
   lowerCamelCase__	:     Optional[int]								=		full_error_msg + begin_error_msg + str(_lowerCamelCase							)
  raise ValueError(_lowerCamelCase							)

 lowerCamelCase__	:     Any								=		PyTorchBenchmark(args=_lowerCamelCase							)
 benchmark.run()


if __name__ == "__main__":
      main()

