


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

 def __init__(			self			:						List[Any],       a_			:						Union[str, Any]=5_0257,       a_			:						int=1024,       a_			:						Optional[int]=768,       a_			:						int=12,       a_			:						int=12,       a_			:						Union[str, Any]=None,       a_			:						Any="gelu_new",       a_			:						Optional[int]=0.1,       a_			:						Union[str, Any]=0.1,       a_			:						List[str]=0.1,       a_			:						Union[str, Any]=1e-5,       a_			:						Union[str, Any]=0.02,       a_			:						int="cls_index",       a_			:						Optional[Any]=True,       a_			:						List[Any]=None,       a_			:						int=True,       a_			:						str=0.1,       a_			:						Tuple=True,       a_			:						Optional[int]=True,       a_			:						Optional[int]=5_0256,       a_			:						List[str]=5_0256,       a_			:						Optional[int]=False,       a_			:						Union[str, Any]=False,       **a_			:						List[str],       ):





    """simple docstring"""



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

    UpperCamelCase__			    =    bos_token_id
    UpperCamelCase__			    =    eos_token_id

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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def __init__(			self			:						str,       a_			:						PretrainedConfig,       a_			:						str = "default",       a_			:						List[PatchingSpec] = None,       a_			:						bool = False,       ):





    """simple docstring"""



    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?
       UpperCamelCase__			    =    0

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    UpperCamelCase__			    =    OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}       )
    if self.use_past:
       self.fill_with_past_key_values_(a_,       direction="inputs"       )
       UpperCamelCase__			    =    {0: "batch", 1: "past_sequence + sequence"}
    else:
       UpperCamelCase__			    =    {0: "batch", 1: "sequence"}

    return common_inputs

 @property
 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    return self._config.n_layer

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    return self._config.n_head

 def 		lowercase_    (			self			:						int,       a_			:						PreTrainedTokenizer,       a_			:						int = -1,       a_			:						int = -1,       a_			:						bool = False,       a_			:						Optional[TensorType] = None,       ):





    """simple docstring"""



    UpperCamelCase__			    =    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()
    UpperCamelCase__			    =    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__			    =    common_inputs["input_ids"].shape
          # Not using the same length for past_key_values
          UpperCamelCase__			    =    seqlen + 2
          UpperCamelCase__			    =    (
              batch,
              self.num_attention_heads,
              past_key_values_length,
              self._config.hidden_size // self.num_attention_heads,
          )
          UpperCamelCase__			    =    [
              (torch.zeros(a_       ), torch.zeros(a_       )) for _ in range(self.num_layers       )
          ]

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

    return ordered_inputs

 @property
 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



    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"],
        ),       )