
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFResNetForImageClassification, TFResNetModel
						from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor





class   UpperCamelCase_      :







						'''simple docstring'''



						def __init__(			self							:str		,    lowerCAmelCase__							:List[Any]		,    lowerCAmelCase__							:List[Any]=3		,    lowerCAmelCase__							:Any=32		,    lowerCAmelCase__							:Union[str, Any]=3		,    lowerCAmelCase__							:List[str]=10		,    lowerCAmelCase__							:Optional[int]=[10, 20, 30, 40]		,    lowerCAmelCase__							:int=[1, 1, 2, 1]		,    lowerCAmelCase__							:List[Any]=True		,    lowerCAmelCase__							:Optional[Any]=True		,    lowerCAmelCase__							:Tuple="relu"		,    lowerCAmelCase__							:Any=3		,    lowerCAmelCase__							:List[Any]=None		,    )  ->str:
										lowercase         =      parent
										lowercase         =      batch_size
										lowercase         =      image_size
										lowercase         =      num_channels
										lowercase         =      embeddings_size
										lowercase         =      hidden_sizes
										lowercase         =      depths
										lowercase         =      is_training
										lowercase         =      use_labels
										lowercase         =      hidden_act
										lowercase         =      num_labels
										lowercase         =      scope
										lowercase         =      len(SCREAMING_SNAKE_CASE_     )





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Optional[Any]:
										lowercase         =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

										lowercase         =      None
										if self.use_labels:
														lowercase         =      ids_tensor([self.batch_size]		,    self.num_labels     )

										lowercase         =      self.get_config()

										return config, pixel_values, labels





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Optional[Any]:
										return ResNetConfig(
										    num_channels=self.num_channels		,    embeddings_size=self.embeddings_size		,    hidden_sizes=self.hidden_sizes		,    depths=self.depths		,    hidden_act=self.hidden_act		,    num_labels=self.num_labels		,    image_size=self.image_size		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Tuple		,    lowerCAmelCase__							:Any		,    lowerCAmelCase__							:List[str]		,    lowerCAmelCase__							:int     )  ->List[str]:
										lowercase         =      TFResNetModel(config=SCREAMING_SNAKE_CASE_     )
										lowercase         =      model(SCREAMING_SNAKE_CASE_     )
										# expected last hidden states: B, C, H // 32, W // 32
										self.parent.assertEqual(
										    result.last_hidden_state.shape		,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:int     )  ->str:
										lowercase         =      self.num_labels
										lowercase         =      TFResNetForImageClassification(SCREAMING_SNAKE_CASE_     )
										lowercase         =      model(SCREAMING_SNAKE_CASE_		,    labels=SCREAMING_SNAKE_CASE_     )
										self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.num_labels)     )





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->str:
										lowercase         =      self.prepare_config_and_inputs()
										lowercase         =      config_and_inputs
										lowercase         =      {"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_tf
class   UpperCamelCase_      (      UpperCAmelCase_		,    UpperCAmelCase_		,    unittest.TestCase		):







						'''simple docstring'''



						UpperCamelCase      :  Any				   =					(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
						UpperCamelCase      :  Optional[Any]				   =					(
						    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

						UpperCamelCase      :  Optional[Any]				   =					False
						UpperCamelCase      :  Optional[Any]				   =					False
						UpperCamelCase      :  List[str]				   =					False
						UpperCamelCase      :  str				   =					False
						UpperCamelCase      :  List[Any]				   =					False





						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->Optional[int]:
										lowercase         =      TFResNetModelTester(self     )
										lowercase         =      ConfigTester(self		,    config_class=SCREAMING_SNAKE_CASE_		,    has_text_modality=SCREAMING_SNAKE_CASE_     )





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->int:
										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()





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





						@unittest.skip(reason="ResNet does not use inputs_embeds"     )
						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->str:
										pass





						@unittest.skip(reason="ResNet does not support input and output embeddings"     )
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->str:
										pass





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->List[Any]:
										lowercase         =      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														lowercase         =      model_class(SCREAMING_SNAKE_CASE_     )
														lowercase         =      inspect.signature(model.call     )
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														lowercase         =      [*signature.parameters.keys()]

														lowercase         =      ["""pixel_values"""]
														self.assertListEqual(arg_names[:1]		,    SCREAMING_SNAKE_CASE_     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Tuple:
										lowercase         =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_     )





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Tuple:




										def check_hidden_states_output(lowerCAmelCase__							:Dict		,    lowerCAmelCase__							:List[Any]		,    lowerCAmelCase__							:Optional[int]     ):
														lowercase         =      model_class(SCREAMING_SNAKE_CASE_     )
														lowercase         =      model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_     )     )

														lowercase         =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

														lowercase         =      self.model_tester.num_stages
														self.assertEqual(len(SCREAMING_SNAKE_CASE_     )		,    expected_num_stages + 1     )

														# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
														self.assertListEqual(
														    list(hidden_states[0].shape[-2:]     )		,    [self.model_tester.image_size // 4, self.model_tester.image_size // 4]		,    )

										lowercase         =      self.model_tester.prepare_config_and_inputs_for_common()
										lowercase         =      ["""basic""", """bottleneck"""]
										for model_class in self.all_model_classes:
														for layer_type in layers_type:
																		lowercase         =      layer_type
																		lowercase         =      True
																		check_hidden_states_output(SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_     )

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		lowercase         =      True

																		check_hidden_states_output(SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Any:
										lowercase         =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_     )





						@slow
						def        SCREAMING_SNAKE_CASE(			self							:int     )  ->List[Any]:




										for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowercase         =      TFResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_     )
														self.assertIsNotNone(SCREAMING_SNAKE_CASE_     )




def  __snake_case							(	):







				'''simple docstring'''


				lowercase         =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
				return image





@require_tf
@require_vision
class   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						@cached_property
						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->Optional[Any]:
										return (
										    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
										    if is_vision_available()
										    else None
										)





						@slow
						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->Tuple:
										lowercase         =      TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

										lowercase         =      self.default_image_processor
										lowercase         =      prepare_img()
										lowercase         =      image_processor(images=SCREAMING_SNAKE_CASE_		,    return_tensors="tf"     )

										# forward pass
										lowercase         =      model(**SCREAMING_SNAKE_CASE_     )

										# verify the logits
										lowercase         =      tf.TensorShape((1, 1000)     )
										self.assertEqual(outputs.logits.shape		,    SCREAMING_SNAKE_CASE_     )

										lowercase         =      tf.constant([-11.1069, -9.78_77, -8.37_77]     )

										self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()		,    SCREAMING_SNAKE_CASE_		,    atol=1E-4     )     )


from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


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

lowerCamelCase__     :		Union[str, Any]        = {
    """YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json""",
    """YituTech/conv-bert-medium-small""": (
        """https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json"""
    ),
    """YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json""",
    # See all ConvBERT models at https://huggingface.co/models?filter=convbert
}



class    _snake_case (						UpperCAmelCase_				):
 __lowerCAmelCase	:  Union[str, Any]	   =      'convbert'


 def __init__(       self       ,	SCREAMING_SNAKE_CASE_=3_05_22       ,	SCREAMING_SNAKE_CASE_=7_68       ,	SCREAMING_SNAKE_CASE_=12       ,	SCREAMING_SNAKE_CASE_=12       ,	SCREAMING_SNAKE_CASE_=30_72       ,	SCREAMING_SNAKE_CASE_="gelu"       ,	SCREAMING_SNAKE_CASE_=0.1       ,	SCREAMING_SNAKE_CASE_=0.1       ,	SCREAMING_SNAKE_CASE_=5_12       ,	SCREAMING_SNAKE_CASE_=2       ,	SCREAMING_SNAKE_CASE_=0.0_2       ,	SCREAMING_SNAKE_CASE_=1E-12       ,	SCREAMING_SNAKE_CASE_=1       ,	SCREAMING_SNAKE_CASE_=0       ,	SCREAMING_SNAKE_CASE_=2       ,	SCREAMING_SNAKE_CASE_=7_68       ,	SCREAMING_SNAKE_CASE_=2       ,	SCREAMING_SNAKE_CASE_=9       ,	SCREAMING_SNAKE_CASE_=1       ,	SCREAMING_SNAKE_CASE_=None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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

   lowercase__	: Dict     		=   vocab_size
   lowercase__	: List[Any]     		=   hidden_size
   lowercase__	: Optional[Any]     		=   num_hidden_layers
   lowercase__	: Union[str, Any]     		=   num_attention_heads
   lowercase__	: List[str]     		=   intermediate_size
   lowercase__	: Optional[int]     		=   hidden_act
   lowercase__	: Tuple     		=   hidden_dropout_prob
   lowercase__	: List[str]     		=   attention_probs_dropout_prob
   lowercase__	: Tuple     		=   max_position_embeddings
   lowercase__	: Dict     		=   type_vocab_size
   lowercase__	: Union[str, Any]     		=   initializer_range
   lowercase__	: Dict     		=   layer_norm_eps
   lowercase__	: Tuple     		=   embedding_size
   lowercase__	: List[str]     		=   head_ratio
   lowercase__	: Dict     		=   conv_kernel_size
   lowercase__	: Dict     		=   num_groups
   lowercase__	: int     		=   classifier_dropout



class    _snake_case (						UpperCAmelCase_				):


 @property
 def   lowercase__  (       self):


   '''simple docstring'''




   if self.task == "multiple-choice":
     lowercase__	: Union[str, Any]     		=   {0: """batch""", 1: """choice""", 2: """sequence"""}
   else:
     lowercase__	: str     		=   {0: """batch""", 1: """sequence"""}
   return OrderedDict(
       [
           ("""input_ids""", dynamic_axis),
           ("""attention_mask""", dynamic_axis),
           ("""token_type_ids""", dynamic_axis),
       ])






