"""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        UpperCamelCase		:
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=13     ,__UpperCamelCase=32     ,__UpperCamelCase=3     ,__UpperCamelCase=4     ,__UpperCamelCase=[10, 20, 30, 40]     ,__UpperCamelCase=[2, 2, 3, 2]     ,__UpperCamelCase=True     ,__UpperCamelCase=True     ,__UpperCamelCase=37     ,__UpperCamelCase="gelu"     ,__UpperCamelCase=10     ,__UpperCamelCase=0.02     ,__UpperCamelCase=["stage2", "stage3", "stage4"]     ,__UpperCamelCase=[2, 3, 4]     ,__UpperCamelCase=None     ,)	->      Any:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	parent
        lowercase_	:				Dict													=	batch_size
        lowercase_	:				List[Any]													=	image_size
        lowercase_	:				int													=	num_channels
        lowercase_	:				List[Any]													=	num_stages
        lowercase_	:				Optional[int]													=	hidden_sizes
        lowercase_	:				str													=	depths
        lowercase_	:				int													=	is_training
        lowercase_	:				List[Any]													=	use_labels
        lowercase_	:				Optional[int]													=	intermediate_size
        lowercase_	:				str													=	hidden_act
        lowercase_	:				Tuple													=	num_labels
        lowercase_	:				Optional[int]													=	initializer_range
        lowercase_	:				str													=	out_features
        lowercase_	:				Any													=	out_indices
        lowercase_	:				Optional[Any]													=	scope
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        lowercase_	:				Union[str, Any]													=	None
        if self.use_labels:
             lowercase_	:				Optional[Any]													=	ids_tensor([self.batch_size]     ,self.num_labels			)

        lowercase_	:				int													=	self.get_config()
        return config, pixel_values, labels
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


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


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	ConvNextModel(config=__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()
        lowercase_	:				Any													=	model(__UpperCamelCase			)
        # 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     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				str													=	ConvNextForImageClassification(__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()
        lowercase_	:				Any													=	model(__UpperCamelCase     ,labels=__UpperCamelCase			)
        self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.num_labels)			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				int													=	ConvNextBackbone(config=__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()
        lowercase_	:				Tuple													=	model(__UpperCamelCase			)

        # 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
        lowercase_	:				str													=	None
        lowercase_	:				List[Any]													=	ConvNextBackbone(config=__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()
        lowercase_	:				str													=	model(__UpperCamelCase			)

        # 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			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Tuple													=	self.prepare_config_and_inputs()
        lowercase_							,  lowercase_							,  lowercase_	:				List[Any]													=	config_and_inputs
        lowercase_	:				Any													=	{'pixel_values': pixel_values}
        return config, inputs_dict







@require_torch
class        UpperCamelCase		(			lowercase_						,      lowercase_						,      unittest.TestCase  ):
   lowercase							=  (
       (
           ConvNextModel,
           ConvNextForImageClassification,
           ConvNextBackbone,
       )
       if is_torch_available()
       else ()
   )
   lowercase							=  (
       {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
       if is_torch_available()
       else {}
   )

   lowercase							=  True
   lowercase							=  False
   lowercase							=  False
   lowercase							=  False
   lowercase							=  False
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	ConvNextModelTester(self			)
        lowercase_	:				Optional[int]													=	ConfigTester(self     ,config_class=__UpperCamelCase     ,has_text_modality=__UpperCamelCase     ,hidden_size=37			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''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			)	->      str:


        '''simple docstring'''


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


        '''simple docstring'''


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


        '''simple docstring'''


        pass
   @unittest.skip(reason='ConvNext does not use feedforward chunking'			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


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


        '''simple docstring'''


        lowercase_							,  lowercase_	:				List[str]													=	self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_	:				Dict													=	['pixel_values']
             self.assertListEqual(arg_names[:1]     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        def check_hidden_states_output(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			):
             lowercase_	:				Dict													=	model_class(__UpperCamelCase			)
             model.to(__UpperCamelCase			)
             model.eval()

             with torch.no_grad():
                  lowercase_	:				List[str]													=	model(**self._prepare_for_class(__UpperCamelCase     ,__UpperCamelCase			)			)

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

             lowercase_	:				Optional[int]													=	self.model_tester.num_stages
             self.assertEqual(len(__UpperCamelCase			)     ,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_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_	:				Any													=	True
             check_hidden_states_output(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)

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

             check_hidden_states_output(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				int													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase			)







   @slow
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_	:				Optional[Any]													=	ConvNextModel.from_pretrained(__UpperCamelCase			)
             self.assertIsNotNone(__UpperCamelCase			)






def 			lowercase__(       ):
     lowercase_	:				Tuple													=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
     return image







@require_torch
@require_vision
class        UpperCamelCase		(			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			)	->      int:


        '''simple docstring'''


        lowercase_	:				List[str]													=	ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'			).to(__UpperCamelCase			)

        lowercase_	:				Tuple													=	self.default_image_processor
        lowercase_	:				List[Any]													=	prepare_img()
        lowercase_	:				Union[str, Any]													=	image_processor(images=__UpperCamelCase     ,return_tensors='pt'			).to(__UpperCamelCase			)

        # forward pass
        with torch.no_grad():
             lowercase_	:				Optional[Any]													=	model(**__UpperCamelCase			)

        # verify the logits
        lowercase_	:				Optional[Any]													=	torch.Size((1, 1000)			)
        self.assertEqual(outputs.logits.shape     ,__UpperCamelCase			)

        lowercase_	:				List[Any]													=	torch.tensor([-0.0260, -0.4739, 0.1911]			).to(__UpperCamelCase			)

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







@require_torch
class        UpperCamelCase		(			unittest.TestCase						,      lowercase_  ):
   lowercase							=  (ConvNextBackbone,) if is_torch_available() else ()
   lowercase							=  ConvNextConfig

   lowercase							=  False
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				List[str]													=	ConvNextModelTester(self			)


"""simple docstring"""







from __future__ import annotations



def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     list      ):
     if not nums:
          raise ValueError('List is empty'      )
     return sum(__SCREAMING_SNAKE_CASE      ) / len(__SCREAMING_SNAKE_CASE      )


if __name__ == "__main__":
       import doctest

       doctest.testmod()

