





"""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 			_UpperCAmelCase  (       UpperCAmelCase__      ,       UpperCAmelCase__      ,       unittest.TestCase		):



      '''simple docstring'''
      lowercase_				:			int        =       StableDiffusionParadigmsPipeline
      lowercase_				:			Optional[int]        =       TEXT_TO_IMAGE_PARAMS
      lowercase_				:			Optional[Any]        =       TEXT_TO_IMAGE_BATCH_PARAMS
      lowercase_				:			Tuple        =       TEXT_TO_IMAGE_IMAGE_PARAMS
      lowercase_				:			Dict        =       TEXT_TO_IMAGE_IMAGE_PARAMS

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        torch.manual_seed(0  )
        A_  :	str    						=  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') ,				cross_attention_dim=3_2 ,				attention_head_dim=(2, 4) ,				use_linear_projection=snake_case_ ,				)
        A_  :	int    						=  DDIMParallelScheduler(
            beta_start=0.0_00_85 ,				beta_end=0.0_12 ,				beta_schedule='scaled_linear' ,				clip_sample=snake_case_ ,				set_alpha_to_one=snake_case_ ,				)
        torch.manual_seed(0  )
        A_  :	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  )
        A_  :	Optional[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=5_1_2 ,				)
        A_  :	int    						=  CLIPTextModel(snake_case_  )
        A_  :	Any    						=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

        A_  :	Optional[int]    						=  {
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'safety_checker': None,
            'feature_extractor': None,
        }
        return components

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_=0  ):

        """simple docstring"""

        if str(snake_case_  ).startswith('mps'  ):
          A_  :	Optional[int]    						=  torch.manual_seed(snake_case_  )
        else:
          A_  :	Tuple    						=  torch.Generator(device=snake_case_  ).manual_seed(snake_case_  )
        A_  :	Tuple    						=  {
            'prompt': 'a photograph of an astronaut riding a horse',
            'generator': generator,
            'num_inference_steps': 1_0,
            'guidance_scale': 6.0,
            'output_type': 'numpy',
            'parallel': 3,
            'debug': True,
        }
        return inputs

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  'cpu'  # ensure determinism for the device-dependent torch.Generator
        A_  :	List[Any]    						=  self.get_dummy_components()
        A_  :	Dict    						=  StableDiffusionParadigmsPipeline(**snake_case_  )
        A_  :	Dict    						=  sd_pipe.to(snake_case_  )
        sd_pipe.set_progress_bar_config(disable=snake_case_  )

        A_  :	Tuple    						=  self.get_dummy_inputs(snake_case_  )
        A_  :	Optional[Any]    						=  sd_pipe(**snake_case_  ).images
        A_  :	str    						=  image[0, -3:, -3:, -1]
        assert image.shape == (1, 6_4, 6_4, 3)

        A_  :	Dict    						=  np.array([0.47_73, 0.54_17, 0.47_23, 0.49_25, 0.56_31, 0.47_52, 0.52_40, 0.49_35, 0.50_23]  )

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

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Dict    						=  'cpu'  # ensure determinism for the device-dependent torch.Generator
        A_  :	Optional[int]    						=  self.get_dummy_components()
        torch.manual_seed(0  )
        A_  :	int    						=  DDPMParallelScheduler()
        torch.manual_seed(0  )
        A_  :	int    						=  StableDiffusionParadigmsPipeline(**snake_case_  )
        A_  :	Union[str, Any]    						=  sd_pipe.to(snake_case_  )
        sd_pipe.set_progress_bar_config(disable=snake_case_  )

        A_  :	List[Any]    						=  self.get_dummy_inputs(snake_case_  )
        A_  :	str    						=  sd_pipe(**snake_case_  ).images
        A_  :	Optional[Any]    						=  image[0, -3:, -3:, -1]
        assert image.shape == (1, 6_4, 6_4, 3)

        A_  :	List[str]    						=  np.array([0.35_73, 0.44_20, 0.49_60, 0.47_99, 0.37_96, 0.38_79, 0.48_19, 0.43_65, 0.44_68]  )

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

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        super().test_inference_batch_consistent(batch_sizes=[1, 2]  )

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        super().test_inference_batch_single_identical(batch_size=2 ,				expected_max_diff=3E-3  )

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  'cpu'  # ensure determinism for the device-dependent torch.Generator
        A_  :	str    						=  self.get_dummy_components()
        A_  :	Union[str, Any]    						=  StableDiffusionParadigmsPipeline(**snake_case_  )
        A_  :	List[Any]    						=  sd_pipe.to(snake_case_  )
        sd_pipe.set_progress_bar_config(disable=snake_case_  )

        A_  :	Optional[int]    						=  self.get_dummy_inputs(snake_case_  )
        A_  :	str    						=  'french fries'
        A_  :	Any    						=  sd_pipe(**snake_case_ ,				negative_prompt=snake_case_  )
        A_  :	int    						=  output.images
        A_  :	Any    						=  image[0, -3:, -3:, -1]

        assert image.shape == (1, 6_4, 6_4, 3)

        A_  :	List[str]    						=  np.array([0.47_71, 0.54_20, 0.46_83, 0.49_18, 0.56_36, 0.47_25, 0.52_30, 0.49_23, 0.50_15]  )

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


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



      '''simple docstring'''

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

      def  lowerCamelCase_      (					self ,				snake_case_=0  ):

        """simple docstring"""

        A_  :	Dict    						=  torch.Generator(device=snake_case_  ).manual_seed(snake_case_  )
        A_  :	Union[str, Any]    						=  {
            'prompt': 'a photograph of an astronaut riding a horse',
            'generator': generator,
            'num_inference_steps': 1_0,
            'guidance_scale': 7.5,
            'output_type': 'numpy',
            'parallel': 3,
            'debug': True,
        }
        return inputs

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	int    						=  'stabilityai/stable-diffusion-2-base'
        A_  :	Union[str, Any]    						=  DDIMParallelScheduler.from_pretrained(snake_case_ ,				subfolder='scheduler'  )
        A_  :	Tuple    						=  StableDiffusionParadigmsPipeline.from_pretrained(snake_case_ ,				scheduler=snake_case_ ,				safety_checker=snake_case_  )
        pipe.to(snake_case_  )
        pipe.set_progress_bar_config(disable=snake_case_  )
        pipe.enable_attention_slicing()

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

        assert image.shape == (1, 5_1_2, 5_1_2, 3)

        A_  :	List[Any]    						=  np.array([0.96_22, 0.96_02, 0.97_48, 0.95_91, 0.96_30, 0.96_91, 0.96_61, 0.96_31, 0.97_41]  )

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






"""simple docstring"""




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


lowerCamelCase_					:						Union[str, Any]      = logging.get_logger(__name__)

lowerCamelCase_					:						Optional[Any]      = {
    '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 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_				:			Optional[Any]        =       """gpt2"""
      lowercase_				:			Optional[int]        =       ["""past_key_values"""]
      lowercase_				:			Dict        =       {
          """hidden_size""": """n_embd""",
          """max_position_embeddings""": """n_positions""",
          """num_attention_heads""": """n_head""",
          """num_hidden_layers""": """n_layer""",
      }

      def __init__(					self ,				snake_case_=5_0_2_5_7 ,				snake_case_=1_0_2_4 ,				snake_case_=7_6_8 ,				snake_case_=1_2 ,				snake_case_=1_2 ,				snake_case_=None ,				snake_case_="gelu_new" ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=1E-5 ,				snake_case_=0.02 ,				snake_case_="cls_index" ,				snake_case_=True ,				snake_case_=None ,				snake_case_=True ,				snake_case_=0.1 ,				snake_case_=True ,				snake_case_=True ,				snake_case_=5_0_2_5_6 ,				snake_case_=5_0_2_5_6 ,				snake_case_=False ,				snake_case_=False ,				**snake_case_ ,				):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  vocab_size
        A_  :	List[Any]    						=  n_positions
        A_  :	List[Any]    						=  n_embd
        A_  :	Tuple    						=  n_layer
        A_  :	List[Any]    						=  n_head
        A_  :	List[str]    						=  n_inner
        A_  :	str    						=  activation_function
        A_  :	Optional[Any]    						=  resid_pdrop
        A_  :	int    						=  embd_pdrop
        A_  :	Tuple    						=  attn_pdrop
        A_  :	str    						=  layer_norm_epsilon
        A_  :	Any    						=  initializer_range
        A_  :	Union[str, Any]    						=  summary_type
        A_  :	Optional[Any]    						=  summary_use_proj
        A_  :	Dict    						=  summary_activation
        A_  :	Optional[int]    						=  summary_first_dropout
        A_  :	Optional[int]    						=  summary_proj_to_labels
        A_  :	Any    						=  scale_attn_weights
        A_  :	Optional[Any]    						=  use_cache
        A_  :	Dict    						=  scale_attn_by_inverse_layer_idx
        A_  :	Any    						=  reorder_and_upcast_attn

        A_  :	Optional[Any]    						=  bos_token_id
        A_  :	List[Any]    						=  eos_token_id

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


class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(					self ,				snake_case_ ,				snake_case_ = "default" ,				snake_case_ = None ,				snake_case_ = False ,				):

        """simple docstring"""

        super().__init__(snake_case_ ,				task=snake_case_ ,				patching_specs=snake_case_ ,				use_past=snake_case_  )
        if not getattr(self._config ,				'pad_token_id' ,				snake_case_  ):
          # TODO: how to do that better?
          A_  :	Tuple    						=  0

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Dict    						=  OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}  )
        if self.use_past:
          self.fill_with_past_key_values_(snake_case_ ,				direction='inputs'  )
          A_  :	List[str]    						=  {0: 'batch', 1: 'past_sequence + sequence'}
        else:
          A_  :	Tuple    						=  {0: 'batch', 1: 'sequence'}

        return common_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_layer

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_head

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

        A_  :	int    						=  super(snake_case_ ,				self  ).generate_dummy_inputs(
            snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )

        # We need to order the input in the way they appears in the forward()
        A_  :	Optional[Any]    						=  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

            A_						,	A_  :	List[str]    						=  common_inputs['input_ids'].shape
            # Not using the same length for past_key_values
            A_  :	Optional[Any]    						=  seqlen + 2
            A_  :	Any    						=  (
                batch,
                self.num_attention_heads,
                past_key_values_length,
                self._config.hidden_size // self.num_attention_heads,
            )
            A_  :	Any    						=  [
                (torch.zeros(snake_case_  ), torch.zeros(snake_case_  )) for _ in range(self.num_layers  )
            ]

        A_  :	List[Any]    						=  common_inputs['attention_mask']
        if self.use_past:
          A_  :	List[Any]    						=  ordered_inputs['attention_mask'].dtype
          A_  :	Any    						=  torch.cat(
              [ordered_inputs['attention_mask'], torch.ones(snake_case_ ,				snake_case_ ,				dtype=snake_case_  )] ,				dim=1  )

        return ordered_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return 1_3