


from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class   A__ :







    """simple docstring"""

    def __init__(	self      , __snake_case      , __snake_case=3      , __snake_case=3_2      , __snake_case=3      , __snake_case=1_0      , __snake_case=[1_0, 2_0, 3_0, 4_0]      , __snake_case=[1, 1, 2, 1]      , __snake_case=True      , __snake_case=True      , __snake_case="relu"      , __snake_case=3      , __snake_case=None      , ):
         snake_case					=    parent
         snake_case					=    batch_size
         snake_case					=    image_size
         snake_case					=    num_channels
         snake_case					=    embeddings_size
         snake_case					=    hidden_sizes
         snake_case					=    depths
         snake_case					=    is_training
         snake_case					=    use_labels
         snake_case					=    hidden_act
         snake_case					=    num_labels
         snake_case					=    scope
         snake_case					=    len(__snake_case   )
    def 		a_      (	self   ):
         snake_case					=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

         snake_case					=    self.get_config()
         return config, pixel_values, labels
    def 		a_      (	self   ):
         return RegNetConfig(
             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      , )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    TFRegNetModel(config=__snake_case   )
         snake_case					=    model(__snake_case      , training=__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 // 3_2, self.image_size // 3_2)      , )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    self.num_labels
         snake_case					=    TFRegNetForImageClassification(__snake_case   )
         snake_case					=    model(__snake_case      , labels=__snake_case      , training=__snake_case   )
         self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)   )




    def 		a_      (	self   ):
         snake_case					=    self.prepare_config_and_inputs()
         snake_case			,  snake_case			,  snake_case					=    config_and_inputs
         snake_case					=    {'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_tf
class   A__ (   snake_case__	, snake_case__	, unittest.TestCase     ):







    """simple docstring"""

    __magic_name__        =		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
    __magic_name__        =		(
        {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
        if is_tf_available()
        else {}
    )

    __magic_name__        =		False
    __magic_name__        =		False
    __magic_name__        =		False
    __magic_name__        =		False
    __magic_name__        =		False
    def 		a_      (	self   ):
         snake_case					=    TFRegNetModelTester(self   )
         snake_case					=    ConfigTester(self      , config_class=__snake_case      , has_text_modality=__snake_case   )
    def 		a_      (	self   ):
         return
    @unittest.skip(reason='''RegNet does not use inputs_embeds'''   )
    def 		a_      (	self   ):
         pass
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''   )   ) == 0      , reason='''TF does not support backprop for grouped convolutions on CPU.'''      , )
    @slow
    def 		a_      (	self   ):
         super().test_keras_fit()
    @unittest.skip(reason='''RegNet does not support input and output embeddings'''   )
    def 		a_      (	self   ):
         pass
    def 		a_      (	self   ):
         snake_case			,  snake_case					=    self.model_tester.prepare_config_and_inputs_for_common()

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

              snake_case					=    ['''pixel_values''']
              self.assertListEqual(arg_names[:1]      , __snake_case   )
    def 		a_      (	self   ):
         snake_case					=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case   )
    def 		a_      (	self   ):
         def check_hidden_states_output(__snake_case      , __snake_case      , __snake_case   ):
              snake_case					=    model_class(__snake_case   )
              snake_case					=    model(**self._prepare_for_class(__snake_case      , __snake_case   )      , training=__snake_case   )

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

              snake_case					=    self.model_tester.num_stages
              self.assertEqual(len(__snake_case   )      , expected_num_stages + 1   )

              # RegNet'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 // 2, self.model_tester.image_size // 2]      , )

         snake_case			,  snake_case					=    self.model_tester.prepare_config_and_inputs_for_common()
         snake_case					=    ['''basic''', '''bottleneck''']
         for model_class in self.all_model_classes:
              for layer_type in layers_type:
                   snake_case					=    layer_type
                   snake_case					=    True
                   check_hidden_states_output(__snake_case      , __snake_case      , __snake_case   )

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

                   check_hidden_states_output(__snake_case      , __snake_case      , __snake_case   )
    def 		a_      (	self   ):
         snake_case			,  snake_case					=    self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(__snake_case      , __snake_case      , __snake_case      , __snake_case={}   ):
              snake_case					=    model(__snake_case      , return_dict=__snake_case      , **__snake_case   )
              snake_case					=    model(__snake_case      , return_dict=__snake_case      , **__snake_case   ).to_tuple()

              def recursive_check(__snake_case      , __snake_case   ):
                   if isinstance(__snake_case      , (List, Tuple)   ):
                        for tuple_iterable_value, dict_iterable_value in zip(__snake_case      , __snake_case   ):
                             recursive_check(__snake_case      , __snake_case   )
                   elif tuple_object is None:
                        return
                   else:
                        self.assertTrue(
                            all(tf.equal(__snake_case      , __snake_case   )   )      , msg=(
                                '''Tuple and dict output are not equal. Difference:'''
                                F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object   )   )}'''
                            )      , )

                   recursive_check(__snake_case      , __snake_case   )

         for model_class in self.all_model_classes:
              snake_case					=    model_class(__snake_case   )

              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case   )
              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case   )
              check_equivalence(__snake_case      , __snake_case      , __snake_case   )

              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case      , return_labels=__snake_case   )
              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case      , return_labels=__snake_case   )
              check_equivalence(__snake_case      , __snake_case      , __snake_case   )

              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case   )
              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case   )
              check_equivalence(__snake_case      , __snake_case      , __snake_case      , {'''output_hidden_states''': True}   )

              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case      , return_labels=__snake_case   )
              snake_case					=    self._prepare_for_class(__snake_case      , __snake_case      , return_labels=__snake_case   )
              check_equivalence(__snake_case      , __snake_case      , __snake_case      , {'''output_hidden_states''': True}   )
    def 		a_      (	self   ):
         snake_case					=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__snake_case   )




    @slow
    def 		a_      (	self   ):
         for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              snake_case					=    TFRegNetModel.from_pretrained(__snake_case   )
              self.assertIsNotNone(__snake_case   )






def       UpperCAmelCase__						():



     """simple docstring"""






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

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







    """simple docstring"""

    @cached_property
    def 		a_      (	self   ):
         return (
             AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
             if is_vision_available()
             else None
         )




    @slow
    def 		a_      (	self   ):
         snake_case					=    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

         snake_case					=    self.default_image_processor
         snake_case					=    prepare_img()
         snake_case					=    image_processor(images=__snake_case      , return_tensors='''tf'''   )

         # forward pass
         snake_case					=    model(**__snake_case      , training=__snake_case   )

         # verify the logits
         snake_case					=    tf.TensorShape((1, 1_0_0_0)   )
         self.assertEqual(outputs.logits.shape      , __snake_case   )

         snake_case					=    tf.constant([-0.4180, -1.5051, -3.4836]   )

         tf.debugging.assert_near(outputs.logits[0, :3]      , __snake_case      , atol=1E-4   )








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_SCREAMING_SNAKE_CASE      :			int      				=   {
    "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _SCREAMING_SNAKE_CASE      :			Dict      				=   [
     "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
     "TimesformerModel",
     "TimesformerForVideoClassification",
     "TimesformerPreTrainedModel",
 ]

if TYPE_CHECKING:
 from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_timesformer import (
      TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TimesformerForVideoClassification,
      TimesformerModel,
      TimesformerPreTrainedModel,
  )

else:
 import sys

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




