



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




       """simple docstring"""






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

             """simple docstring"""





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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

             UpperCAmelCase_  :	Optional[int]				      =		None
             if self.use_labels:
                   UpperCAmelCase_  :	str				      =		ids_tensor([self.batch_size]     ,self.num_labels)

             UpperCAmelCase_  :	Any				      =		self.get_config()

             return config, pixel_values, labels



       def  A_   (     self):

             """simple docstring"""





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



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		ConvNextVaModel(config=lowercase)
             model.to(lowercase)
             model.eval()
             UpperCAmelCase_  :	Tuple				      =		model(lowercase)
             # 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  A_   (     self     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		ConvNextVaForImageClassification(lowercase)
             model.to(lowercase)
             model.eval()
             UpperCAmelCase_  :	List[Any]				      =		model(lowercase     ,labels=lowercase)
             self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.num_labels))



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		ConvNextVaBackbone(config=lowercase)
             model.to(lowercase)
             model.eval()
             UpperCAmelCase_  :	Optional[Any]				      =		model(lowercase)

             # 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_  :	int				      =		None
             UpperCAmelCase_  :	List[Any]				      =		ConvNextVaBackbone(config=lowercase)
             model.to(lowercase)
             model.eval()
             UpperCAmelCase_  :	List[Any]				      =		model(lowercase)

             # 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  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		self.prepare_config_and_inputs()
             UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_  :	Tuple				      =		config_and_inputs
             UpperCAmelCase_  :	Tuple				      =		{"pixel_values": pixel_values}
             return config, inputs_dict



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		self.prepare_config_and_inputs()
             UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_  :	Any				      =		config_and_inputs
             UpperCAmelCase_  :	Optional[int]				      =		{"pixel_values": pixel_values, "labels": labels}
             return config, inputs_dict


@require_torch
class   snake_case_ (lowercase__ , lowercase__ , unittest.TestCase  ):




       """simple docstring"""






       _lowerCamelCase			    =				(
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       _lowerCamelCase			    =				(
           {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		ConvNextVaModelTester(self)
             UpperCAmelCase_  :	List[Any]				      =		ConfigTester(self     ,config_class=lowercase     ,has_text_modality=lowercase     ,hidden_size=37)



       def  A_   (     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  A_   (     self):

             """simple docstring"""





             return



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

             """simple docstring"""





             pass



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

             """simple docstring"""





             pass



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

             """simple docstring"""





             pass



       def  A_   (     self):

             """simple docstring"""





             if not self.model_tester.is_training:
                   return

             for model_class in self.all_model_classes:
                   UpperCAmelCase_      ,      UpperCAmelCase_  :	str				      =		self.model_tester.prepare_config_and_inputs_with_labels()
                   UpperCAmelCase_  :	Dict				      =		True

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

                   UpperCAmelCase_  :	Any				      =		model_class(lowercase)
                   model.to(lowercase)
                   model.train()
                   UpperCAmelCase_  :	Tuple				      =		self._prepare_for_class(lowercase     ,lowercase     ,return_labels=lowercase)
                   UpperCAmelCase_  :	Union[str, Any]				      =		model(**lowercase).loss
                   loss.backward()



       def  A_   (     self):

             """simple docstring"""





             if not self.model_tester.is_training:
                   return

             for model_class in self.all_model_classes:
                   UpperCAmelCase_      ,      UpperCAmelCase_  :	int				      =		self.model_tester.prepare_config_and_inputs_with_labels()
                   UpperCAmelCase_  :	Tuple				      =		False
                   UpperCAmelCase_  :	int				      =		True

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

                   UpperCAmelCase_  :	List[Any]				      =		model_class(lowercase)
                   model.to(lowercase)
                   model.gradient_checkpointing_enable()
                   model.train()
                   UpperCAmelCase_  :	int				      =		self._prepare_for_class(lowercase     ,lowercase     ,return_labels=lowercase)
                   UpperCAmelCase_  :	Optional[int]				      =		model(**lowercase).loss
                   loss.backward()



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_      ,      UpperCAmelCase_  :	List[Any]				      =		self.model_tester.prepare_config_and_inputs_for_common()

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

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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[Any]				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase)



       def  A_   (     self):

             """simple docstring"""





             def check_hidden_states_output(lowercase     ,lowercase     ,lowercase):
                   UpperCAmelCase_  :	int				      =		model_class(lowercase)
                   model.to(lowercase)
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_  :	Tuple				      =		model(**self._prepare_for_class(lowercase     ,lowercase))

                   UpperCAmelCase_  :	Optional[int]				      =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

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

             for model_class in self.all_model_classes:
                   UpperCAmelCase_  :	Dict				      =		True
                   check_hidden_states_output(lowercase     ,lowercase     ,lowercase)

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

                   check_hidden_states_output(lowercase     ,lowercase     ,lowercase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Union[str, Any]				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase)



       @slow
       def  A_   (     self):

             """simple docstring"""





             for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_  :	int				      =		ConvNextVaModel.from_pretrained(lowercase)
                   self.assertIsNotNone(lowercase)







def    _snake_case (       )     ->     List[Any]:






      '''simple docstring'''







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





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




       """simple docstring"""






       @cached_property
       def  A_   (     self):

             """simple docstring"""





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



       @slow
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224").to(lowercase)

             UpperCAmelCase_  :	Optional[int]				      =		self.default_image_processor
             UpperCAmelCase_  :	Optional[int]				      =		prepare_img()
             UpperCAmelCase_  :	Optional[int]				      =		preprocessor(images=lowercase     ,return_tensors="pt").to(lowercase)

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_  :	Dict				      =		model(**lowercase)

             # verify the logits
             UpperCAmelCase_  :	List[Any]				      =		torch.Size((1, 1000))
             self.assertEqual(outputs.logits.shape     ,lowercase)

             UpperCAmelCase_  :	Optional[Any]				      =		torch.tensor([0.9996, 0.1966, -0.4386]).to(lowercase)
             self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,lowercase     ,atol=1E-4))





def    _snake_case (       __snake_case					,  __snake_case					,  __snake_case    )     ->     list:






      '''simple docstring'''







      UpperCAmelCase_  :	Any				      =		len(__snake_case    )
      UpperCAmelCase_  :	Tuple				      =		[[0] * n for i in range(__snake_case    )]
      for i in range(__snake_case    ):
            UpperCAmelCase_  :	Optional[Any]				      =		y_points[i]

      for i in range(2					,  __snake_case    ):
            for j in range(__snake_case					,  __snake_case    ):
                  UpperCAmelCase_  :	int				      =		(
                      (xa - x_points[j - i + 1]) * q[j][i - 1]
                      - (xa - x_points[j]) * q[j - 1][i - 1]
                  ) / (x_points[j] - x_points[j - i + 1])

      return [q[n - 1][n - 1], q]


if __name__ == "__main__":
   import doctest

   doctest.testmod()
