

"""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 	__UpperCamelCase    :

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

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

      _lowerCAmelCase       :   str  =    self.get_config()
      return config, pixel_values, labels

  def __lowerCamelCase		(		self      ):
      '''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    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    TFRegNetModel(config=_A      )
      _lowerCAmelCase       :   Any  =    model(_A    ,training=_A      )
      # 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    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    self.num_labels
      _lowerCAmelCase       :   int  =    TFRegNetForImageClassification(_A      )
      _lowerCAmelCase       :   Any  =    model(_A    ,labels=_A    ,training=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.prepare_config_and_inputs()
      _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    config_and_inputs
      _lowerCAmelCase       :   str  =    {'pixel_values': pixel_values}
      return config, inputs_dict







@require_tf
class 	__UpperCamelCase    (    a__							,							a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
  _UpperCAmelCase          =		(
      {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
      if is_tf_available()
      else {}
  )

  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    TFRegNetModelTester(self      )
      _lowerCAmelCase       :   Optional[int]  =    ConfigTester(self    ,config_class=_A    ,has_text_modality=_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return

  @unittest.skip(reason='RegNet does not use inputs_embeds'      )
  def __lowerCamelCase		(		self      ):
      '''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      ):
      '''simple docstring'''

      super().test_keras_fit()

  @unittest.skip(reason='RegNet does not support input and output embeddings'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

          _lowerCAmelCase       :   Optional[int]  =    ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      def check_hidden_states_output(_A    ,_A    ,_A      ):
          _lowerCAmelCase       :   List[Any]  =    model_class(_A      )
          _lowerCAmelCase       :   str  =    model(**self._prepare_for_class(_A    ,_A      )    ,training=_A      )

          _lowerCAmelCase       :   List[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(_A      )    ,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]    ,)

      _lowerCAmelCase,					_lowerCAmelCase       :   Optional[int]  =    self.model_tester.prepare_config_and_inputs_for_common()
      _lowerCAmelCase       :   Optional[Any]  =    ['basic', 'bottleneck']
      for model_class in self.all_model_classes:
          for layer_type in layers_type:
              _lowerCAmelCase       :   Tuple  =    layer_type
              _lowerCAmelCase       :   Tuple  =    True
              check_hidden_states_output(_A    ,_A    ,_A      )

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

              check_hidden_states_output(_A    ,_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase,					_lowerCAmelCase       :   Dict  =    self.model_tester.prepare_config_and_inputs_for_common()

      def check_equivalence(_A    ,_A    ,_A    ,_A={}      ):
          _lowerCAmelCase       :   Optional[int]  =    model(_A    ,return_dict=_A    ,**_A      )
          _lowerCAmelCase       :   List[str]  =    model(_A    ,return_dict=_A    ,**_A      ).to_tuple()

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

              recursive_check(_A    ,_A      )

      for model_class in self.all_model_classes:
          _lowerCAmelCase       :   Optional[int]  =    model_class(_A      )

          _lowerCAmelCase       :   List[Any]  =    self._prepare_for_class(_A    ,_A      )
          _lowerCAmelCase       :   Any  =    self._prepare_for_class(_A    ,_A      )
          check_equivalence(_A    ,_A    ,_A      )

          _lowerCAmelCase       :   int  =    self._prepare_for_class(_A    ,_A    ,return_labels=_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    self._prepare_for_class(_A    ,_A    ,return_labels=_A      )
          check_equivalence(_A    ,_A    ,_A      )

          _lowerCAmelCase       :   Union[str, Any]  =    self._prepare_for_class(_A    ,_A      )
          _lowerCAmelCase       :   Any  =    self._prepare_for_class(_A    ,_A      )
          check_equivalence(_A    ,_A    ,_A    ,{'output_hidden_states': True}      )

          _lowerCAmelCase       :   Tuple  =    self._prepare_for_class(_A    ,_A    ,return_labels=_A      )
          _lowerCAmelCase       :   Dict  =    self._prepare_for_class(_A    ,_A    ,return_labels=_A      )
          check_equivalence(_A    ,_A    ,_A    ,{'output_hidden_states': True}      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_A      )







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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





def 		lowerCamelCase__		(					):

    '''simple docstring'''



    _lowerCAmelCase       :   List[str]  =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
    return image







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

  @cached_property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

      _lowerCAmelCase       :   List[str]  =    self.default_image_processor
      _lowerCAmelCase       :   int  =    prepare_img()
      _lowerCAmelCase       :   Optional[int]  =    image_processor(images=_A    ,return_tensors='tf'      )

      # forward pass
      _lowerCAmelCase       :   List[str]  =    model(**_A    ,training=_A      )

      # verify the logits
      _lowerCAmelCase       :   int  =    tf.TensorShape((1, 1000)      )
      self.assertEqual(outputs.logits.shape    ,_A      )

      _lowerCAmelCase       :   Optional[int]  =    tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]      )

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








"""simple docstring"""






import logging
import os

from .state import PartialState







class 	__UpperCamelCase    (    logging.LoggerAdapter						):

  @staticmethod
  def __lowerCamelCase		(		_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    PartialState()
      return not main_process_only or (main_process_only and state.is_main_process)







  def __lowerCamelCase		(		self    ,_A    ,_A    ,*_A    ,**_A      ):
      '''simple docstring'''

      if PartialState._shared_state == {}:
          raise RuntimeError(
              'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.'      )
      _lowerCAmelCase       :   Tuple  =    kwargs.pop('main_process_only'    ,_A      )
      _lowerCAmelCase       :   Any  =    kwargs.pop('in_order'    ,_A      )

      if self.isEnabledFor(_A      ):
          if self._should_log(_A      ):
              _lowerCAmelCase,					_lowerCAmelCase       :   Optional[int]  =    self.process(_A    ,_A      )
              self.logger.log(_A    ,_A    ,*_A    ,**_A      )

          elif in_order:
              _lowerCAmelCase       :   str  =    PartialState()
              for i in range(state.num_processes      ):
                  if i == state.process_index:
                      _lowerCAmelCase,					_lowerCAmelCase       :   Optional[int]  =    self.process(_A    ,_A      )
                      self.logger.log(_A    ,_A    ,*_A    ,**_A      )
                  state.wait_for_everyone()





def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase = None   ):

    '''simple docstring'''



    if log_level is None:
        _lowerCAmelCase       :   Union[str, Any]  =    os.environ.get('ACCELERATE_LOG_LEVEL' ,   _lowerCamelCase   )
    _lowerCAmelCase       :   int  =    logging.getLogger(_lowerCamelCase   )
    if log_level is not None:
        logger.setLevel(log_level.upper()   )
        logger.root.setLevel(log_level.upper()   )
    return MultiProcessAdapter(_lowerCamelCase ,   {}   )





