



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

      '''simple docstring'''




      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.0_2				,							_A=["stage2", "stage3", "stage4"]				,							_A=[2, 3, 4]				,							_A=None				,							):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= parent
             __SCREAMING_SNAKE_CASE									= batch_size
             __SCREAMING_SNAKE_CASE									= image_size
             __SCREAMING_SNAKE_CASE									= num_channels
             __SCREAMING_SNAKE_CASE									= num_stages
             __SCREAMING_SNAKE_CASE									= hidden_sizes
             __SCREAMING_SNAKE_CASE									= depths
             __SCREAMING_SNAKE_CASE									= is_training
             __SCREAMING_SNAKE_CASE									= use_labels
             __SCREAMING_SNAKE_CASE									= intermediate_size
             __SCREAMING_SNAKE_CASE									= hidden_act
             __SCREAMING_SNAKE_CASE									= num_labels
             __SCREAMING_SNAKE_CASE									= initializer_range
             __SCREAMING_SNAKE_CASE									= out_features
             __SCREAMING_SNAKE_CASE									= out_indices
             __SCREAMING_SNAKE_CASE									= scope






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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






      def 	_A     (   self				,							_A				,							_A				,							_A		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= ConvNextVaModel(config=_a		)
             model.to(_a		)
             model.eval()
             __SCREAMING_SNAKE_CASE									= 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 	_A     (   self				,							_A				,							_A				,							_A		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= ConvNextVaForImageClassification(_a		)
             model.to(_a		)
             model.eval()
             __SCREAMING_SNAKE_CASE									= model(_a				,							labels=_a		)
             self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)		)






      def 	_A     (   self				,							_A				,							_A				,							_A		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= ConvNextVaBackbone(config=_a		)
             model.to(_a		)
             model.eval()
             __SCREAMING_SNAKE_CASE									= 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
             __SCREAMING_SNAKE_CASE									= None
             __SCREAMING_SNAKE_CASE									= ConvNextVaBackbone(config=_a		)
             model.to(_a		)
             model.eval()
             __SCREAMING_SNAKE_CASE									= 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 	_A     (   self		):







             '''simple docstring'''

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






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= self.prepare_config_and_inputs()
             __SCREAMING_SNAKE_CASE									= config_and_inputs
             __SCREAMING_SNAKE_CASE									= {'pixel_values': pixel_values, 'labels': labels}
             return config, inputs_dict







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

      '''simple docstring'''




      UpperCamelCase__      :			Dict      =  (
          (
              ConvNextVaModel,
              ConvNextVaForImageClassification,
              ConvNextVaBackbone,
          )
          if is_torch_available()
          else ()
      )
      UpperCamelCase__      :			Dict      =  (
          {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
          if is_torch_available()
          else {}
      )

      UpperCamelCase__      :			Optional[int]      =  False
      UpperCamelCase__      :			List[str]      =  False
      UpperCamelCase__      :			Tuple      =  False
      UpperCamelCase__      :			List[str]      =  False
      UpperCamelCase__      :			List[Any]      =  False






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= ConvNextVaModelTester(self		)
             __SCREAMING_SNAKE_CASE									= ConfigTester(self				,							config_class=_a				,							has_text_modality=_a				,							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:
                    __SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs_with_labels()
                    __SCREAMING_SNAKE_CASE									= True

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

                    __SCREAMING_SNAKE_CASE									= model_class(_a		)
                    model.to(_a		)
                    model.train()
                    __SCREAMING_SNAKE_CASE									= self._prepare_for_class(_a				,							_a				,							return_labels=_a		)
                    __SCREAMING_SNAKE_CASE									= model(**_a		).loss
                    loss.backward()






      def 	_A     (   self		):







             '''simple docstring'''

             if not self.model_tester.is_training:
                    return

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

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

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






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs_for_common()

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

                    __SCREAMING_SNAKE_CASE									= ['pixel_values']
                    self.assertListEqual(arg_names[:1]				,							_a		)






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_a		)






      def 	_A     (   self		):







             '''simple docstring'''

             def check_hidden_states_output(_A				,							_A				,							_A		):
                    __SCREAMING_SNAKE_CASE									= model_class(_a		)
                    model.to(_a		)
                    model.eval()

                    with torch.no_grad():
                           __SCREAMING_SNAKE_CASE									= model(**self._prepare_for_class(_a				,							_a		)		)

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

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

             __SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    __SCREAMING_SNAKE_CASE									= True
                    check_hidden_states_output(_a				,							_a				,							_a		)

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

                    check_hidden_states_output(_a				,							_a				,							_a		)






      def 	_A     (   self		):







             '''simple docstring'''

             __SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_a		)






      @slow
      def 	_A     (   self		):







             '''simple docstring'''

             for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    __SCREAMING_SNAKE_CASE									= ConvNextVaModel.from_pretrained(_a		)
                    self.assertIsNotNone(_a		)







def      __lowercase       (			)    ->			List[Any]:
       __SCREAMING_SNAKE_CASE									= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
       return image

@require_torch
@require_vision
class        UpperCAmelCase_  (       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'''

             __SCREAMING_SNAKE_CASE									= ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'		).to(_a		)

             __SCREAMING_SNAKE_CASE									= self.default_image_processor
             __SCREAMING_SNAKE_CASE									= prepare_img()
             __SCREAMING_SNAKE_CASE									= preprocessor(images=_a				,							return_tensors='pt'		).to(_a		)

             # forward pass
             with torch.no_grad():
                    __SCREAMING_SNAKE_CASE									= model(**_a		)

             # verify the logits
             __SCREAMING_SNAKE_CASE									= torch.Size((1, 1_000)		)
             self.assertEqual(outputs.logits.shape				,							_a		)

             __SCREAMING_SNAKE_CASE									= torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]		).to(_a		)
             self.assertTrue(torch.allclose(outputs.logits[0, :3]				,							_a				,							atol=1e-4		)		)











def      __lowercase       (			a__       )    ->			int:
							__SCREAMING_SNAKE_CASE									= [[0 for _ in range(a__       )] for _ in range(m + 1       )]
							for i in range(m + 1       ):
														__SCREAMING_SNAKE_CASE									= 1

							for n in range(m + 1       ):
														for k in range(1							,       a__       ):
																					memo[n][k] += memo[n][k - 1]
																					if n - k > 0:
																												memo[n][k] += memo[n - k - 1][k]

							return memo[m][m - 1]


if __name__ == "__main__":
			import sys

			if len(sys.argv) == 1:
						try:
									lowerCAmelCase__		:					Optional[Any]							=int(input('''Enter a number: ''').strip())
									print(partition(n))
						except ValueError:
									print('''Please enter a number.''')
			else:
						try:
									lowerCAmelCase__		:					str							=int(sys.argv[1])
									print(partition(n))
						except ValueError:
									print('''Please pass a number.''')






