

"""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  :					Union[str, Any]												= logging.get_logger(__name__)

__A  :					List[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     __UpperCamelCase				(     _A		):
		SCREAMING_SNAKE_CASE              =					"gpt2"
		SCREAMING_SNAKE_CASE              =					["past_key_values"]
		SCREAMING_SNAKE_CASE              =					{
		    "hidden_size": "n_embd",
		    "max_position_embeddings": "n_positions",
		    "num_attention_heads": "n_head",
		    "num_hidden_layers": "n_layer",
		}


		def __init__(self				:	str  ,  __SCREAMING_SNAKE_CASE				:	Any=5_0_2_5_7  ,  __SCREAMING_SNAKE_CASE				:	Dict=1_0_2_4  ,  __SCREAMING_SNAKE_CASE				:	int=7_6_8  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]=1_2  ,  __SCREAMING_SNAKE_CASE				:	List[Any]=1_2  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]=None  ,  __SCREAMING_SNAKE_CASE				:	Tuple="gelu_new"  ,  __SCREAMING_SNAKE_CASE				:	str=0.1  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]=0.1  ,  __SCREAMING_SNAKE_CASE				:	List[str]=0.1  ,  __SCREAMING_SNAKE_CASE				:	Dict=1E-5  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]=0.0_2  ,  __SCREAMING_SNAKE_CASE				:	Optional[int]="cls_index"  ,  __SCREAMING_SNAKE_CASE				:	List[Any]=True  ,  __SCREAMING_SNAKE_CASE				:	List[Any]=None  ,  __SCREAMING_SNAKE_CASE				:	int=True  ,  __SCREAMING_SNAKE_CASE				:	str=0.1  ,  __SCREAMING_SNAKE_CASE				:	Any=True  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]=True  ,  __SCREAMING_SNAKE_CASE				:	str=5_0_2_5_6  ,  __SCREAMING_SNAKE_CASE				:	List[Any]=5_0_2_5_6  ,  __SCREAMING_SNAKE_CASE				:	Any=False  ,  __SCREAMING_SNAKE_CASE				:	Optional[Any]=False  ,  **__SCREAMING_SNAKE_CASE				:	Dict  ,  ):
							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     __UpperCamelCase				(     _A		):


		def __init__(self				:	Any  ,  __SCREAMING_SNAKE_CASE				:	str  ,  __SCREAMING_SNAKE_CASE				:	int = "default"  ,  __SCREAMING_SNAKE_CASE				:	str = None  ,  __SCREAMING_SNAKE_CASE				:	Tuple = False  ,  ):
							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       SCREAMING_SNAKE_CASE__     (self				:	str):
							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       SCREAMING_SNAKE_CASE__     (self				:	Union[str, Any]):
							return self._config.n_layer


		@property
		def       SCREAMING_SNAKE_CASE__     (self				:	Any):
							return self._config.n_head


		def       SCREAMING_SNAKE_CASE__     (self				:	Tuple  ,  __SCREAMING_SNAKE_CASE				:	Any  ,  __SCREAMING_SNAKE_CASE				:	List[Any] = -1  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any] = -1  ,  __SCREAMING_SNAKE_CASE				:	int = False  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any] = None  ,  ):
							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    =      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       SCREAMING_SNAKE_CASE__     (self				:	str):
							return 1_3








"""simple docstring"""




import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
	from PIL import Image
else:





	class     __UpperCamelCase				:


			@staticmethod
			def       SCREAMING_SNAKE_CASE__     (*__SCREAMING_SNAKE_CASE				:	Optional[Any]  ,  **__SCREAMING_SNAKE_CASE				:	Any):
								pass





@is_pipeline_test
@require_torch_or_tf
@require_vision
class     __UpperCamelCase				(     unittest.TestCase		):
		SCREAMING_SNAKE_CASE              =					MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
		SCREAMING_SNAKE_CASE              =					TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING


		def       SCREAMING_SNAKE_CASE__     (self				:	Any  ,  __SCREAMING_SNAKE_CASE				:	List[str]  ,  __SCREAMING_SNAKE_CASE				:	Union[str, Any]  ,  __SCREAMING_SNAKE_CASE				:	Tuple):
							A    =      ImageClassificationPipeline(model=__SCREAMING_SNAKE_CASE  ,  image_processor=__SCREAMING_SNAKE_CASE  ,  top_k=2)
							A    =      [
							    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
							    "http://images.cocodataset.org/val2017/000000039769.jpg",
							]
							return image_classifier, examples


		def       SCREAMING_SNAKE_CASE__     (self				:	Any  ,  __SCREAMING_SNAKE_CASE				:	Optional[int]  ,  __SCREAMING_SNAKE_CASE				:	Dict):
							A    =      image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png")

							self.assertEqual(
							    __SCREAMING_SNAKE_CASE  ,  [
							        {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							    ]  ,  )

							import datasets

							A    =      datasets.load_dataset("hf-internal-testing/fixtures_image_utils"  ,  "image"  ,  split="test")

							# Accepts URL + PIL.Image + lists
							A    =      image_classifier(
							    [
							        Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        # RGBA
							        dataset[0]["file"],
							        # LA
							        dataset[1]["file"],
							        # L
							        dataset[2]["file"],
							    ])
							self.assertEqual(
							    __SCREAMING_SNAKE_CASE  ,  [
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							    ]  ,  )


		@require_torch
		def       SCREAMING_SNAKE_CASE__     (self				:	str):
							A    =      "hf-internal-testing/tiny-random-vit"
							A    =      pipeline("image-classification"  ,  model=__SCREAMING_SNAKE_CASE)

							A    =      image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]  ,  )

							A    =      image_classifier(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]  ,  top_k=2  ,  )
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							    ]  ,  )


		@require_tf
		def       SCREAMING_SNAKE_CASE__     (self				:	List[str]):
							A    =      "hf-internal-testing/tiny-random-vit"
							A    =      pipeline("image-classification"  ,  model=__SCREAMING_SNAKE_CASE  ,  framework="tf")

							A    =      image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]  ,  )

							A    =      image_classifier(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]  ,  top_k=2  ,  )
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							    ]  ,  )


		def       SCREAMING_SNAKE_CASE__     (self				:	Union[str, Any]):
							A    =      PreTrainedTokenizer()

							# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
							A    =      pipeline(
							    "image-classification"  ,  model="hf-internal-testing/tiny-random-vit"  ,  tokenizer=__SCREAMING_SNAKE_CASE)

							self.assertIs(image_classifier.tokenizer  ,  __SCREAMING_SNAKE_CASE)


		@slow
		@require_torch
		def       SCREAMING_SNAKE_CASE__     (self				:	List[Any]):
							# Perceiver is not tested by `run_pipeline_test` properly.
							# That is because the type of feature_extractor and model preprocessor need to be kept
							# in sync, which is not the case in the current design
							A    =      pipeline("image-classification"  ,  model="deepmind/vision-perceiver-conv")
							A    =      image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [
							        {"score": 0.4_3_8_5, "label": "tabby, tabby cat"},
							        {"score": 0.3_2_1, "label": "tiger cat"},
							        {"score": 0.0_5_0_2, "label": "Egyptian cat"},
							        {"score": 0.0_1_3_7, "label": "crib, cot"},
							        {"score": 0.0_0_7, "label": "radiator"},
							    ]  ,  )

							A    =      pipeline("image-classification"  ,  model="deepmind/vision-perceiver-fourier")
							A    =      image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [
							        {"score": 0.5_6_5_8, "label": "tabby, tabby cat"},
							        {"score": 0.1_3_0_9, "label": "tiger cat"},
							        {"score": 0.0_7_2_2, "label": "Egyptian cat"},
							        {"score": 0.0_7_0_7, "label": "remote control, remote"},
							        {"score": 0.0_0_8_2, "label": "computer keyboard, keypad"},
							    ]  ,  )

							A    =      pipeline("image-classification"  ,  model="deepmind/vision-perceiver-learned")
							A    =      image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE  ,  decimals=4)  ,  [
							        {"score": 0.3_0_2_2, "label": "tabby, tabby cat"},
							        {"score": 0.2_3_6_2, "label": "Egyptian cat"},
							        {"score": 0.1_8_5_6, "label": "tiger cat"},
							        {"score": 0.0_3_2_4, "label": "remote control, remote"},
							        {"score": 0.0_0_9_6, "label": "quilt, comforter, comfort, puff"},
							    ]  ,  )





