

"""simple docstring"""





import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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_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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
   from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor




class 					_lowerCAmelCase  :







 """simple docstring"""







 def __init__(			self							:			Optional[int],					UpperCAmelCase__							:			List[str],					UpperCAmelCase__							:			Tuple=1_3,					UpperCAmelCase__							:			str=3_2,					UpperCAmelCase__							:			Optional[int]=3,					UpperCAmelCase__							:			int=4,					UpperCAmelCase__							:			str=[1_0, 2_0, 3_0, 4_0],					UpperCAmelCase__							:			Optional[Any]=[2, 2, 3, 2],					UpperCAmelCase__							:			List[Any]=True,					UpperCAmelCase__							:			Tuple=True,					UpperCAmelCase__							:			Optional[int]=3_7,					UpperCAmelCase__							:			Optional[Any]="gelu",					UpperCAmelCase__							:			int=1_0,					UpperCAmelCase__							:			Optional[int]=0.02,					UpperCAmelCase__							:			Union[str, Any]=["stage2", "stage3", "stage4"],					UpperCAmelCase__							:			Tuple=[2, 3, 4],					UpperCAmelCase__							:			Optional[Any]=None,					):
    __lowercase								=						parent
    __lowercase								=						batch_size
    __lowercase								=						image_size
    __lowercase								=						num_channels
    __lowercase								=						num_stages
    __lowercase								=						hidden_sizes
    __lowercase								=						depths
    __lowercase								=						is_training
    __lowercase								=						use_labels
    __lowercase								=						intermediate_size
    __lowercase								=						hidden_act
    __lowercase								=						num_labels
    __lowercase								=						initializer_range
    __lowercase								=						out_features
    __lowercase								=						out_indices
    __lowercase								=						scope


 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

    __lowercase								=						self.get_config()

    return config, pixel_values, labels


 def 					_lowercase (			self							:			Tuple	):
    return ConvNextVaConfig(
        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 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			Any,					UpperCAmelCase__							:			List[str],					UpperCAmelCase__							:			Any	):
    __lowercase								=						ConvNextVaModel(config=UpperCAmelCase__	)
    model.to(UpperCAmelCase__	)
    model.eval()
    __lowercase								=						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 // 3_2, self.image_size // 3_2),					)


 def 					_lowercase (			self							:			Union[str, Any],					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Tuple	):
    __lowercase								=						ConvNextVaForImageClassification(UpperCAmelCase__	)
    model.to(UpperCAmelCase__	)
    model.eval()
    __lowercase								=						model(UpperCAmelCase__,					labels=UpperCAmelCase__	)
    self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_labels)	)


 def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			Dict	):
    __lowercase								=						ConvNextVaBackbone(config=UpperCAmelCase__	)
    model.to(UpperCAmelCase__	)
    model.eval()
    __lowercase								=						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								=						None
    __lowercase								=						ConvNextVaBackbone(config=UpperCAmelCase__	)
    model.to(UpperCAmelCase__	)
    model.eval()
    __lowercase								=						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 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						self.prepare_config_and_inputs()
    __lowercase		,__lowercase		,__lowercase								=						config_and_inputs
    __lowercase								=						{"pixel_values": pixel_values}
    return config, inputs_dict



 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						self.prepare_config_and_inputs()
    __lowercase		,__lowercase		,__lowercase								=						config_and_inputs
    __lowercase								=						{"pixel_values": pixel_values, "labels": labels}
    return config, inputs_dict







@require_torch
class 					_lowerCAmelCase  (	lowercase     ,lowercase     ,unittest.TestCase   ):







 """simple docstring"""







 __UpperCAmelCase	:					Any   		=	(
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 __UpperCAmelCase	:					Optional[Any]   		=	(
     {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 __UpperCAmelCase	:					int   		=	False
 __UpperCAmelCase	:					int   		=	False
 __UpperCAmelCase	:					Union[str, Any]   		=	False
 __UpperCAmelCase	:					Union[str, Any]   		=	False
 __UpperCAmelCase	:					Optional[Any]   		=	False


 def 					_lowercase (			self							:			Any	):
    __lowercase								=						ConvNextVaModelTester(self	)
    __lowercase								=						ConfigTester(self,					config_class=UpperCAmelCase__,					has_text_modality=UpperCAmelCase__,					hidden_size=3_7	)


 def 					_lowercase (			self							:			Dict	):
    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 					_lowercase (			self							:			Tuple	):
    return


 @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"	)
 def 					_lowercase (			self							:			Any	):
    pass


 @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"	)
 def 					_lowercase (			self							:			Dict	):
    pass


 @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"	)
 def 					_lowercase (			self							:			Tuple	):
    pass


 def 					_lowercase (			self							:			Dict	):
    if not self.model_tester.is_training:
       return

    for model_class in self.all_model_classes:
       __lowercase		,__lowercase								=						self.model_tester.prepare_config_and_inputs_with_labels()
       __lowercase								=						True

       if model_class.__name__ in [
           *get_values(UpperCAmelCase__	),
           *get_values(UpperCAmelCase__	),
       ]:
          continue

       __lowercase								=						model_class(UpperCAmelCase__	)
       model.to(UpperCAmelCase__	)
       model.train()
       __lowercase								=						self._prepare_for_class(UpperCAmelCase__,					UpperCAmelCase__,					return_labels=UpperCAmelCase__	)
       __lowercase								=						model(**UpperCAmelCase__	).loss
       loss.backward()


 def 					_lowercase (			self							:			List[str]	):
    if not self.model_tester.is_training:
       return

    for model_class in self.all_model_classes:
       __lowercase		,__lowercase								=						self.model_tester.prepare_config_and_inputs_with_labels()
       __lowercase								=						False
       __lowercase								=						True

       if (
           model_class.__name__
           in [*get_values(UpperCAmelCase__	), *get_values(UpperCAmelCase__	)]
           or not model_class.supports_gradient_checkpointing
       ):
          continue

       __lowercase								=						model_class(UpperCAmelCase__	)
       model.to(UpperCAmelCase__	)
       model.gradient_checkpointing_enable()
       model.train()
       __lowercase								=						self._prepare_for_class(UpperCAmelCase__,					UpperCAmelCase__,					return_labels=UpperCAmelCase__	)
       __lowercase								=						model(**UpperCAmelCase__	).loss
       loss.backward()


 def 					_lowercase (			self							:			Optional[int]	):
    __lowercase		,__lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()

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

       __lowercase								=						["pixel_values"]
       self.assertListEqual(arg_names[:1],					UpperCAmelCase__	)


 def 					_lowercase (			self							:			int	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCAmelCase__	)


 def 					_lowercase (			self							:			List[str]	):
    def check_hidden_states_output(UpperCAmelCase__							:			int,					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			Dict	):
       __lowercase								=						model_class(UpperCAmelCase__	)
       model.to(UpperCAmelCase__	)
       model.eval()

       with torch.no_grad():
          __lowercase								=						model(**self._prepare_for_class(UpperCAmelCase__,					UpperCAmelCase__	)	)

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

       __lowercase								=						self.model_tester.num_stages
       self.assertEqual(len(UpperCAmelCase__	),					expected_num_stages + 1	)

       # ConvNextV2'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								=						self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowercase								=						True
       check_hidden_states_output(UpperCAmelCase__,					UpperCAmelCase__,					UpperCAmelCase__	)

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

       check_hidden_states_output(UpperCAmelCase__,					UpperCAmelCase__,					UpperCAmelCase__	)


 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__	)



 @slow
 def 					_lowercase (			self							:			Optional[Any]	):
    for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowercase								=						ConvNextVaModel.from_pretrained(UpperCAmelCase__	)
       self.assertIsNotNone(UpperCAmelCase__	)







def   _A  (  )	->						Optional[int]:
   '''simple docstring'''


   __lowercase								=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
   return image




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







 """simple docstring"""







 @cached_property
 def 					_lowercase (			self							:			str	):
    return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"	) if is_vision_available() else None



 @slow
 def 					_lowercase (			self							:			Any	):
    __lowercase								=						ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"	).to(UpperCAmelCase__	)

    __lowercase								=						self.default_image_processor
    __lowercase								=						prepare_img()
    __lowercase								=						preprocessor(images=UpperCAmelCase__,					return_tensors="pt"	).to(UpperCAmelCase__	)

    # forward pass
    with torch.no_grad():
       __lowercase								=						model(**UpperCAmelCase__	)

    # verify the logits
    __lowercase								=						torch.Size((1, 1_0_0_0)	)
    self.assertEqual(outputs.logits.shape,					UpperCAmelCase__	)

    __lowercase								=						torch.tensor([0.9_996, 0.1_966, -0.4_386]	).to(UpperCAmelCase__	)
    self.assertTrue(torch.allclose(outputs.logits[0, :3],					UpperCAmelCase__,					atol=1E-4	)	)







"""simple docstring"""





def   _A  (  UpperCamelCase_     :       list[int])	->						float:
   '''simple docstring'''


   if not nums:  # Makes sure that the list is not empty
      raise ValueError("List is empty")

   __lowercase								=						sum(UpperCamelCase_) / len(UpperCamelCase_)  # Calculate the average
   return sum(abs(x - average) for x in nums) / len(UpperCamelCase_)


if __name__ == "__main__":
   import doctest

   doctest.testmod()




