

'''simple docstring'''




import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    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   _SCREAMING_SNAKE_CASE    (    __a		,__a		,unittest.TestCase	):
 __SCREAMING_SNAKE_CASE     :Any			       =     StableDiffusionParadigmsPipeline
 __SCREAMING_SNAKE_CASE     :int			       =     TEXT_TO_IMAGE_PARAMS
 __SCREAMING_SNAKE_CASE     :int			       =     TEXT_TO_IMAGE_BATCH_PARAMS
 __SCREAMING_SNAKE_CASE     :List[str]			       =     TEXT_TO_IMAGE_IMAGE_PARAMS
 __SCREAMING_SNAKE_CASE     :Optional[int]			       =     TEXT_TO_IMAGE_IMAGE_PARAMS



 def  snake_case__  (    self		:    List[str]			):
      torch.manual_seed(0			)
      __magic_name__						   =				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''') ,      cross_attention_dim=32 ,      attention_head_dim=(2, 4) ,      use_linear_projection=UpperCAmelCase_ ,      )
      __magic_name__						   =				DDIMParallelScheduler(
          beta_start=0.00_085 ,      beta_end=0.012 ,      beta_schedule='''scaled_linear''' ,      clip_sample=UpperCAmelCase_ ,      set_alpha_to_one=UpperCAmelCase_ ,      )
      torch.manual_seed(0			)
      __magic_name__						   =				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			)
      __magic_name__						   =				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=512 ,      )
      __magic_name__						   =				CLIPTextModel(UpperCAmelCase_			)
      __magic_name__						   =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''			)

      __magic_name__						   =				{
          '''unet''': unet,
          '''scheduler''': scheduler,
          '''vae''': vae,
          '''text_encoder''': text_encoder,
          '''tokenizer''': tokenizer,
          '''safety_checker''': None,
          '''feature_extractor''': None,
      }
      return components



 def  snake_case__  (    self		:    Tuple ,      a__		:    Optional[Any] ,      a__		:    Optional[Any]=0			):
      if str(UpperCAmelCase_			).startswith('''mps'''			):
           __magic_name__						   =				torch.manual_seed(UpperCAmelCase_			)
      else:
           __magic_name__						   =				torch.Generator(device=UpperCAmelCase_			).manual_seed(UpperCAmelCase_			)
      __magic_name__						   =				{
          '''prompt''': '''a photograph of an astronaut riding a horse''',
          '''generator''': generator,
          '''num_inference_steps''': 10,
          '''guidance_scale''': 6.0,
          '''output_type''': '''numpy''',
          '''parallel''': 3,
          '''debug''': True,
      }
      return inputs



 def  snake_case__  (    self		:    List[str]			):
      __magic_name__						   =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      __magic_name__						   =				self.get_dummy_components()
      __magic_name__						   =				StableDiffusionParadigmsPipeline(**UpperCAmelCase_			)
      __magic_name__						   =				sd_pipe.to(UpperCAmelCase_			)
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

      __magic_name__						   =				self.get_dummy_inputs(UpperCAmelCase_			)
      __magic_name__						   =				sd_pipe(**UpperCAmelCase_			).images
      __magic_name__						   =				image[0, -3:, -3:, -1]
      assert image.shape == (1, 64, 64, 3)

      __magic_name__						   =				np.array([0.4_773, 0.5_417, 0.4_723, 0.4_925, 0.5_631, 0.4_752, 0.5_240, 0.4_935, 0.5_023]			)

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



 def  snake_case__  (    self		:    List[Any]			):
      __magic_name__						   =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      __magic_name__						   =				self.get_dummy_components()
      torch.manual_seed(0			)
      __magic_name__						   =				DDPMParallelScheduler()
      torch.manual_seed(0			)
      __magic_name__						   =				StableDiffusionParadigmsPipeline(**UpperCAmelCase_			)
      __magic_name__						   =				sd_pipe.to(UpperCAmelCase_			)
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

      __magic_name__						   =				self.get_dummy_inputs(UpperCAmelCase_			)
      __magic_name__						   =				sd_pipe(**UpperCAmelCase_			).images
      __magic_name__						   =				image[0, -3:, -3:, -1]
      assert image.shape == (1, 64, 64, 3)

      __magic_name__						   =				np.array([0.3_573, 0.4_420, 0.4_960, 0.4_799, 0.3_796, 0.3_879, 0.4_819, 0.4_365, 0.4_468]			)

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



 def  snake_case__  (    self		:    Tuple			):
      super().test_inference_batch_consistent(batch_sizes=[1, 2]			)



 def  snake_case__  (    self		:    List[Any]			):
      super().test_inference_batch_single_identical(batch_size=2 ,      expected_max_diff=3E-3			)



 def  snake_case__  (    self		:    Dict			):
      __magic_name__						   =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      __magic_name__						   =				self.get_dummy_components()
      __magic_name__						   =				StableDiffusionParadigmsPipeline(**UpperCAmelCase_			)
      __magic_name__						   =				sd_pipe.to(UpperCAmelCase_			)
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

      __magic_name__						   =				self.get_dummy_inputs(UpperCAmelCase_			)
      __magic_name__						   =				'''french fries'''
      __magic_name__						   =				sd_pipe(**UpperCAmelCase_ ,      negative_prompt=UpperCAmelCase_			)
      __magic_name__						   =				output.images
      __magic_name__						   =				image[0, -3:, -3:, -1]

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

      __magic_name__						   =				np.array([0.4_771, 0.5_420, 0.4_683, 0.4_918, 0.5_636, 0.4_725, 0.5_230, 0.4_923, 0.5_015]			)

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






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



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



 def  snake_case__  (    self		:    Union[str, Any] ,      a__		:    Optional[int]=0			):
      __magic_name__						   =				torch.Generator(device=UpperCAmelCase_			).manual_seed(UpperCAmelCase_			)
      __magic_name__						   =				{
          '''prompt''': '''a photograph of an astronaut riding a horse''',
          '''generator''': generator,
          '''num_inference_steps''': 10,
          '''guidance_scale''': 7.5,
          '''output_type''': '''numpy''',
          '''parallel''': 3,
          '''debug''': True,
      }
      return inputs



 def  snake_case__  (    self		:    Optional[int]			):
      __magic_name__						   =				'''stabilityai/stable-diffusion-2-base'''
      __magic_name__						   =				DDIMParallelScheduler.from_pretrained(UpperCAmelCase_ ,      subfolder='''scheduler'''			)
      __magic_name__						   =				StableDiffusionParadigmsPipeline.from_pretrained(UpperCAmelCase_ ,      scheduler=UpperCAmelCase_ ,      safety_checker=UpperCAmelCase_			)
      pipe.to(UpperCAmelCase_			)
      pipe.set_progress_bar_config(disable=UpperCAmelCase_			)
      pipe.enable_attention_slicing()

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

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

      __magic_name__						   =				np.array([0.9_622, 0.9_602, 0.9_748, 0.9_591, 0.9_630, 0.9_691, 0.9_661, 0.9_631, 0.9_741]			)

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













from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


UpperCAmelCase__  :	str     =logging.get_logger(__name__)

UpperCAmelCase__  :	Optional[int]     ={
    '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/config.json''',
    '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/config.json''',
    '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/config.json''',
    '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/config.json''',
    '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/config.json''',
}

class 					__A   (  a			):
				__A            = """gpt2"""
				__A            = ["""past_key_values"""]
				__A            = {
				    """hidden_size""": """n_embd""",
				    """max_position_embeddings""": """n_positions""",
				    """num_attention_heads""": """n_head""",
				    """num_hidden_layers""": """n_layer""",
				}


				def __init__(						self      ,       UpperCAmelCase_=50257      ,       UpperCAmelCase_=1024      ,       UpperCAmelCase_=768      ,       UpperCAmelCase_=12      ,       UpperCAmelCase_=12      ,       UpperCAmelCase_=None      ,       UpperCAmelCase_="gelu_new"      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=1E-5      ,       UpperCAmelCase_=0.0_2      ,       UpperCAmelCase_="cls_index"      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=None      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=50256      ,       UpperCAmelCase_=50256      ,       UpperCAmelCase_=False      ,       UpperCAmelCase_=False      ,       **UpperCAmelCase_      ,       ):
								lowerCamelCase		       =vocab_size
								lowerCamelCase		       =n_positions
								lowerCamelCase		       =n_embd
								lowerCamelCase		       =n_layer
								lowerCamelCase		       =n_head
								lowerCamelCase		       =n_inner
								lowerCamelCase		       =activation_function
								lowerCamelCase		       =resid_pdrop
								lowerCamelCase		       =embd_pdrop
								lowerCamelCase		       =attn_pdrop
								lowerCamelCase		       =layer_norm_epsilon
								lowerCamelCase		       =initializer_range
								lowerCamelCase		       =summary_type
								lowerCamelCase		       =summary_use_proj
								lowerCamelCase		       =summary_activation
								lowerCamelCase		       =summary_first_dropout
								lowerCamelCase		       =summary_proj_to_labels
								lowerCamelCase		       =scale_attn_weights
								lowerCamelCase		       =use_cache
								lowerCamelCase		       =scale_attn_by_inverse_layer_idx
								lowerCamelCase		       =reorder_and_upcast_attn

								lowerCamelCase		       =bos_token_id
								lowerCamelCase		       =eos_token_id

								super().__init__(bos_token_id=UpperCAmelCase_      ,       eos_token_id=UpperCAmelCase_      ,       **UpperCAmelCase_							)




class 					__A   (  a			):


				def __init__(						self      ,       UpperCAmelCase_      ,       UpperCAmelCase_ = "default"      ,       UpperCAmelCase_ = None      ,       UpperCAmelCase_ = False      ,       ):
								super().__init__(UpperCAmelCase_      ,       task=UpperCAmelCase_      ,       patching_specs=UpperCAmelCase_      ,       use_past=UpperCAmelCase_							)
								if not getattr(self._config      ,       """pad_token_id"""      ,       UpperCAmelCase_							):
												# TODO: how to do that better?
												lowerCamelCase		       =0


				@property
				def _snake_case				(						self							):
								lowerCamelCase		       =OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}							)
								if self.use_past:
												self.fill_with_past_key_values_(UpperCAmelCase_      ,       direction="""inputs"""							)
												lowerCamelCase		       ={0: """batch""", 1: """past_sequence + sequence"""}
								else:
												lowerCamelCase		       ={0: """batch""", 1: """sequence"""}

								return common_inputs


				@property
				def _snake_case				(						self							):
								return self._config.n_layer


				@property
				def _snake_case				(						self							):
								return self._config.n_head


				def _snake_case				(						self      ,       UpperCAmelCase_      ,       UpperCAmelCase_ = -1      ,       UpperCAmelCase_ = -1      ,       UpperCAmelCase_ = False      ,       UpperCAmelCase_ = None      ,       ):
								lowerCamelCase		       =super(UpperCAmelCase_      ,       self							).generate_dummy_inputs(
								    UpperCAmelCase_      ,       batch_size=UpperCAmelCase_      ,       seq_length=UpperCAmelCase_      ,       is_pair=UpperCAmelCase_      ,       framework=UpperCAmelCase_							)

								# We need to order the input in the way they appears in the forward()
								lowerCamelCase		       =OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}							)

								# Need to add the past_keys
								if self.use_past:
												if not is_torch_available():
																raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
												else:
																import torch

																lowerCamelCase       ,     lowerCamelCase		       =common_inputs["""input_ids"""].shape
																# Not using the same length for past_key_values
																lowerCamelCase		       =seqlen + 2
																lowerCamelCase		       =(
																    batch,
																    self.num_attention_heads,
																    past_key_values_length,
																    self._config.hidden_size // self.num_attention_heads,
																)
																lowerCamelCase		       =[
																    (torch.zeros(UpperCAmelCase_							), torch.zeros(UpperCAmelCase_							)) for _ in range(self.num_layers							)
																]

								lowerCamelCase		       =common_inputs["""attention_mask"""]
								if self.use_past:
												lowerCamelCase		       =ordered_inputs["""attention_mask"""].dtype
												lowerCamelCase		       =torch.cat(
												    [ordered_inputs["""attention_mask"""], torch.ones(UpperCAmelCase_      ,       UpperCAmelCase_      ,       dtype=UpperCAmelCase_							)]      ,       dim=1							)

								return ordered_inputs


				@property
				def _snake_case				(						self							):
								return 13





