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


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

_lowercase		:					List[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        __magic_name__		(       SCREAMING_SNAKE_CASE__):
			UpperCamelCase__							=			'gpt2'
			UpperCamelCase__							=			['past_key_values']
			UpperCamelCase__							=			{
			    'hidden_size': 'n_embd',
			    'max_position_embeddings': 'n_positions',
			    'num_attention_heads': 'n_head',
			    'num_hidden_layers': 'n_layer',
			}







			def __init__(      self							:    List[Any]							,     lowercase_							:    Union[str, Any]=50257							,     lowercase_							:    int=1024							,     lowercase_							:    Optional[int]=768							,     lowercase_							:    int=12							,     lowercase_							:    int=12							,     lowercase_							:    Union[str, Any]=None							,     lowercase_							:    Any="gelu_new"							,     lowercase_							:    Optional[int]=0.1							,     lowercase_							:    Union[str, Any]=0.1							,     lowercase_							:    List[str]=0.1							,     lowercase_							:    Union[str, Any]=1E-5							,     lowercase_							:    Union[str, Any]=0.02							,     lowercase_							:    int="cls_index"							,     lowercase_							:    Optional[Any]=True							,     lowercase_							:    List[Any]=None							,     lowercase_							:    int=True							,     lowercase_							:    str=0.1							,     lowercase_							:    Tuple=True							,     lowercase_							:    Optional[int]=True							,     lowercase_							:    Optional[int]=50256							,     lowercase_							:    List[str]=50256							,     lowercase_							:    Optional[int]=False							,     lowercase_							:    Union[str, Any]=False							,     **lowercase_							:    List[str]							,     ):
										lowercase_   :     List[str]									=			vocab_size
										lowercase_   :     Dict									=			n_positions
										lowercase_   :     Optional[int]									=			n_embd
										lowercase_   :     List[Any]									=			n_layer
										lowercase_   :     str									=			n_head
										lowercase_   :     Tuple									=			n_inner
										lowercase_   :     Optional[int]									=			activation_function
										lowercase_   :     Optional[Any]									=			resid_pdrop
										lowercase_   :     int									=			embd_pdrop
										lowercase_   :     List[str]									=			attn_pdrop
										lowercase_   :     Optional[int]									=			layer_norm_epsilon
										lowercase_   :     Dict									=			initializer_range
										lowercase_   :     Optional[int]									=			summary_type
										lowercase_   :     Tuple									=			summary_use_proj
										lowercase_   :     Optional[int]									=			summary_activation
										lowercase_   :     Optional[int]									=			summary_first_dropout
										lowercase_   :     Optional[int]									=			summary_proj_to_labels
										lowercase_   :     List[Any]									=			scale_attn_weights
										lowercase_   :     Tuple									=			use_cache
										lowercase_   :     Dict									=			scale_attn_by_inverse_layer_idx
										lowercase_   :     Union[str, Any]									=			reorder_and_upcast_attn

										lowercase_   :     Optional[Any]									=			bos_token_id
										lowercase_   :     List[str]									=			eos_token_id

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





class        __magic_name__		(       SCREAMING_SNAKE_CASE__):







			def __init__(      self							:    str							,     lowercase_							:    PretrainedConfig							,     lowercase_							:    str = "default"							,     lowercase_							:    List[PatchingSpec] = None							,     lowercase_							:    bool = False							,     ):
										super().__init__(a_							,     task=a_							,     patching_specs=a_							,     use_past=a_       )
										if not getattr(self._config							,     """pad_token_id"""							,     a_       ):
																	# TODO: how to do that better?
																	lowercase_   :     Optional[Any]									=			0







			@property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Dict       ):
										lowercase_   :     str									=			OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}       )
										if self.use_past:
																	self.fill_with_past_key_values_(a_							,     direction="""inputs"""       )
																	lowercase_   :     Any									=			{0: """batch""", 1: """past_sequence + sequence"""}
										else:
																	lowercase_   :     str									=			{0: """batch""", 1: """sequence"""}

										return common_inputs







			@property
			def       SCREAMING_SNAKE_CASE_	(      self							:    int       ):
										return self._config.n_layer







			@property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Dict       ):
										return self._config.n_head







			def       SCREAMING_SNAKE_CASE_	(      self							:    int							,     lowercase_							:    PreTrainedTokenizer							,     lowercase_							:    int = -1							,     lowercase_							:    int = -1							,     lowercase_							:    bool = False							,     lowercase_							:    Optional[TensorType] = None							,     ):
										lowercase_   :     List[str]									=			super(a_							,     self       ).generate_dummy_inputs(
										    a_							,     batch_size=a_							,     seq_length=a_							,     is_pair=a_							,     framework=a_       )

										# We need to order the input in the way they appears in the forward()
										lowercase_   :     Dict									=			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

																								lowercase_		,		lowercase_   :     Dict									=			common_inputs["""input_ids"""].shape
																								# Not using the same length for past_key_values
																								lowercase_   :     Optional[int]									=			seqlen + 2
																								lowercase_   :     Union[str, Any]									=			(
																								    batch,
																								    self.num_attention_heads,
																								    past_key_values_length,
																								    self._config.hidden_size // self.num_attention_heads,
																								)
																								lowercase_   :     Optional[Any]									=			[
																								    (torch.zeros(a_       ), torch.zeros(a_       )) for _ in range(self.num_layers       )
																								]

										lowercase_   :     Union[str, Any]									=			common_inputs["""attention_mask"""]
										if self.use_past:
																	lowercase_   :     int									=			ordered_inputs["""attention_mask"""].dtype
																	lowercase_   :     List[Any]									=			torch.cat(
																	    [ordered_inputs["""attention_mask"""], torch.ones(a_							,     a_							,     dtype=a_       )]							,     dim=1       )

										return ordered_inputs







			@property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Optional[Any]       ):
										return 13









'''simple docstring'''

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import OwlViTImageProcessor







class 			UpperCAmelCase			(							unittest.TestCase):

 def __init__(			self			:						Optional[Any],       a_			:						Optional[int],       a_			:						Dict=7,       a_			:						List[str]=3,       a_			:						int=18,       a_			:						Tuple=30,       a_			:						Any=400,       a_			:						Optional[int]=True,       a_			:						Optional[int]=None,       a_			:						Any=True,       a_			:						Optional[int]=None,       a_			:						int=True,       a_			:						Optional[int]=[0.48_145_466, 0.4_578_275, 0.40_821_073],       a_			:						Optional[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711],       a_			:						Optional[int]=True,       ):





    """simple docstring"""



    UpperCamelCase__			    =    parent
    UpperCamelCase__			    =    batch_size
    UpperCamelCase__			    =    num_channels
    UpperCamelCase__			    =    image_size
    UpperCamelCase__			    =    min_resolution
    UpperCamelCase__			    =    max_resolution
    UpperCamelCase__			    =    do_resize
    UpperCamelCase__			    =    size if size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_center_crop
    UpperCamelCase__			    =    crop_size if crop_size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_normalize
    UpperCamelCase__			    =    image_mean
    UpperCamelCase__			    =    image_std
    UpperCamelCase__			    =    do_convert_rgb

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    return {
        "do_resize": self.do_resize,
        "size": self.size,
        "do_center_crop": self.do_center_crop,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_convert_rgb": self.do_convert_rgb,
    }







@require_torch
@require_vision
class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       Tuple            =       OwlViTImageProcessor if is_vision_available() else None

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    OwlViTImageProcessingTester(self       )

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    return self.image_processor_tester.prepare_image_processor_dict()

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    self.assertTrue(hasattr(a_,       "do_resize"       )       )
    self.assertTrue(hasattr(a_,       "size"       )       )
    self.assertTrue(hasattr(a_,       "do_center_crop"       )       )
    self.assertTrue(hasattr(a_,       "center_crop"       )       )
    self.assertTrue(hasattr(a_,       "do_normalize"       )       )
    self.assertTrue(hasattr(a_,       "image_mean"       )       )
    self.assertTrue(hasattr(a_,       "image_std"       )       )
    self.assertTrue(hasattr(a_,       "do_convert_rgb"       )       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict       )
    self.assertEqual(image_processor.size,       {"height": 18, "width": 18}       )
    self.assertEqual(image_processor.crop_size,       {"height": 18, "width": 18}       )

    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict,       size=42,       crop_size=84       )
    self.assertEqual(image_processor.size,       {"height": 42, "width": 42}       )
    self.assertEqual(image_processor.crop_size,       {"height": 84, "width": 84}       )

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PIL images
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_       )

    for image in image_inputs:
       self.assertIsInstance(a_,       Image.Image       )

    # Test not batched input
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random numpy tensors
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_,       numpify=a_       )
    for image in image_inputs:
       self.assertIsInstance(a_,       np.ndarray       )

    # Test not batched input
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PyTorch tensors
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_,       torchify=a_       )
    for image in image_inputs:
       self.assertIsInstance(a_,       torch.Tensor       )

    # Test not batched input
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )