
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    _snake_case :


 def __init__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=3       ,	SCREAMING_SNAKE_CASE_=32       ,	SCREAMING_SNAKE_CASE_=3       ,	SCREAMING_SNAKE_CASE_=10       ,	SCREAMING_SNAKE_CASE_=[10, 20, 30, 40]       ,	SCREAMING_SNAKE_CASE_=[1, 1, 2, 1]       ,	SCREAMING_SNAKE_CASE_=True       ,	SCREAMING_SNAKE_CASE_=True       ,	SCREAMING_SNAKE_CASE_="relu"       ,	SCREAMING_SNAKE_CASE_=3       ,	SCREAMING_SNAKE_CASE_=None       ,	):


   '''simple docstring'''




   lowercase__	: Any     		=   parent
   lowercase__	: Any     		=   batch_size
   lowercase__	: Dict     		=   image_size
   lowercase__	: Union[str, Any]     		=   num_channels
   lowercase__	: Optional[Any]     		=   embeddings_size
   lowercase__	: Optional[Any]     		=   hidden_sizes
   lowercase__	: Any     		=   depths
   lowercase__	: Optional[int]     		=   is_training
   lowercase__	: Optional[int]     		=   use_labels
   lowercase__	: Optional[int]     		=   hidden_act
   lowercase__	: Dict     		=   num_labels
   lowercase__	: str     		=   scope
   lowercase__	: Optional[int]     		=   len(SCREAMING_SNAKE_CASE_)


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Tuple     		=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowercase__	: Union[str, Any]     		=   None
   if self.use_labels:
     lowercase__	: Any     		=   ids_tensor([self.batch_size]       ,	self.num_labels)

   lowercase__	: str     		=   self.get_config()

   return config, pixel_values, labels


 def   lowercase__  (       self):


   '''simple docstring'''




   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   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   TFResNetModel(config=SCREAMING_SNAKE_CASE_)
   lowercase__	: int     		=   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   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   self.num_labels
   lowercase__	: List[Any]     		=   TFResNetForImageClassification(SCREAMING_SNAKE_CASE_)
   lowercase__	: int     		=   model(SCREAMING_SNAKE_CASE_       ,	labels=SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels))



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Tuple     		=   self.prepare_config_and_inputs()
   lowercase__		,     lowercase__		,     lowercase__	: Union[str, Any]     		=   config_and_inputs
   lowercase__	: List[str]     		=   {"""pixel_values""": pixel_values}
   return config, inputs_dict



@require_tf
class    _snake_case (						UpperCAmelCase_	,    UpperCAmelCase_	,    unittest.TestCase				):
 __lowerCAmelCase	:  Any	   =      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 __lowerCAmelCase	:  Optional[Any]	   =      (
     {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

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


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Tuple     		=   TFResNetModelTester(self)
   lowercase__	: str     		=   ConfigTester(self       ,	config_class=SCREAMING_SNAKE_CASE_       ,	has_text_modality=SCREAMING_SNAKE_CASE_)


 def   lowercase__  (       self):


   '''simple docstring'''




   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   lowercase__  (       self):


   '''simple docstring'''




   return


 @unittest.skip(reason="""ResNet does not use inputs_embeds""")
 def   lowercase__  (       self):


   '''simple docstring'''




   pass


 @unittest.skip(reason="""ResNet does not support input and output embeddings""")
 def   lowercase__  (       self):


   '''simple docstring'''




   pass


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__		,     lowercase__	: Union[str, Any]     		=   self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     lowercase__	: Union[str, Any]     		=   model_class(SCREAMING_SNAKE_CASE_)
     lowercase__	: Tuple     		=   inspect.signature(model.call)
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     lowercase__	: List[Any]     		=   [*signature.parameters.keys()]

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


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[str]     		=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_)


 def   lowercase__  (       self):


   '''simple docstring'''




   def check_hidden_states_output(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):
     lowercase__	: int     		=   model_class(SCREAMING_SNAKE_CASE_)
     lowercase__	: Dict     		=   model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_))

     lowercase__	: Union[str, Any]     		=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     lowercase__	: Optional[Any]     		=   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__		,     lowercase__	: Tuple     		=   self.model_tester.prepare_config_and_inputs_for_common()
   lowercase__	: int     		=   ["""basic""", """bottleneck"""]
   for model_class in self.all_model_classes:
     for layer_type in layers_type:
       lowercase__	: Any     		=   layer_type
       lowercase__	: str     		=   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__	: Dict     		=   True

       check_hidden_states_output(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_)


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[Any]     		=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_)



 @slow
 def   lowercase__  (       self):


   '''simple docstring'''




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

def 		UpperCamelCase						(   )		->						Dict:


  '''simple docstring'''






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



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


 @cached_property
 def   lowercase__  (       self):


   '''simple docstring'''




   return (
       AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
       if is_vision_available()
       else None
   )



 @slow
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

   lowercase__	: Any     		=   self.default_image_processor
   lowercase__	: Any     		=   prepare_img()
   lowercase__	: List[str]     		=   image_processor(images=SCREAMING_SNAKE_CASE_       ,	return_tensors="""tf""")

   # forward pass
   lowercase__	: List[Any]     		=   model(**SCREAMING_SNAKE_CASE_)

   # verify the logits
   lowercase__	: List[str]     		=   tf.TensorShape((1, 10_00))
   self.assertEqual(outputs.logits.shape       ,	SCREAMING_SNAKE_CASE_)

   lowercase__	: Optional[Any]     		=   tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7])

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






