
'''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        __snake_case	:







    """simple docstring"""



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

    def __lowercase       (       self   :  int		)       ->  Optional[Any]:
      lowerCAmelCase_      :				int      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

      lowerCAmelCase_      :				Any      =       self.get_config()

      return config, pixel_values, labels

    def __lowercase       (       self   :  Any		)       ->  List[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 __lowercase       (       self   :  Any   ,						lowerCamelCase   :  int   ,						lowerCamelCase   :  Optional[int]   ,						lowerCamelCase   :  Optional[int]		)       ->  List[Any]:
      lowerCAmelCase_      :				Union[str, Any]      =       TFResNetModel(config=__UpperCAmelCase		)
      lowerCAmelCase_      :				Optional[Any]      =       model(__UpperCAmelCase		)
      # 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   :  List[str]   ,						lowerCamelCase   :  Union[str, Any]   ,						lowerCamelCase   :  Optional[int]   ,						lowerCamelCase   :  Optional[Any]		)       ->  Tuple:
      lowerCAmelCase_      :				Union[str, Any]      =       self.num_labels
      lowerCAmelCase_      :				str      =       TFResNetForImageClassification(__UpperCAmelCase		)
      lowerCAmelCase_      :				Tuple      =       model(__UpperCAmelCase   ,						labels=__UpperCAmelCase		)
      self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.num_labels)		)





    def __lowercase       (       self   :  Tuple		)       ->  List[str]:
      lowerCAmelCase_      :				Optional[int]      =       self.prepare_config_and_inputs()
      lowerCAmelCase_      :				int      =       config_and_inputs
      lowerCAmelCase_      :				Dict      =       {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_tf
class        __snake_case	(       __SCREAMING_SNAKE_CASE     ,__SCREAMING_SNAKE_CASE     ,unittest.TestCase):







    """simple docstring"""



    lowercase       			= (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    lowercase       			= (
        {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    lowercase       			= False
    lowercase       			= False
    lowercase       			= False
    lowercase       			= False
    lowercase       			= False

    def __lowercase       (       self   :  Any		)       ->  Optional[int]:
      lowerCAmelCase_      :				str      =       TFResNetModelTester(self		)
      lowerCAmelCase_      :				Tuple      =       ConfigTester(self   ,						config_class=__UpperCAmelCase   ,						has_text_modality=__UpperCAmelCase		)

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

    @unittest.skip(reason="""ResNet does not use inputs_embeds"""		)
    def __lowercase       (       self   :  List[Any]		)       ->  Tuple:
      pass

    @unittest.skip(reason="""ResNet does not support input and output embeddings"""		)
    def __lowercase       (       self   :  List[Any]		)       ->  Dict:
      pass

    def __lowercase       (       self   :  List[Any]		)       ->  str:
      lowerCAmelCase_      :				int      =       self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCAmelCase_      :				Optional[Any]      =       ["""pixel_values"""]
        self.assertListEqual(arg_names[:1]   ,						__UpperCAmelCase		)

    def __lowercase       (       self   :  Optional[int]		)       ->  Optional[int]:
      lowerCAmelCase_      :				Union[str, Any]      =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase		)

    def __lowercase       (       self   :  int		)       ->  List[str]:
      def check_hidden_states_output(lowerCamelCase   :  Optional[int]   ,						lowerCamelCase   :  Any   ,						lowerCamelCase   :  Optional[Any]		):
        lowerCAmelCase_      :				Optional[int]      =       model_class(__UpperCAmelCase		)
        lowerCAmelCase_      :				Optional[Any]      =       model(**self._prepare_for_class(__UpperCAmelCase   ,						__UpperCAmelCase		)		)

        lowerCAmelCase_      :				str      =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        lowerCAmelCase_      :				Optional[Any]      =       self.model_tester.num_stages
        self.assertEqual(len(__UpperCAmelCase		)   ,						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]   ,						)

      lowerCAmelCase_      :				List[str]      =       self.model_tester.prepare_config_and_inputs_for_common()
      lowerCAmelCase_      :				Union[str, Any]      =       ["""basic""", """bottleneck"""]
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          lowerCAmelCase_      :				Optional[Any]      =       layer_type
          lowerCAmelCase_      :				int      =       True
          check_hidden_states_output(__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase		)

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowerCAmelCase_      :				Optional[int]      =       True

          check_hidden_states_output(__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase		)

    def __lowercase       (       self   :  Tuple		)       ->  List[Any]:
      lowerCAmelCase_      :				Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)





    @slow
    def __lowercase       (       self   :  Union[str, Any]		)       ->  int:
      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCAmelCase_      :				Optional[Any]      =       TFResNetModel.from_pretrained(__UpperCAmelCase		)
        self.assertIsNotNone(__UpperCAmelCase		)







def     UpperCamelCase_      (   ):
  '''simple docstring'''





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






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







    """simple docstring"""



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





    @slow
    def __lowercase       (       self   :  List[str]		)       ->  Tuple:
      lowerCAmelCase_      :				Dict      =       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

      lowerCAmelCase_      :				Any      =       self.default_image_processor
      lowerCAmelCase_      :				Optional[Any]      =       prepare_img()
      lowerCAmelCase_      :				Dict      =       image_processor(images=__UpperCAmelCase   ,						return_tensors="""tf"""		)

      # forward pass
      lowerCAmelCase_      :				Dict      =       model(**__UpperCAmelCase		)

      # verify the logits
      lowerCAmelCase_      :				Dict      =       tf.TensorShape((1, 10_00)		)
      self.assertEqual(outputs.logits.shape   ,						__UpperCAmelCase		)

      lowerCAmelCase_      :				str      =       tf.constant([-11.1_069, -9.7_877, -8.3_777]		)

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







'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__A :  List[Any]    							=				{
    "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"],
    "tokenization_roc_bert": ["RoCBertTokenizer"],
}

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  pass

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __A :  Union[str, Any]    							=				[
      "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
      "RoCBertForCausalLM",
      "RoCBertForMaskedLM",
      "RoCBertForMultipleChoice",
      "RoCBertForPreTraining",
      "RoCBertForQuestionAnswering",
      "RoCBertForSequenceClassification",
      "RoCBertForTokenClassification",
      "RoCBertLayer",
      "RoCBertModel",
      "RoCBertPreTrainedModel",
      "load_tf_weights_in_roc_bert",
  ]

if TYPE_CHECKING:
  from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
  from .tokenization_roc_bert import RoCBertTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    raise OptionalDependencyNotAvailable()

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_roc_bert import (
        ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
        RoCBertForCausalLM,
        RoCBertForMaskedLM,
        RoCBertForMultipleChoice,
        RoCBertForPreTraining,
        RoCBertForQuestionAnswering,
        RoCBertForSequenceClassification,
        RoCBertForTokenClassification,
        RoCBertLayer,
        RoCBertModel,
        RoCBertPreTrainedModel,
        load_tf_weights_in_roc_bert,
    )


else:
  import sys

  __A :  int    							=				_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



