


'''simple docstring'''




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 					a			:
 '''simple docstring'''




 def __init__(    self		,      lowerCamelCase_		,      lowerCamelCase_=3		,      lowerCamelCase_=3_2		,      lowerCamelCase_=3		,      lowerCamelCase_=1_0		,      lowerCamelCase_=[1_0, 2_0, 3_0, 4_0]		,      lowerCamelCase_=[1, 1, 2, 1]		,      lowerCamelCase_=True		,      lowerCamelCase_=True		,      lowerCamelCase_="relu"		,      lowerCamelCase_=3		,      lowerCamelCase_=None		,      )      ->    int:
    _a					:  Tuple						=  parent
    _a					:  int						=  batch_size
    _a					:  List[str]						=  image_size
    _a					:  List[Any]						=  num_channels
    _a					:  int						=  embeddings_size
    _a					:  List[Any]						=  hidden_sizes
    _a					:  int						=  depths
    _a					:  Tuple						=  is_training
    _a					:  str						=  use_labels
    _a					:  Optional[Any]						=  hidden_act
    _a					:  int						=  num_labels
    _a					:  str						=  scope
    _a					:  Any						=  len(lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    List[Any]:
    _a					:  Dict						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

    _a					:  Optional[int]						=  None
    if self.use_labels:
       _a					:  Dict						=  ids_tensor([self.batch_size]		,      self.num_labels      )

    _a					:  Dict						=  self.get_config()

    return config, pixel_values, labels




 def   __UpperCamelCase   (    self      )      ->    str:
    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   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Any:
    _a					:  Any						=  TFResNetModel(config=lowerCamelCase_      )
    _a					:  Tuple						=  model(lowerCamelCase_      )
    # 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 // 3_2, self.image_size // 3_2)		,      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    str:
    _a					:  int						=  self.num_labels
    _a					:  Optional[int]						=  TFResNetForImageClassification(lowerCamelCase_      )
    _a					:  Tuple						=  model(lowerCamelCase_		,      labels=lowerCamelCase_      )
    self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)      )




 def   __UpperCamelCase   (    self      )      ->    Optional[int]:
    _a					:  Dict						=  self.prepare_config_and_inputs()
    _a		,						_a		,						_a					:  List[Any]						=  config_and_inputs
    _a					:  Dict						=  {'pixel_values': pixel_values}
    return config, inputs_dict







@require_tf
class 					a			(				snake_case__			,							snake_case__			,							unittest.TestCase  ):
 '''simple docstring'''




 __lowerCAmelCase						: List[str]							  =		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 __lowerCAmelCase						: str							  =		(
     {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 __lowerCAmelCase						: Dict							  =		False
 __lowerCAmelCase						: Union[str, Any]							  =		False
 __lowerCAmelCase						: List[Any]							  =		False
 __lowerCAmelCase						: Any							  =		False
 __lowerCAmelCase						: Optional[int]							  =		False




 def   __UpperCamelCase   (    self      )      ->    Union[str, Any]:
    _a					:  List[str]						=  TFResNetModelTester(self      )
    _a					:  List[str]						=  ConfigTester(self		,      config_class=lowerCamelCase_		,      has_text_modality=lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    List[str]:
    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   __UpperCamelCase   (    self      )      ->    Optional[int]:
    return




 @unittest.skip(reason='ResNet does not use inputs_embeds'      )
 def   __UpperCamelCase   (    self      )      ->    Dict:
    pass




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




 def   __UpperCamelCase   (    self      )      ->    Any:
    _a		,						_a					:  Dict						=  self.model_tester.prepare_config_and_inputs_for_common()

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

       _a					:  Dict						=  ['pixel_values']
       self.assertListEqual(arg_names[:1]		,      lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Optional[int]:
    _a					:  str						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    str:
    def check_hidden_states_output(lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      ):
       _a					:  Optional[Any]						=  model_class(lowerCamelCase_      )
       _a					:  Optional[Any]						=  model(**self._prepare_for_class(lowerCamelCase_		,      lowerCamelCase_      )      )

       _a					:  int						=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

       _a					:  int						=  self.model_tester.num_stages
       self.assertEqual(len(lowerCamelCase_      )		,      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]		,      )

    _a		,						_a					:  str						=  self.model_tester.prepare_config_and_inputs_for_common()
    _a					:  Union[str, Any]						=  ['basic', 'bottleneck']
    for model_class in self.all_model_classes:
       for layer_type in layers_type:
          _a					:  List[str]						=  layer_type
          _a					:  Dict						=  True
          check_hidden_states_output(lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          _a					:  Union[str, Any]						=  True

          check_hidden_states_output(lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    str:
    _a					:  List[str]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_      )




 @slow
 def   __UpperCamelCase   (    self      )      ->    int:
    for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _a					:  Tuple						=  TFResNetModel.from_pretrained(lowerCamelCase_      )
       self.assertIsNotNone(lowerCamelCase_      )





def    UpperCAmelCase_  (       ):
   '''simple docstring'''





   _a					:  int						=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
   return image







@require_tf
@require_vision
class 					a			(				unittest.TestCase  ):
 '''simple docstring'''




 @cached_property
 def   __UpperCamelCase   (    self      )      ->    List[str]:
    return (
        AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )
        if is_vision_available()
        else None
    )




 @slow
 def   __UpperCamelCase   (    self      )      ->    List[str]:
    _a					:  str						=  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

    _a					:  str						=  self.default_image_processor
    _a					:  Tuple						=  prepare_img()
    _a					:  int						=  image_processor(images=lowerCamelCase_		,      return_tensors='tf'      )

    # forward pass
    _a					:  Dict						=  model(**lowerCamelCase_      )

    # verify the logits
    _a					:  Optional[Any]						=  tf.TensorShape((1, 1_0_0_0)      )
    self.assertEqual(outputs.logits.shape		,      lowerCamelCase_      )

    _a					:  Tuple						=  tf.constant([-11.1069, -9.7877, -8.3777]      )

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






'''simple docstring'''




from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_      :		Dict          =		logging.get_logger(__name__)

UpperCAmelCase_      :		List[str]          =		{
    "uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json",
    "uclanlp/visualbert-vqa-pre": "https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json",
    "uclanlp/visualbert-vqa-coco-pre": (
        "https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json"
    ),
    "uclanlp/visualbert-vcr": "https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json",
    "uclanlp/visualbert-vcr-pre": "https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json",
    "uclanlp/visualbert-vcr-coco-pre": (
        "https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json"
    ),
    "uclanlp/visualbert-nlvr2": "https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json",
    "uclanlp/visualbert-nlvr2-pre": "https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json",
    "uclanlp/visualbert-nlvr2-coco-pre": (
        "https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json"
    )
    # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert
}







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: int							  =		"""visual_bert"""




 def __init__(    self		,      lowerCamelCase_=3_0_5_2_2		,      lowerCamelCase_=7_6_8		,      lowerCamelCase_=5_1_2		,      lowerCamelCase_=1_2		,      lowerCamelCase_=1_2		,      lowerCamelCase_=3_0_7_2		,      lowerCamelCase_="gelu"		,      lowerCamelCase_=0.1		,      lowerCamelCase_=0.1		,      lowerCamelCase_=5_1_2		,      lowerCamelCase_=2		,      lowerCamelCase_=0.02		,      lowerCamelCase_=1e-12		,      lowerCamelCase_=False		,      lowerCamelCase_=True		,      lowerCamelCase_=1		,      lowerCamelCase_=0		,      lowerCamelCase_=2		,      **lowerCamelCase_		,      )      ->    Optional[Any]:
    super().__init__(pad_token_id=lowerCamelCase_		,      bos_token_id=lowerCamelCase_		,      eos_token_id=lowerCamelCase_		,      **lowerCamelCase_      )

    _a					:  List[str]						=  vocab_size
    _a					:  Union[str, Any]						=  max_position_embeddings
    _a					:  Tuple						=  hidden_size
    _a					:  Tuple						=  visual_embedding_dim
    _a					:  Optional[Any]						=  num_hidden_layers
    _a					:  str						=  num_attention_heads
    _a					:  Union[str, Any]						=  intermediate_size
    _a					:  List[str]						=  hidden_act
    _a					:  str						=  hidden_dropout_prob
    _a					:  List[Any]						=  attention_probs_dropout_prob
    _a					:  Optional[Any]						=  initializer_range
    _a					:  List[Any]						=  type_vocab_size
    _a					:  Any						=  layer_norm_eps
    _a					:  Tuple						=  bypass_transformer
    _a					:  str						=  special_visual_initialize


