




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






			'''simple docstring'''



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

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

							_lowerCamelCase     :			Any    =    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  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			Optional[int]    =    TFRegNetModel(config=lowercase  )
							_lowerCamelCase     :			Any    =    model(lowercase  ,      training=lowercase  )
							# 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 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			str    =    self.num_labels
							_lowerCamelCase     :			int    =    TFRegNetForImageClassification(lowercase  )
							_lowerCamelCase     :			List[str]    =    model(lowercase  ,      labels=lowercase  ,      training=lowercase  )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)  )






			def 					A_    (  self  ):
							_lowerCamelCase     :			Any    =    self.prepare_config_and_inputs()
							_lowerCamelCase, _lowerCamelCase, _lowerCamelCase     :			str    =    config_and_inputs
							_lowerCamelCase     :			Union[str, Any]    =    {'pixel_values': pixel_values}
							return config, inputs_dict






@require_tf
class lowerCAmelCase__	(     lowercase,	lowercase,	unittest.TestCase						):






			'''simple docstring'''



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

			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			def 					A_    (  self  ):
							_lowerCamelCase     :			Union[str, Any]    =    TFRegNetModelTester(self  )
							_lowerCamelCase     :			Union[str, Any]    =    ConfigTester(self  ,      config_class=lowercase  ,      has_text_modality=lowercase  )
			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  ):
							_lowerCamelCase, _lowerCamelCase     :			Tuple    =    self.model_tester.prepare_config_and_inputs_for_common()

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

											_lowerCamelCase     :			int    =    ['pixel_values']
											self.assertListEqual(arg_names[:1]  ,      lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			Dict    =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase  )
			def 					A_    (  self  ):
							def check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  ):
											_lowerCamelCase     :			Optional[Any]    =    model_class(lowercase  )
											_lowerCamelCase     :			List[Any]    =    model(**self._prepare_for_class(lowercase  ,      lowercase  )  ,      training=lowercase  )

											_lowerCamelCase     :			Tuple    =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											_lowerCamelCase     :			str    =    self.model_tester.num_stages
											self.assertEqual(len(lowercase  )  ,      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     :			Any    =    self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase     :			Any    =    ['basic', 'bottleneck']
							for model_class in self.all_model_classes:
											for layer_type in layers_type:
															_lowerCamelCase     :			Tuple    =    layer_type
															_lowerCamelCase     :			int    =    True
															check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  )

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

															check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase, _lowerCamelCase     :			int    =    self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      lowercase={}  ):
											_lowerCamelCase     :			Optional[Any]    =    model(lowercase  ,      return_dict=lowercase  ,      **lowercase  )
											_lowerCamelCase     :			int    =    model(lowercase  ,      return_dict=lowercase  ,      **lowercase  ).to_tuple()

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

															recursive_check(lowercase  ,      lowercase  )

							for model_class in self.all_model_classes:
											_lowerCamelCase     :			Dict    =    model_class(lowercase  )

											_lowerCamelCase     :			Any    =    self._prepare_for_class(lowercase  ,      lowercase  )
											_lowerCamelCase     :			List[Any]    =    self._prepare_for_class(lowercase  ,      lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  )

											_lowerCamelCase     :			Any    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											_lowerCamelCase     :			int    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  )

											_lowerCamelCase     :			int    =    self._prepare_for_class(lowercase  ,      lowercase  )
											_lowerCamelCase     :			Union[str, Any]    =    self._prepare_for_class(lowercase  ,      lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      {'output_hidden_states': True}  )

											_lowerCamelCase     :			Optional[Any]    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											_lowerCamelCase     :			List[str]    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      {'output_hidden_states': True}  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			Tuple    =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase  )






			@slow
			def 					A_    (  self  ):
							for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_lowerCamelCase     :			Dict    =    TFRegNetModel.from_pretrained(lowercase  )
											self.assertIsNotNone(lowercase  )







def      _snake_case			(				):
				_lowerCamelCase     :			Optional[Any]    =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
				return image






@require_tf
@require_vision
class lowerCAmelCase__	(     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  ):
							_lowerCamelCase     :			Optional[Any]    =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

							_lowerCamelCase     :			Optional[int]    =    self.default_image_processor
							_lowerCamelCase     :			Optional[int]    =    prepare_img()
							_lowerCamelCase     :			Optional[Any]    =    image_processor(images=lowercase  ,      return_tensors='tf'  )

							# forward pass
							_lowerCamelCase     :			Dict    =    model(**lowercase  ,      training=lowercase  )

							# verify the logits
							_lowerCamelCase     :			Any    =    tf.TensorShape((1, 1000)  )
							self.assertEqual(outputs.logits.shape  ,      lowercase  )

							_lowerCamelCase     :			str    =    tf.constant([-0.41_80, -1.50_51, -3.48_36]  )

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






import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


__A			   = logging.get_logger(__name__)

__A			   = {
    "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json",
}


class     UpperCAmelCase						(_UpperCAmelCase  ):



    """simple docstring"""

    _UpperCAmelCase	:Dict						    = "deta"
    _UpperCAmelCase	:Any						    = {
        "hidden_size": "d_model",
        "num_attention_heads": "encoder_attention_heads",
    }






    def __init__(   self    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=900    ,			_UpperCAmelCase=2048    ,			_UpperCAmelCase=6    ,			_UpperCAmelCase=2048    ,			_UpperCAmelCase=8    ,			_UpperCAmelCase=6    ,			_UpperCAmelCase=1024    ,			_UpperCAmelCase=8    ,			_UpperCAmelCase=0.0    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase="relu"    ,			_UpperCAmelCase=256    ,			_UpperCAmelCase=0.1    ,			_UpperCAmelCase=0.0    ,			_UpperCAmelCase=0.0    ,			_UpperCAmelCase=0.02    ,			_UpperCAmelCase=1.0    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase="sine"    ,			_UpperCAmelCase=5    ,			_UpperCAmelCase=4    ,			_UpperCAmelCase=4    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=300    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=1    ,			_UpperCAmelCase=5    ,			_UpperCAmelCase=2    ,			_UpperCAmelCase=1    ,			_UpperCAmelCase=1    ,			_UpperCAmelCase=5    ,			_UpperCAmelCase=2    ,			_UpperCAmelCase=0.1    ,			_UpperCAmelCase=0.25    ,			**_UpperCAmelCase    ,			):
       if backbone_config is None:
          logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''							)
          lowercase__:   str					=      CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4''']							)
       else:
          if isinstance(_UpperCAmelCase    ,			_UpperCAmelCase							):
             lowercase__:   Tuple					=      backbone_config.pop('''model_type'''							)
             lowercase__:   str					=      CONFIG_MAPPING[backbone_model_type]
             lowercase__:   Optional[int]					=      config_class.from_dict(_UpperCAmelCase							)

       lowercase__:   int					=      backbone_config
       lowercase__:   Any					=      num_queries
       lowercase__:   List[str]					=      max_position_embeddings
       lowercase__:   Optional[Any]					=      d_model
       lowercase__:   List[Any]					=      encoder_ffn_dim
       lowercase__:   Tuple					=      encoder_layers
       lowercase__:   Dict					=      encoder_attention_heads
       lowercase__:   Any					=      decoder_ffn_dim
       lowercase__:   Union[str, Any]					=      decoder_layers
       lowercase__:   List[Any]					=      decoder_attention_heads
       lowercase__:   int					=      dropout
       lowercase__:   List[str]					=      attention_dropout
       lowercase__:   Tuple					=      activation_dropout
       lowercase__:   Tuple					=      activation_function
       lowercase__:   int					=      init_std
       lowercase__:   Optional[Any]					=      init_xavier_std
       lowercase__:   Optional[Any]					=      encoder_layerdrop
       lowercase__:   Optional[int]					=      auxiliary_loss
       lowercase__:   Union[str, Any]					=      position_embedding_type
       # deformable attributes
       lowercase__:   List[str]					=      num_feature_levels
       lowercase__:   Optional[Any]					=      encoder_n_points
       lowercase__:   int					=      decoder_n_points
       lowercase__:   str					=      two_stage
       lowercase__:   Optional[int]					=      two_stage_num_proposals
       lowercase__:   Tuple					=      with_box_refine
       lowercase__:   str					=      assign_first_stage
       if two_stage is True and with_box_refine is False:
          raise ValueError('''If two_stage is True, with_box_refine must be True.'''							)
       # Hungarian matcher
       lowercase__:   Union[str, Any]					=      class_cost
       lowercase__:   Optional[int]					=      bbox_cost
       lowercase__:   int					=      giou_cost
       # Loss coefficients
       lowercase__:   Optional[int]					=      mask_loss_coefficient
       lowercase__:   List[str]					=      dice_loss_coefficient
       lowercase__:   str					=      bbox_loss_coefficient
       lowercase__:   Union[str, Any]					=      giou_loss_coefficient
       lowercase__:   Optional[int]					=      eos_coefficient
       lowercase__:   str					=      focal_alpha
       super().__init__(is_encoder_decoder=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    @property
    def _snake_case			(   self							):
       return self.encoder_attention_heads






    @property
    def _snake_case			(   self							):
       return self.d_model






    def _snake_case			(   self							):
       lowercase__:   Union[str, Any]					=      copy.deepcopy(self.__dict__							)
       lowercase__:   Dict					=      self.backbone_config.to_dict()
       lowercase__:   Union[str, Any]					=      self.__class__.model_type
       return output
