
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
   from PIL import Image

   from transformers import ConvNextImageProcessor





class 				UpperCamelCase__		:






       """simple docstring"""


       def __init__(							self ,     _A ,     _A=13 ,     _A=32 ,     _A=3 ,     _A=4 ,     _A=[10, 20, 30, 40] ,     _A=[2, 2, 3, 2] ,     _A=True ,     _A=True ,     _A=37 ,     _A="gelu" ,     _A=10 ,     _A=0.02 ,     _A=3 ,     _A=None ,     )				->				Tuple:
          SCREAMING_SNAKE_CASE_	=      parent
          SCREAMING_SNAKE_CASE_	=      batch_size
          SCREAMING_SNAKE_CASE_	=      image_size
          SCREAMING_SNAKE_CASE_	=      num_channels
          SCREAMING_SNAKE_CASE_	=      num_stages
          SCREAMING_SNAKE_CASE_	=      hidden_sizes
          SCREAMING_SNAKE_CASE_	=      depths
          SCREAMING_SNAKE_CASE_	=      is_training
          SCREAMING_SNAKE_CASE_	=      use_labels
          SCREAMING_SNAKE_CASE_	=      intermediate_size
          SCREAMING_SNAKE_CASE_	=      hidden_act
          SCREAMING_SNAKE_CASE_	=      type_sequence_label_size
          SCREAMING_SNAKE_CASE_	=      initializer_range
          SCREAMING_SNAKE_CASE_	=      scope



       def     _UpperCamelCase	(							self	)				->				Dict:
          SCREAMING_SNAKE_CASE_	=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

          SCREAMING_SNAKE_CASE_	=      None
          if self.use_labels:
             SCREAMING_SNAKE_CASE_	=      ids_tensor([self.batch_size] ,     self.type_sequence_label_size	)

          SCREAMING_SNAKE_CASE_	=      self.get_config()

          return config, pixel_values, labels



       def     _UpperCamelCase	(							self	)				->				Union[str, Any]:
          return ConvNextConfig(
              num_channels=self.num_channels ,     hidden_sizes=self.hidden_sizes ,     depths=self.depths ,     num_stages=self.num_stages ,     hidden_act=self.hidden_act ,     is_decoder=_A ,     initializer_range=self.initializer_range ,     )



       def     _UpperCamelCase	(							self ,     _A ,     _A ,     _A	)				->				Any:
          SCREAMING_SNAKE_CASE_	=      TFConvNextModel(config=_A	)
          SCREAMING_SNAKE_CASE_	=      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     _UpperCamelCase	(							self ,     _A ,     _A ,     _A	)				->				Dict:
          SCREAMING_SNAKE_CASE_	=      self.type_sequence_label_size
          SCREAMING_SNAKE_CASE_	=      TFConvNextForImageClassification(_A	)
          SCREAMING_SNAKE_CASE_	=      model(_A ,     labels=_A ,     training=_A	)
          self.parent.assertEqual(result.logits.shape ,     (self.batch_size, self.type_sequence_label_size)	)




       def     _UpperCamelCase	(							self	)				->				List[Any]:
          SCREAMING_SNAKE_CASE_	=      self.prepare_config_and_inputs()
          SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	=      config_and_inputs
          SCREAMING_SNAKE_CASE_	=      {'''pixel_values''': pixel_values}
          return config, inputs_dict







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






       """simple docstring"""


       UpperCAmelCase_				       =(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       UpperCAmelCase_				       =(
           {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       UpperCAmelCase_				       =False
       UpperCAmelCase_				       =False
       UpperCAmelCase_				       =False
       UpperCAmelCase_				       =False
       UpperCAmelCase_				       =False



       def     _UpperCamelCase	(							self	)				->				Any:
          SCREAMING_SNAKE_CASE_	=      TFConvNextModelTester(self	)
          SCREAMING_SNAKE_CASE_	=      ConfigTester(
              self ,     config_class=_A ,     has_text_modality=_A ,     hidden_size=37 ,     )



       @unittest.skip(reason='''ConvNext does not use inputs_embeds'''	)
       def     _UpperCamelCase	(							self	)				->				Any:
          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     _UpperCamelCase	(							self	)				->				List[Any]:
          super().test_keras_fit()



       @unittest.skip(reason='''ConvNext does not support input and output embeddings'''	)
       def     _UpperCamelCase	(							self	)				->				Optional[int]:
          pass



       def     _UpperCamelCase	(							self	)				->				List[Any]:
          SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	=      self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE_	=      ['''pixel_values''']
             self.assertListEqual(arg_names[:1] ,     _A	)



       def     _UpperCamelCase	(							self	)				->				int:
          SCREAMING_SNAKE_CASE_	=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_A	)



       @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.''' ,     )
       def     _UpperCamelCase	(							self	)				->				Tuple:
          super().test_dataset_conversion()



       def     _UpperCamelCase	(							self	)				->				Optional[int]:
          def check_hidden_states_output(_A ,     _A ,     _A	):
             SCREAMING_SNAKE_CASE_	=      model_class(_A	)

             SCREAMING_SNAKE_CASE_	=      model(**self._prepare_for_class(_A ,     _A	)	)
             SCREAMING_SNAKE_CASE_	=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             SCREAMING_SNAKE_CASE_	=      self.model_tester.num_stages
             self.assertEqual(len(_A	) ,     expected_num_stages + 1	)

             # ConvNext'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] ,     )

          SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_	=      True
             check_hidden_states_output(_A ,     _A ,     _A	)

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

             check_hidden_states_output(_A ,     _A ,     _A	)



       def     _UpperCamelCase	(							self	)				->				Dict:
          SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	=      self.model_tester.prepare_config_and_inputs_for_common()

          def check_equivalence(_A ,     _A ,     _A ,     _A={}	):
             SCREAMING_SNAKE_CASE_	=      model(_A ,     return_dict=_A ,     **_A	)
             SCREAMING_SNAKE_CASE_	=      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:
             SCREAMING_SNAKE_CASE_	=      model_class(_A	)

             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A	)
             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A	)
             check_equivalence(_A ,     _A ,     _A	)

             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A ,     return_labels=_A	)
             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A ,     return_labels=_A	)
             check_equivalence(_A ,     _A ,     _A	)

             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A	)
             SCREAMING_SNAKE_CASE_	=      self._prepare_for_class(_A ,     _A	)
             check_equivalence(_A ,     _A ,     _A ,     {'''output_hidden_states''': True}	)

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



       def     _UpperCamelCase	(							self	)				->				int:
          SCREAMING_SNAKE_CASE_	=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_A	)




       @slow
       def     _UpperCamelCase	(							self	)				->				int:
          SCREAMING_SNAKE_CASE_	=      TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''	)
          self.assertIsNotNone(_A	)







def  A__ (       ):
   SCREAMING_SNAKE_CASE_	=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
   return image





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






       """simple docstring"""


       @cached_property
       def     _UpperCamelCase	(							self	)				->				str:
          return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''	) if is_vision_available() else None




       @slow
       def     _UpperCamelCase	(							self	)				->				Any:
          SCREAMING_SNAKE_CASE_	=      TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''	)

          SCREAMING_SNAKE_CASE_	=      self.default_image_processor
          SCREAMING_SNAKE_CASE_	=      prepare_img()
          SCREAMING_SNAKE_CASE_	=      image_processor(images=_A ,     return_tensors='''tf'''	)

          # forward pass
          SCREAMING_SNAKE_CASE_	=      model(**_A	)

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

          SCREAMING_SNAKE_CASE_	=      tf.constant([-0.0260, -0.4739, 0.1911]	)

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




from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
   from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType


__UpperCAmelCase   						=     logging.get_logger(__name__)

__UpperCAmelCase   						=     {
    "microsoft/deberta-base": "https://huggingface.co/microsoft/deberta-base/resolve/main/config.json",
    "microsoft/deberta-large": "https://huggingface.co/microsoft/deberta-large/resolve/main/config.json",
    "microsoft/deberta-xlarge": "https://huggingface.co/microsoft/deberta-xlarge/resolve/main/config.json",
    "microsoft/deberta-base-mnli": "https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/config.json",
    "microsoft/deberta-large-mnli": "https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/config.json",
    "microsoft/deberta-xlarge-mnli": "https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/config.json",
}





class 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       UpperCAmelCase_				       ="deberta"



       def __init__(							self ,     _A=50265 ,     _A=768 ,     _A=12 ,     _A=12 ,     _A=3072 ,     _A="gelu" ,     _A=0.1 ,     _A=0.1 ,     _A=512 ,     _A=0 ,     _A=0.02 ,     _A=1E-7 ,     _A=False ,     _A=-1 ,     _A=0 ,     _A=True ,     _A=None ,     _A=0 ,     _A="gelu" ,     **_A ,     )				->				Optional[int]:
          super().__init__(**_A	)

          SCREAMING_SNAKE_CASE_	=      hidden_size
          SCREAMING_SNAKE_CASE_	=      num_hidden_layers
          SCREAMING_SNAKE_CASE_	=      num_attention_heads
          SCREAMING_SNAKE_CASE_	=      intermediate_size
          SCREAMING_SNAKE_CASE_	=      hidden_act
          SCREAMING_SNAKE_CASE_	=      hidden_dropout_prob
          SCREAMING_SNAKE_CASE_	=      attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_	=      max_position_embeddings
          SCREAMING_SNAKE_CASE_	=      type_vocab_size
          SCREAMING_SNAKE_CASE_	=      initializer_range
          SCREAMING_SNAKE_CASE_	=      relative_attention
          SCREAMING_SNAKE_CASE_	=      max_relative_positions
          SCREAMING_SNAKE_CASE_	=      pad_token_id
          SCREAMING_SNAKE_CASE_	=      position_biased_input

          # Backwards compatibility
          if type(_A	) == str:
             SCREAMING_SNAKE_CASE_	=      [x.strip() for x in pos_att_type.lower().split('''|'''	)]

          SCREAMING_SNAKE_CASE_	=      pos_att_type
          SCREAMING_SNAKE_CASE_	=      vocab_size
          SCREAMING_SNAKE_CASE_	=      layer_norm_eps

          SCREAMING_SNAKE_CASE_	=      kwargs.get('''pooler_hidden_size''' ,     _A	)
          SCREAMING_SNAKE_CASE_	=      pooler_dropout
          SCREAMING_SNAKE_CASE_	=      pooler_hidden_act







class 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       @property
       def     _UpperCamelCase	(							self	)				->				Mapping[str, Mapping[int, str]]:
          if self.task == "multiple-choice":
             SCREAMING_SNAKE_CASE_	=      {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
          else:
             SCREAMING_SNAKE_CASE_	=      {0: '''batch''', 1: '''sequence'''}
          if self._config.type_vocab_size > 0:
             return OrderedDict(
                 [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)]	)
          else:
             return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)]	)



       @property
       def     _UpperCamelCase	(							self	)				->				int:
          return 12




       def     _UpperCamelCase	(							self ,     _A ,     _A = -1 ,     _A = -1 ,     _A = -1 ,     _A = False ,     _A = None ,     _A = 3 ,     _A = 40 ,     _A = 40 ,     _A = None ,     )				->				Mapping[str, Any]:
          SCREAMING_SNAKE_CASE_	=      super().generate_dummy_inputs(preprocessor=_A ,     framework=_A	)
          if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
             del dummy_inputs["token_type_ids"]
          return dummy_inputs


