


"""simple docstring"""



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







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

       '''simple docstring'''




       snake_case       : Union[str, Any]    =       parent
       snake_case       : Optional[int]    =       batch_size
       snake_case       : Tuple    =       image_size
       snake_case       : str    =       num_channels
       snake_case       : Optional[Any]    =       embeddings_size
       snake_case       : Any    =       hidden_sizes
       snake_case       : Union[str, Any]    =       depths
       snake_case       : Union[str, Any]    =       is_training
       snake_case       : Tuple    =       use_labels
       snake_case       : Union[str, Any]    =       hidden_act
       snake_case       : Optional[Any]    =       num_labels
       snake_case       : Optional[Any]    =       scope
       snake_case       : List[str]    =       len(UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       snake_case       : Optional[Any]    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

       snake_case       : List[str]    =       self.get_config()
       return config, pixel_values, labels







   def 					lowerCamelCase						(      self		)      ->						Optional[int]:

       '''simple docstring'''




       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 					lowerCamelCase						(      self		,      UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						Any:

       '''simple docstring'''




       snake_case       : List[Any]    =       TFRegNetModel(config=UpperCamelCase__		)
       snake_case       : str    =       model(UpperCamelCase__		,      training=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 					lowerCamelCase						(      self		,      UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						List[str]:

       '''simple docstring'''




       snake_case       : Dict    =       self.num_labels
       snake_case       : Any    =       TFRegNetForImageClassification(UpperCamelCase__		)
       snake_case       : Optional[int]    =       model(UpperCamelCase__		,      labels=UpperCamelCase__		,      training=UpperCamelCase__		)
       self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)		)







   def 					lowerCamelCase						(      self		)      ->						Optional[Any]:

       '''simple docstring'''




       snake_case       : Tuple    =       self.prepare_config_and_inputs()
       snake_case   ,snake_case   ,snake_case       : str    =       config_and_inputs
       snake_case       : Optional[int]    =       {"pixel_values": pixel_values}
       return config, inputs_dict







@require_tf
class _lowerCAmelCase							( snake_case_       ,				snake_case_       ,				unittest.TestCase      ):
   __UpperCAmelCase					:			Union[str, Any]				    =    (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
   __UpperCAmelCase					:			str				    =    (
       {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
       if is_tf_available()
       else {}
   )

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







   def 					lowerCamelCase						(      self		)      ->						Optional[Any]:

       '''simple docstring'''




       snake_case       : int    =       TFRegNetModelTester(self		)
       snake_case       : Optional[Any]    =       ConfigTester(self		,      config_class=UpperCamelCase__		,      has_text_modality=UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       return







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

       '''simple docstring'''




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

       '''simple docstring'''




       super().test_keras_fit()







   @unittest.skip(reason="RegNet does not support input and output embeddings"		)
   def 					lowerCamelCase						(      self		)      ->						Optional[int]:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       snake_case   ,snake_case       : Tuple    =       self.model_tester.prepare_config_and_inputs_for_common()

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

           snake_case       : Optional[int]    =       ["pixel_values"]
           self.assertListEqual(arg_names[:1]		,      UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						Optional[int]:

       '''simple docstring'''




       snake_case       : int    =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       def check_hidden_states_output(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		):
           snake_case       : str    =       model_class(UpperCamelCase__		)
           snake_case       : Any    =       model(**self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		)		,      training=UpperCamelCase__		)

           snake_case       : Optional[Any]    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           snake_case       : Dict    =       self.model_tester.num_stages
           self.assertEqual(len(UpperCamelCase__		)		,      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       : Optional[Any]    =       self.model_tester.prepare_config_and_inputs_for_common()
       snake_case       : Optional[Any]    =       ["basic", "bottleneck"]
       for model_class in self.all_model_classes:
           for layer_type in layers_type:
               snake_case       : List[str]    =       layer_type
               snake_case       : Any    =       True
               check_hidden_states_output(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)

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

               check_hidden_states_output(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						Tuple:

       '''simple docstring'''




       snake_case   ,snake_case       : int    =       self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__={}		):
           snake_case       : List[str]    =       model(UpperCamelCase__		,      return_dict=UpperCamelCase__		,      **UpperCamelCase__		)
           snake_case       : Optional[Any]    =       model(UpperCamelCase__		,      return_dict=UpperCamelCase__		,      **UpperCamelCase__		).to_tuple()

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

               recursive_check(UpperCamelCase__		,      UpperCamelCase__		)

       for model_class in self.all_model_classes:
           snake_case       : Any    =       model_class(UpperCamelCase__		)

           snake_case       : Optional[int]    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		)
           snake_case       : Dict    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		)
           check_equivalence(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Optional[Any]    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		,      return_labels=UpperCamelCase__		)
           snake_case       : Dict    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		,      return_labels=UpperCamelCase__		)
           check_equivalence(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Tuple    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		)
           snake_case       : Tuple    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		)
           check_equivalence(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		,      {"output_hidden_states": True}		)

           snake_case       : Optional[Any]    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		,      return_labels=UpperCamelCase__		)
           snake_case       : Union[str, Any]    =       self._prepare_for_class(UpperCamelCase__		,      UpperCamelCase__		,      return_labels=UpperCamelCase__		)
           check_equivalence(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		,      {"output_hidden_states": True}		)







   def 					lowerCamelCase						(      self		)      ->						Dict:

       '''simple docstring'''




       snake_case       : Tuple    =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__		)







   @slow
   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case       : Tuple    =       TFRegNetModel.from_pretrained(UpperCamelCase__		)
           self.assertIsNotNone(UpperCamelCase__		)







def     __lowerCAmelCase		(		)      ->		List[Any]:


    """simple docstring"""





    snake_case       : List[Any]    =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
    return image







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







   @cached_property
   def 					lowerCamelCase						(      self		)      ->						List[Any]:

       '''simple docstring'''




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







   @slow
   def 					lowerCamelCase						(      self		)      ->						Union[str, Any]:

       '''simple docstring'''




       snake_case       : List[str]    =       TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

       snake_case       : List[Any]    =       self.default_image_processor
       snake_case       : Optional[Any]    =       prepare_img()
       snake_case       : List[str]    =       image_processor(images=UpperCamelCase__		,      return_tensors="tf"		)

       # forward pass
       snake_case       : Any    =       model(**UpperCamelCase__		,      training=UpperCamelCase__		)

       # verify the logits
       snake_case       : Dict    =       tf.TensorShape((1, 1000)		)
       self.assertEqual(outputs.logits.shape		,      UpperCamelCase__		)

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

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









"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__snake_case       =       {
    """configuration_time_series_transformer""": [
        """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """TimeSeriesTransformerConfig""",
    ],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case       =       [
      """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """TimeSeriesTransformerForPrediction""",
      """TimeSeriesTransformerModel""",
      """TimeSeriesTransformerPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_time_series_transformer import (
      TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
      TimeSeriesTransformerConfig,
  )

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_time_series_transformer import (
        TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
        TimeSeriesTransformerForPrediction,
        TimeSeriesTransformerModel,
        TimeSeriesTransformerPreTrainedModel,
    )

else:
  import sys

  __snake_case       =       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





