






'''simple docstring'''



import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor
class 							__SCREAMING_SNAKE_CASE       :




      def __init__(  self ,   lowerCamelCase ,   lowerCamelCase=13 ,   lowerCamelCase=32 ,   lowerCamelCase=3 ,   lowerCamelCase=4 ,   lowerCamelCase=[10, 20, 30, 40] ,   lowerCamelCase=[2, 2, 3, 2] ,   lowerCamelCase=True ,   lowerCamelCase=True ,   lowerCamelCase=37 ,   lowerCamelCase="gelu" ,   lowerCamelCase=10 ,   lowerCamelCase=0.02 ,   lowerCamelCase=["stage2", "stage3", "stage4"] ,   lowerCamelCase=[2, 3, 4] ,   lowerCamelCase=None ,   )							->List[str]:



         '''simple docstring'''
         __a				     =    parent
         __a				     =    batch_size
         __a				     =    image_size
         __a				     =    num_channels
         __a				     =    num_stages
         __a				     =    hidden_sizes
         __a				     =    depths
         __a				     =    is_training
         __a				     =    use_labels
         __a				     =    intermediate_size
         __a				     =    hidden_act
         __a				     =    num_labels
         __a				     =    initializer_range
         __a				     =    out_features
         __a				     =    out_indices
         __a				     =    scope




      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

         __a				     =    None
         if self.use_labels:
            __a				     =    ids_tensor([self.batch_size] ,   self.num_labels      )

         __a				     =    self.get_config()
         return config, pixel_values, labels




      def  __UpperCamelCase							(  self      )							->Dict:



         '''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=lowerCamelCase ,   initializer_range=self.initializer_range ,   out_features=self.out_features ,   out_indices=self.out_indices ,   num_labels=self.num_labels ,   )




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



         '''simple docstring'''
         __a				     =    ConvNextModel(config=lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )
         # 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 ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )							->Tuple:



         '''simple docstring'''
         __a				     =    ConvNextForImageClassification(lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase ,   labels=lowerCamelCase      )
         self.parent.assertEqual(result.logits.shape ,   (self.batch_size, self.num_labels)      )




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



         '''simple docstring'''
         __a				     =    ConvNextBackbone(config=lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )

         # verify hidden states
         self.parent.assertEqual(len(result.feature_maps      ) ,   len(config.out_features      )      )
         self.parent.assertListEqual(list(result.feature_maps[0].shape      ) ,   [self.batch_size, self.hidden_sizes[1], 4, 4]      )

         # verify channels
         self.parent.assertEqual(len(model.channels      ) ,   len(config.out_features      )      )
         self.parent.assertListEqual(model.channels ,   config.hidden_sizes[1:]      )

         # verify backbone works with out_features=None
         __a				     =    None
         __a				     =    ConvNextBackbone(config=lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps      ) ,   1      )
         self.parent.assertListEqual(list(result.feature_maps[0].shape      ) ,   [self.batch_size, self.hidden_sizes[-1], 1, 1]      )

         # verify channels
         self.parent.assertEqual(len(model.channels      ) ,   1      )
         self.parent.assertListEqual(model.channels ,   [config.hidden_sizes[-1]]      )






      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    self.prepare_config_and_inputs()
         __a     ,			__a     ,			__a				     =    config_and_inputs
         __a				     =    {'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase      ,      _lowerCAmelCase      ,      unittest.TestCase     ):
      __a  					=(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      __a  					=(
          {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      __a  					=True
      __a  					=False
      __a  					=False
      __a  					=False
      __a  					=False




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



         '''simple docstring'''
         __a				     =    ConvNextModelTester(self      )
         __a				     =    ConfigTester(self ,   config_class=lowerCamelCase ,   has_text_modality=lowerCamelCase ,   hidden_size=37      )




      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()




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



         '''simple docstring'''
         return




      @unittest.skip(reason='ConvNext does not use inputs_embeds'      )
      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         pass




      @unittest.skip(reason='ConvNext does not support input and output embeddings'      )
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         pass




      @unittest.skip(reason='ConvNext does not use feedforward chunking'      )
      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         pass




      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()

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

            __a				     =    ['pixel_values']
            self.assertListEqual(arg_names[:1] ,   lowerCamelCase      )




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



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*lowerCamelCase      )




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



         '''simple docstring'''
         def check_hidden_states_output(lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      ):
            __a				     =    model_class(lowerCamelCase      )
            model.to(lowerCamelCase      )
            model.eval()

            with torch.no_grad():
               __a				     =    model(**self._prepare_for_class(lowerCamelCase ,   lowerCamelCase      )      )

            __a				     =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            __a				     =    self.model_tester.num_stages
            self.assertEqual(len(lowerCamelCase      ) ,   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] ,   )

         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __a				     =    True
            check_hidden_states_output(lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )

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

            check_hidden_states_output(lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowerCamelCase      )






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



         '''simple docstring'''
         for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    ConvNextModel.from_pretrained(lowerCamelCase      )
            self.assertIsNotNone(lowerCamelCase      )







def    __UpperCAmelCase	(				)  ->			Optional[int]:

   """simple docstring"""
   __a				     =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
   return image
@require_torch
@require_vision
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      @cached_property
      def  __UpperCamelCase							(  self      )							->Union[str, Any]:



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






      @slow
      def  __UpperCamelCase							(  self      )							->Dict:



         '''simple docstring'''
         __a				     =    ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'      ).to(lowerCamelCase      )

         __a				     =    self.default_image_processor
         __a				     =    prepare_img()
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(**lowerCamelCase      )

         # verify the logits
         __a				     =    torch.Size((1, 1000)      )
         self.assertEqual(outputs.logits.shape ,   lowerCamelCase      )

         __a				     =    torch.tensor([-0.0260, -0.4739, 0.1911]      ).to(lowerCamelCase      )

         self.assertTrue(torch.allclose(outputs.logits[0, :3] ,   lowerCamelCase ,   atol=1e-4      )      )







@require_torch
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase      ,      _lowerCAmelCase     ):
      __a  					=(ConvNextBackbone,) if is_torch_available() else ()
      __a  					=ConvNextConfig

      __a  					=False




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



         '''simple docstring'''
         __a				     =    ConvNextModelTester(self      )







'''simple docstring'''



from typing import TYPE_CHECKING

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


__UpperCamelCase      :       Optional[int]      			=      {
    """configuration_deberta""": ["""DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DebertaConfig""", """DebertaOnnxConfig"""],
    """tokenization_deberta""": ["""DebertaTokenizer"""],
}

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

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __UpperCamelCase      :       Tuple      			=      [
     """DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """DebertaForMaskedLM""",
     """DebertaForQuestionAnswering""",
     """DebertaForSequenceClassification""",
     """DebertaForTokenClassification""",
     """DebertaModel""",
     """DebertaPreTrainedModel""",
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __UpperCamelCase      :       Optional[Any]      			=      [
     """TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """TFDebertaForMaskedLM""",
     """TFDebertaForQuestionAnswering""",
     """TFDebertaForSequenceClassification""",
     """TFDebertaForTokenClassification""",
     """TFDebertaModel""",
     """TFDebertaPreTrainedModel""",
 ]


if TYPE_CHECKING:
 from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
 from .tokenization_deberta import DebertaTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_deberta_fast import DebertaTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_deberta import (
      DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
      DebertaForMaskedLM,
      DebertaForQuestionAnswering,
      DebertaForSequenceClassification,
      DebertaForTokenClassification,
      DebertaModel,
      DebertaPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_deberta import (
      TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFDebertaForMaskedLM,
      TFDebertaForQuestionAnswering,
      TFDebertaForSequenceClassification,
      TFDebertaForTokenClassification,
      TFDebertaModel,
      TFDebertaPreTrainedModel,
  )


else:
 import sys

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