





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  A__       :





      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_=["stage2", "stage3", "stage4"]	,							A_=[2, 3, 4]	,							A_=None	,							):
       '''simple docstring'''




       UpperCamelCase     : Any	     =       parent
       UpperCamelCase     : Optional[Any]	     =       batch_size
       UpperCamelCase     : Dict	     =       image_size
       UpperCamelCase     : Optional[Any]	     =       num_channels
       UpperCamelCase     : Tuple	     =       num_stages
       UpperCamelCase     : Dict	     =       hidden_sizes
       UpperCamelCase     : Union[str, Any]	     =       depths
       UpperCamelCase     : Optional[Any]	     =       is_training
       UpperCamelCase     : str	     =       use_labels
       UpperCamelCase     : List[Any]	     =       intermediate_size
       UpperCamelCase     : int	     =       hidden_act
       UpperCamelCase     : Optional[int]	     =       num_labels
       UpperCamelCase     : Union[str, Any]	     =       initializer_range
       UpperCamelCase     : int	     =       out_features
       UpperCamelCase     : Tuple	     =       out_indices
       UpperCamelCase     : Union[str, Any]	     =       scope





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




       UpperCamelCase     : Optional[Any]	     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

       UpperCamelCase     : Tuple	     =       None
       if self.use_labels:
        UpperCamelCase     : List[str]	     =       ids_tensor([self.batch_size]	,							self.num_labels       )

       UpperCamelCase     : Union[str, Any]	     =       self.get_config()
       return config, pixel_values, labels





      def 	__UpperCamelCase(			self       ):
       '''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=A_	,							initializer_range=self.initializer_range	,							out_features=self.out_features	,							out_indices=self.out_indices	,							num_labels=self.num_labels	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       ConvNextModel(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : List[Any]	     =       model(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_       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       ConvNextForImageClassification(A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : List[Any]	     =       model(A_	,							labels=A_       )
       self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.num_labels)       )





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       ConvNextBackbone(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : Tuple	     =       model(A_       )

       # 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
       UpperCamelCase     : Optional[int]	     =       None
       UpperCamelCase     : Dict	     =       ConvNextBackbone(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : int	     =       model(A_       )

       # 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       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       self.prepare_config_and_inputs()
       UpperCamelCase     ,   UpperCamelCase     ,   UpperCamelCase     : Dict	     =       config_and_inputs
       UpperCamelCase     : List[str]	     =       {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class  A__       (	__snake_case	,       __snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :Dict						   =       (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      _UpperCAmelCase     :Any						   =       (
          {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase     :List[str]						   =       True
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :Optional[Any]						   =       False
      _UpperCAmelCase     :Union[str, Any]						   =       False





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




       UpperCamelCase     : str	     =       ConvNextModelTester(self       )
       UpperCamelCase     : Optional[Any]	     =       ConfigTester(self	,							config_class=A_	,							has_text_modality=A_	,							hidden_size=37       )





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




       return





      @unittest.skip(reason="ConvNext does not use inputs_embeds"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





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




       pass





      @unittest.skip(reason="ConvNext does not use feedforward chunking"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





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




       UpperCamelCase     ,   UpperCamelCase     : Optional[Any]	     =       self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase     : Any	     =       ["pixel_values"]
        self.assertListEqual(arg_names[:1]	,							A_       )





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




       UpperCamelCase     : Dict	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_       )





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




       UpperCamelCase     : Any	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*A_       )





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




       def check_hidden_states_output(A_	,							A_	,							A_       ):
        UpperCamelCase     : Any	     =       model_class(A_       )
        model.to(A_       )
        model.eval()

        with torch.no_grad():
         UpperCamelCase     : Union[str, Any]	     =       model(**self._prepare_for_class(A_	,							A_       )       )

        UpperCamelCase     : Dict	     =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        UpperCamelCase     : List[str]	     =       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]	,							)

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

       for model_class in self.all_model_classes:
        UpperCamelCase     : Any	     =       True
        check_hidden_states_output(A_	,							A_	,							A_       )

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

        check_hidden_states_output(A_	,							A_	,							A_       )





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




       UpperCamelCase     : str	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_       )





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




       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase     : int	     =       ConvNextModel.from_pretrained(A_       )
        self.assertIsNotNone(A_       )



def 		A_    (					)						->			Dict:
 UpperCamelCase     : int	     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image



@require_torch
@require_vision
class  A__       (	unittest.TestCase      ):





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




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





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




       UpperCamelCase     : Union[str, Any]	     =       ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"       ).to(A_       )

       UpperCamelCase     : Tuple	     =       self.default_image_processor
       UpperCamelCase     : int	     =       prepare_img()
       UpperCamelCase     : Dict	     =       image_processor(images=A_	,							return_tensors="pt"       ).to(A_       )

       # forward pass
       with torch.no_grad():
        UpperCamelCase     : List[str]	     =       model(**A_       )

       # verify the logits
       UpperCamelCase     : Tuple	     =       torch.Size((1, 1000)       )
       self.assertEqual(outputs.logits.shape	,							A_       )

       UpperCamelCase     : List[str]	     =       torch.tensor([-0.02_60, -0.47_39, 0.19_11]       ).to(A_       )

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



@require_torch
class  A__       (	unittest.TestCase	,       __snake_case      ):
      _UpperCAmelCase     :Optional[Any]						   =       (ConvNextBackbone,) if is_torch_available() else ()
      _UpperCAmelCase     :Optional[int]						   =       ConvNextConfig

      _UpperCAmelCase     :Tuple						   =       False





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




       UpperCamelCase     : int	     =       ConvNextModelTester(self       )







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCamelCase	:					Tuple			  =					logging.get_logger(__name__)



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :List[Any]						   =       'timm_backbone'





      def __init__(			self	,							A_=None	,							A_=3	,							A_=True	,							A_=True	,							A_=None	,							**A_	,							):
       '''simple docstring'''




       super().__init__(**A_       )
       UpperCamelCase     : Tuple	     =       backbone
       UpperCamelCase     : Dict	     =       num_channels
       UpperCamelCase     : Tuple	     =       features_only
       UpperCamelCase     : Optional[int]	     =       use_pretrained_backbone
       UpperCamelCase     : Dict	     =       True
       UpperCamelCase     : List[str]	     =       out_indices if out_indices is not None else (-1,)
