
import unittest

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

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()

class __snake_case		(      unittest.TestCase     ):
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           torch.manual_seed(0      )
           lowercase							:     Dict       	=      UNetaDModel(
               block_out_channels=(32, 64)		,layers_per_block=2		,sample_size=32		,in_channels=3		,out_channels=3		,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")		,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")		,)
           return model
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           torch.manual_seed(0      )
           lowercase							:     str       	=      VQModel(
               block_out_channels=[32, 64]		,in_channels=3		,out_channels=3		,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]		,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]		,latent_channels=3		,)
           return model
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           torch.manual_seed(0      )
           lowercase							:     Union[str, Any]       	=      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		,)
           return CLIPTextModel(SCREAMING_SNAKE_CASE_      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      self.dummy_uncond_unet
           lowercase							:     Optional[Any]       	=      DDIMScheduler()
           lowercase							:     List[Any]       	=      self.dummy_vq_model

           lowercase							:     Tuple       	=      LDMPipeline(unet=SCREAMING_SNAKE_CASE_		,vqvae=SCREAMING_SNAKE_CASE_		,scheduler=SCREAMING_SNAKE_CASE_      )
           ldm.to(SCREAMING_SNAKE_CASE_      )
           ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_      )

           lowercase							:     str       	=      torch.manual_seed(0      )
           lowercase							:     Dict       	=      ldm(generator=SCREAMING_SNAKE_CASE_		,num_inference_steps=2		,output_type="""numpy"""      ).images

           lowercase							:     Tuple       	=      torch.manual_seed(0      )
           lowercase							:     int       	=      ldm(generator=SCREAMING_SNAKE_CASE_		,num_inference_steps=2		,output_type="""numpy"""		,return_dict=SCREAMING_SNAKE_CASE_      )[0]

           lowercase							:     Dict       	=      image[0, -3:, -3:, -1]
           lowercase							:     int       	=      image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 64, 64, 3)
           lowercase							:     int       	=      np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172]      )
           lowercase							:     Optional[Any]       	=      1e-2 if torch_device != 'mps' else 3e-2

           assert np.abs(image_slice.flatten() - expected_slice      ).max() < tolerance
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice      ).max() < tolerance






@slow
@require_torch
class __snake_case		(      unittest.TestCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256"""      )
           ldm.to(SCREAMING_SNAKE_CASE_      )
           ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_      )

           lowercase							:     int       	=      torch.manual_seed(0      )
           lowercase							:     Optional[Any]       	=      ldm(generator=SCREAMING_SNAKE_CASE_		,num_inference_steps=5		,output_type="""numpy"""      ).images

           lowercase							:     Optional[int]       	=      image[0, -3:, -3:, -1]

           assert image.shape == (1, 256, 256, 3)
           lowercase							:     int       	=      np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447]      )
           lowercase							:     Union[str, Any]       	=      1e-2 if torch_device != 'mps' else 3e-2

           assert np.abs(image_slice.flatten() - expected_slice      ).max() < tolerance





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          =       logging.get_logger(__name__)


__UpperCAmelCase          =       {
    '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
    '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
    '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
    '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
    '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
    '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}



class 				lowerCAmelCase_		(  a__							):
       UpperCAmelCase__				:					List[str]        =  "codegen"
       UpperCAmelCase__				:					str        =  {
           "max_position_embeddings": "n_positions",
           "hidden_size": "n_embd",
           "num_attention_heads": "n_head",
           "num_hidden_layers": "n_layer",
       }
       def __init__(			self,			SCREAMING_SNAKE_CASE_=5_0400,			SCREAMING_SNAKE_CASE_=2048,			SCREAMING_SNAKE_CASE_=2048,			SCREAMING_SNAKE_CASE_=4096,			SCREAMING_SNAKE_CASE_=28,			SCREAMING_SNAKE_CASE_=16,			SCREAMING_SNAKE_CASE_=64,			SCREAMING_SNAKE_CASE_=None,			SCREAMING_SNAKE_CASE_="gelu_new",			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=1e-5,			SCREAMING_SNAKE_CASE_=0.02,			SCREAMING_SNAKE_CASE_=True,			SCREAMING_SNAKE_CASE_=5_0256,			SCREAMING_SNAKE_CASE_=5_0256,			SCREAMING_SNAKE_CASE_=False,			**SCREAMING_SNAKE_CASE_,			)     ->		Tuple:
          UpperCamelCase    :  Tuple							=	vocab_size
          UpperCamelCase    :  Optional[int]							=	n_ctx
          UpperCamelCase    :  Optional[int]							=	n_positions
          UpperCamelCase    :  List[str]							=	n_embd
          UpperCamelCase    :  Dict							=	n_layer
          UpperCamelCase    :  int							=	n_head
          UpperCamelCase    :  Union[str, Any]							=	n_inner
          UpperCamelCase    :  int							=	rotary_dim
          UpperCamelCase    :  Optional[Any]							=	activation_function
          UpperCamelCase    :  Optional[int]							=	resid_pdrop
          UpperCamelCase    :  Union[str, Any]							=	embd_pdrop
          UpperCamelCase    :  Optional[Any]							=	attn_pdrop
          UpperCamelCase    :  List[str]							=	layer_norm_epsilon
          UpperCamelCase    :  Union[str, Any]							=	initializer_range
          UpperCamelCase    :  str							=	use_cache

          UpperCamelCase    :  Dict							=	bos_token_id
          UpperCamelCase    :  Union[str, Any]							=	eos_token_id

          super().__init__(
              bos_token_id=SCREAMING_SNAKE_CASE_,			eos_token_id=SCREAMING_SNAKE_CASE_,			tie_word_embeddings=SCREAMING_SNAKE_CASE_,			**SCREAMING_SNAKE_CASE_       )






class 				lowerCAmelCase_		(  a__							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = "default",			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = False,			)     ->		List[str]:
          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?
             UpperCamelCase    :  str							=	0
       @property
       def 					snake_case_       (			self       )     ->		Mapping[str, Mapping[int, str]]:
          UpperCamelCase    :  Tuple							=	OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}       )
          if self.use_past:
             self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_,			direction='inputs'       )
             UpperCamelCase    :  List[Any]							=	{0: 'batch', 1: 'past_sequence + sequence'}
          else:
             UpperCamelCase    :  Optional[int]							=	{0: 'batch', 1: 'sequence'}

          return common_inputs
       @property
       def 					snake_case_       (			self       )     ->		int:
          return self._config.n_layer
       @property
       def 					snake_case_       (			self       )     ->		int:
          return self._config.n_head
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = -1,			SCREAMING_SNAKE_CASE_ = -1,			SCREAMING_SNAKE_CASE_ = False,			SCREAMING_SNAKE_CASE_ = None,			)     ->		Mapping[str, Any]:
          UpperCamelCase    :  Tuple							=	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()
          UpperCamelCase    :  Optional[int]							=	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

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

          UpperCamelCase    :  List[Any]							=	common_inputs['attention_mask']
          if self.use_past:
             UpperCamelCase    :  Optional[Any]							=	ordered_inputs['attention_mask'].dtype
             UpperCamelCase    :  List[Any]							=	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 					snake_case_       (			self       )     ->		int:
          return 13



