





"""simple docstring"""
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 lowerCamelCase__  :



   def __init__(       self      ,   snake_case      ,   snake_case=1_3      ,   snake_case=3_2      ,   snake_case=3      ,   snake_case=4      ,   snake_case=[1_0, 2_0, 3_0, 4_0]      ,   snake_case=[2, 2, 3, 2]      ,   snake_case=True      ,   snake_case=True      ,   snake_case=3_7      ,   snake_case="gelu"      ,   snake_case=1_0      ,   snake_case=0.02      ,   snake_case=3      ,   snake_case=None      ,   ) ->    int:







      """simple docstring"""
      lowercase    :			Union[str, Any]  =       parent
      lowercase    :			int  =       batch_size
      lowercase    :			int  =       image_size
      lowercase    :			List[str]  =       num_channels
      lowercase    :			str  =       num_stages
      lowercase    :			Optional[Any]  =       hidden_sizes
      lowercase    :			Any  =       depths
      lowercase    :			Any  =       is_training
      lowercase    :			List[str]  =       use_labels
      lowercase    :			Tuple  =       intermediate_size
      lowercase    :			Optional[int]  =       hidden_act
      lowercase    :			str  =       type_sequence_label_size
      lowercase    :			Optional[int]  =       initializer_range
      lowercase    :			List[Any]  =       scope



   def    _UpperCAmelCase	(       self	) ->    str:







      """simple docstring"""
      lowercase    :			Optional[int]  =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

      lowercase    :			str  =       self.get_config()

      return config, pixel_values, labels



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







      """simple docstring"""
      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=snake_case      ,   initializer_range=self.initializer_range      ,   )



   def    _UpperCAmelCase	(       self      ,   snake_case      ,   snake_case      ,   snake_case	) ->    Tuple:







      """simple docstring"""
      lowercase    :			Optional[Any]  =       TFConvNextModel(config=snake_case	)
      lowercase    :			Dict  =       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    _UpperCAmelCase	(       self      ,   snake_case      ,   snake_case      ,   snake_case	) ->    Any:







      """simple docstring"""
      lowercase    :			Optional[Any]  =       self.type_sequence_label_size
      lowercase    :			Tuple  =       TFConvNextForImageClassification(snake_case	)
      lowercase    :			Any  =       model(snake_case      ,   labels=snake_case      ,   training=snake_case	)
      self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.type_sequence_label_size)	)





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







      """simple docstring"""
      lowercase    :			Dict  =       self.prepare_config_and_inputs()
      lowercase  ,					lowercase  ,					lowercase    :			Any  =       config_and_inputs
      lowercase    :			Tuple  =       {"""pixel_values""": pixel_values}
      return config, inputs_dict




@require_tf
class lowerCamelCase__  (    __UpperCamelCase  ,				__UpperCamelCase  ,				unittest.TestCase				):
   __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	) ->    str:







      """simple docstring"""
      lowercase    :			List[Any]  =       TFConvNextModelTester(self	)
      lowercase    :			int  =       ConfigTester(
          self      ,   config_class=snake_case      ,   has_text_modality=snake_case      ,   hidden_size=3_7      ,   )



   @unittest.skip(reason="""ConvNext does not use inputs_embeds"""	)
   def    _UpperCAmelCase	(       self	) ->    Optional[int]:







      """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    _UpperCAmelCase	(       self	) ->    Union[str, Any]:







      """simple docstring"""
      super().test_keras_fit()



   @unittest.skip(reason="""ConvNext does not support input and output embeddings"""	)
   def    _UpperCAmelCase	(       self	) ->    str:







      """simple docstring"""
      pass



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







      """simple docstring"""
      lowercase  ,					lowercase    :			List[Any]  =       self.model_tester.prepare_config_and_inputs_for_common()

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

         lowercase    :			str  =       ["""pixel_values"""]
         self.assertListEqual(arg_names[:1]      ,   snake_case	)



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







      """simple docstring"""
      lowercase    :			Optional[int]  =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case	)



   @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	) ->    List[str]:







      """simple docstring"""
      super().test_dataset_conversion()



   def    _UpperCAmelCase	(       self	) ->    List[Any]:







      """simple docstring"""
      def check_hidden_states_output(snake_case      ,   snake_case      ,   snake_case	):
         lowercase    :			Optional[int]  =       model_class(snake_case	)

         lowercase    :			Optional[int]  =       model(**self._prepare_for_class(snake_case      ,   snake_case	)	)
         lowercase    :			List[str]  =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         lowercase    :			Dict  =       self.model_tester.num_stages
         self.assertEqual(len(snake_case	)      ,   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]      ,   )

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

      for model_class in self.all_model_classes:
         lowercase    :			List[Any]  =       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"]
         lowercase    :			List[str]  =       True

         check_hidden_states_output(snake_case      ,   snake_case      ,   snake_case	)



   def    _UpperCAmelCase	(       self	) ->    str:







      """simple docstring"""
      lowercase  ,					lowercase    :			str  =       self.model_tester.prepare_config_and_inputs_for_common()

      def check_equivalence(snake_case      ,   snake_case      ,   snake_case      ,   snake_case={}	):
         lowercase    :			List[str]  =       model(snake_case      ,   return_dict=snake_case      ,   **snake_case	)
         lowercase    :			List[str]  =       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:
         lowercase    :			Dict  =       model_class(snake_case	)

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

         lowercase    :			int  =       self._prepare_for_class(snake_case      ,   snake_case      ,   return_labels=snake_case	)
         lowercase    :			List[str]  =       self._prepare_for_class(snake_case      ,   snake_case      ,   return_labels=snake_case	)
         check_equivalence(snake_case      ,   snake_case      ,   snake_case	)

         lowercase    :			Dict  =       self._prepare_for_class(snake_case      ,   snake_case	)
         lowercase    :			List[Any]  =       self._prepare_for_class(snake_case      ,   snake_case	)
         check_equivalence(snake_case      ,   snake_case      ,   snake_case      ,   {"""output_hidden_states""": True}	)

         lowercase    :			str  =       self._prepare_for_class(snake_case      ,   snake_case      ,   return_labels=snake_case	)
         lowercase    :			Tuple  =       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    _UpperCAmelCase	(       self	) ->    Dict:







      """simple docstring"""
      lowercase    :			Dict  =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*snake_case	)





   @slow
   def    _UpperCAmelCase	(       self	) ->    List[Any]:







      """simple docstring"""
      lowercase    :			List[str]  =       TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""	)
      self.assertIsNotNone(snake_case	)




def 			__snake_case						(      )		->				List[Any]:
   lowercase    :			Dict  =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
   return image







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



   @cached_property
   def    _UpperCAmelCase	(       self	) ->    int:







      """simple docstring"""
      return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""	) if is_vision_available() else None





   @slow
   def    _UpperCAmelCase	(       self	) ->    str:







      """simple docstring"""
      lowercase    :			List[Any]  =       TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""	)

      lowercase    :			Tuple  =       self.default_image_processor
      lowercase    :			Optional[int]  =       prepare_img()
      lowercase    :			int  =       image_processor(images=snake_case      ,   return_tensors="""tf"""	)

      # forward pass
      lowercase    :			Optional[Any]  =       model(**snake_case	)

      # verify the logits
      lowercase    :			Optional[int]  =       tf.TensorShape((1, 1_0_0_0)	)
      self.assertEqual(outputs.logits.shape      ,   snake_case	)

      lowercase    :			Optional[Any]  =       tf.constant([-0.02_60, -0.47_39, 0.19_11]	)

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









"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase:	Union[str, Any]							      ={
    "configuration_deberta_v2": ["DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaV2Config", "DebertaV2OnnxConfig"],
    "tokenization_deberta_v2": ["DebertaV2Tokenizer"],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCAmelCase:	Dict							      =["DebertaV2TokenizerFast"]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCAmelCase:	Optional[Any]							      =[
       "TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
       "TFDebertaV2ForMaskedLM",
       "TFDebertaV2ForQuestionAnswering",
       "TFDebertaV2ForSequenceClassification",
       "TFDebertaV2ForTokenClassification",
       "TFDebertaV2Model",
       "TFDebertaV2PreTrainedModel",
   ]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCAmelCase:	str							      =[
       "DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
       "DebertaV2ForMaskedLM",
       "DebertaV2ForMultipleChoice",
       "DebertaV2ForQuestionAnswering",
       "DebertaV2ForSequenceClassification",
       "DebertaV2ForTokenClassification",
       "DebertaV2Model",
       "DebertaV2PreTrainedModel",
   ]


if TYPE_CHECKING:
   from .configuration_deberta_va import (
       DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
       DebertaVaConfig,
       DebertaVaOnnxConfig,
   )
   from .tokenization_deberta_va import DebertaVaTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_deberta_va_fast import DebertaVaTokenizerFast

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_deberta_va import (
          TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFDebertaVaForMaskedLM,
          TFDebertaVaForQuestionAnswering,
          TFDebertaVaForSequenceClassification,
          TFDebertaVaForTokenClassification,
          TFDebertaVaModel,
          TFDebertaVaPreTrainedModel,
      )

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_deberta_va import (
          DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
          DebertaVaForMaskedLM,
          DebertaVaForMultipleChoice,
          DebertaVaForQuestionAnswering,
          DebertaVaForSequenceClassification,
          DebertaVaForTokenClassification,
          DebertaVaModel,
          DebertaVaPreTrainedModel,
      )

else:
   import sys

   lowerCAmelCase:	Optional[Any]							      =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


