
"""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


a		:					List[Any]    	=					logging.get_logger(__name__)

a		:					str    	=					{
    '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 						lowercase(_lowercase					):
     __snake_case:  str  				=    'gpt2'
     __snake_case:  Optional[Any]  				=    ['past_key_values']
     __snake_case:  Dict  				=    {
         'hidden_size': 'n_embd',
         'max_position_embeddings': 'n_positions',
         'num_attention_heads': 'n_head',
         'num_hidden_layers': 'n_layer',
     }



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







         """simple docstring"""



         a__    = vocab_size
         a__    = n_positions
         a__    = n_embd
         a__    = n_layer
         a__    = n_head
         a__    = n_inner
         a__    = activation_function
         a__    = resid_pdrop
         a__    = embd_pdrop
         a__    = attn_pdrop
         a__    = layer_norm_epsilon
         a__    = initializer_range
         a__    = summary_type
         a__    = summary_use_proj
         a__    = summary_activation
         a__    = summary_first_dropout
         a__    = summary_proj_to_labels
         a__    = scale_attn_weights
         a__    = use_cache
         a__    = scale_attn_by_inverse_layer_idx
         a__    = reorder_and_upcast_attn

         a__    = bos_token_id
         a__    = eos_token_id

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






class 						lowercase(_lowercase					):



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE = "default"    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = False    ,							)		->    int:







         """simple docstring"""



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



     @property
     def  lowercase__     (       self      )		->    Mapping[str, Mapping[int, str]]:







         """simple docstring"""



         a__    = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}      )
         if self.use_past:
             self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE    ,							direction='inputs'      )
             a__    = {0: 'batch', 1: 'past_sequence + sequence'}
         else:
             a__    = {0: 'batch', 1: 'sequence'}

         return common_inputs



     @property
     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         return self._config.n_layer



     @property
     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         return self._config.n_head



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE = -1    ,							__SCREAMING_SNAKE_CASE = -1    ,							__SCREAMING_SNAKE_CASE = False    ,							__SCREAMING_SNAKE_CASE = None    ,							)		->    Mapping[str, Any]:







         """simple docstring"""



         a__    = super(__SCREAMING_SNAKE_CASE    ,							self      ).generate_dummy_inputs(
             __SCREAMING_SNAKE_CASE    ,							batch_size=__SCREAMING_SNAKE_CASE    ,							seq_length=__SCREAMING_SNAKE_CASE    ,							is_pair=__SCREAMING_SNAKE_CASE    ,							framework=__SCREAMING_SNAKE_CASE      )

         # We need to order the input in the way they appears in the forward()
         a__    = 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__    = common_inputs['input_ids'].shape
                 # Not using the same length for past_key_values
                 a__    = seqlen + 2
                 a__    = (
                     batch,
                     self.num_attention_heads,
                     past_key_values_length,
                     self._config.hidden_size // self.num_attention_heads,
                 )
                 a__    = [
                     (torch.zeros(__SCREAMING_SNAKE_CASE      ), torch.zeros(__SCREAMING_SNAKE_CASE      )) for _ in range(self.num_layers      )
                 ]

         a__    = common_inputs['attention_mask']
         if self.use_past:
             a__    = ordered_inputs['attention_mask'].dtype
             a__    = torch.cat(
                 [ordered_inputs['attention_mask'], torch.ones(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							dtype=__SCREAMING_SNAKE_CASE      )]    ,							dim=1      )

         return ordered_inputs




     @property
     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         return 1_3




"""simple docstring"""




import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


a		:					str    	=					False







@nightly
@require_torch_gpu
class 						lowercase(unittest.TestCase					):



     def  lowercase__     (       self      )		->    Any:







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



         a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'      )
         # remove text_unet
         pipe.remove_unused_weights()
         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'      )

         a__    = torch.manual_seed(0      )
         a__    = pipe(
             prompt='first prompt'    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy'    ,							).images

         with tempfile.TemporaryDirectory() as tmpdirname:
             pipe.save_pretrained(__SCREAMING_SNAKE_CASE      )
             a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained(__SCREAMING_SNAKE_CASE      )

         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = generator.manual_seed(0      )
         a__    = pipe(
             prompt='first prompt'    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy'    ,							).images

         assert np.abs(image - new_image      ).sum() < 1e-5, "Models don't have the same forward pass"




     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'      )
         pipe.remove_unused_weights()
         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = 'cyberpunk 2077'
         a__    = load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'      )
         a__    = torch.manual_seed(0      )
         a__    = pipe(
             prompt=__SCREAMING_SNAKE_CASE    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=5_0    ,							output_type='numpy'    ,							).images

         a__    = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         a__    = np.array([0.07_87, 0.08_49, 0.08_26, 0.08_12, 0.08_07, 0.07_95, 0.08_18, 0.07_98, 0.07_79]      )

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


