


'''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_   :






      def __init__(					self				:    str						,						_A				:    Dict						,						_A				:    str=13						,						_A				:    int=32						,						_A				:    Union[str, Any]=3						,						_A				:    Tuple=4						,						_A				:    List[Any]=[10, 20, 30, 40]						,						_A				:    Optional[int]=[2, 2, 3, 2]						,						_A				:    Optional[Any]=True						,						_A				:    List[Any]=True						,						_A				:    List[Any]=37						,						_A				:    List[Any]="gelu"						,						_A				:    Union[str, Any]=10						,						_A				:    List[str]=0.0_2						,						_A				:    Optional[int]=["stage2", "stage3", "stage4"]						,						_A				:    Optional[int]=[2, 3, 4]						,						_A				:    Union[str, Any]=None						,						):


          '''simple docstring'''


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






      def lowercase_							(					self				:    List[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		int													=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

          UpperCAmelCase__			:		Tuple													=				self.get_config()

          return config, pixel_values, labels






      def lowercase_							(					self				:    List[Any] ):


          '''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 lowercase_							(					self				:    Union[str, Any]						,						_A				:    Tuple						,						_A				:    int						,						_A				:    Optional[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		str													=				ConvNextVaModel(config=_A )
          model.to(_A )
          model.eval()
          UpperCAmelCase__			:		int													=				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 lowercase_							(					self				:    List[str]						,						_A				:    Tuple						,						_A				:    Tuple						,						_A				:    List[str] ):


          '''simple docstring'''


          UpperCAmelCase__			:		str													=				ConvNextVaForImageClassification(_A )
          model.to(_A )
          model.eval()
          UpperCAmelCase__			:		Optional[Any]													=				model(_A						,						labels=_A )
          self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels) )






      def lowercase_							(					self				:    Union[str, Any]						,						_A				:    List[Any]						,						_A				:    int						,						_A				:    List[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Optional[int]													=				ConvNextVaBackbone(config=_A )
          model.to(_A )
          model.eval()
          UpperCAmelCase__			:		str													=				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__			:		Union[str, Any]													=				None
          UpperCAmelCase__			:		Tuple													=				ConvNextVaBackbone(config=_A )
          model.to(_A )
          model.eval()
          UpperCAmelCase__			:		Dict													=				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 lowercase_							(					self				:    List[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Dict													=				self.prepare_config_and_inputs()
          UpperCAmelCase__						,						UpperCAmelCase__						,						UpperCAmelCase__			:		List[str]													=				config_and_inputs
          UpperCAmelCase__			:		Optional[Any]													=				{'''pixel_values''': pixel_values}
          return config, inputs_dict






      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Union[str, Any]													=				self.prepare_config_and_inputs()
          UpperCAmelCase__						,						UpperCAmelCase__						,						UpperCAmelCase__			:		Any													=				config_and_inputs
          UpperCAmelCase__			:		Optional[Any]													=				{'''pixel_values''': pixel_values, '''labels''': labels}
          return config, inputs_dict




@require_torch
class 			lowerCamelCase_   (	__a     ,       __a     ,       unittest.TestCase      ):
      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 lowercase_							(					self				:    Optional[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Optional[Any]													=				ConvNextVaModelTester(self )
          UpperCAmelCase__			:		Optional[int]													=				ConfigTester(self						,						config_class=_A						,						has_text_modality=_A						,						hidden_size=37 )






      def lowercase_							(					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 lowercase_							(					self				:    Union[str, Any] ):


          '''simple docstring'''


          return






      @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' )
      def lowercase_							(					self				:    Tuple ):


          '''simple docstring'''


          pass






      @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' )
      def lowercase_							(					self				:    List[Any] ):


          '''simple docstring'''


          pass






      @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' )
      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          pass






      def lowercase_							(					self				:    Any ):


          '''simple docstring'''


          if not self.model_tester.is_training:
              return

          for model_class in self.all_model_classes:
              UpperCAmelCase__						,						UpperCAmelCase__			:		Optional[int]													=				self.model_tester.prepare_config_and_inputs_with_labels()
              UpperCAmelCase__			:		List[Any]													=				True

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

              UpperCAmelCase__			:		Optional[Any]													=				model_class(_A )
              model.to(_A )
              model.train()
              UpperCAmelCase__			:		Tuple													=				self._prepare_for_class(_A						,						_A						,						return_labels=_A )
              UpperCAmelCase__			:		Optional[Any]													=				model(**_A ).loss
              loss.backward()






      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          if not self.model_tester.is_training:
              return

          for model_class in self.all_model_classes:
              UpperCAmelCase__						,						UpperCAmelCase__			:		Optional[int]													=				self.model_tester.prepare_config_and_inputs_with_labels()
              UpperCAmelCase__			:		Union[str, Any]													=				False
              UpperCAmelCase__			:		Dict													=				True

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

              UpperCAmelCase__			:		List[str]													=				model_class(_A )
              model.to(_A )
              model.gradient_checkpointing_enable()
              model.train()
              UpperCAmelCase__			:		List[str]													=				self._prepare_for_class(_A						,						_A						,						return_labels=_A )
              UpperCAmelCase__			:		Dict													=				model(**_A ).loss
              loss.backward()






      def lowercase_							(					self				:    Tuple ):


          '''simple docstring'''


          UpperCAmelCase__						,						UpperCAmelCase__			:		Any													=				self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase__			:		Tuple													=				['''pixel_values''']
              self.assertListEqual(arg_names[:1]						,						_A )






      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[Any]													=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_A )






      def lowercase_							(					self				:    Dict ):


          '''simple docstring'''


          def check_hidden_states_output(_A				:    List[Any]						,						_A				:    Optional[Any]						,						_A				:    Any ):
              UpperCAmelCase__			:		str													=				model_class(_A )
              model.to(_A )
              model.eval()

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

              UpperCAmelCase__			:		int													=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              UpperCAmelCase__			:		str													=				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]						,						)

          UpperCAmelCase__						,						UpperCAmelCase__			:		int													=				self.model_tester.prepare_config_and_inputs_for_common()

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

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCAmelCase__			:		List[Any]													=				True

              check_hidden_states_output(_A						,						_A						,						_A )






      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[Any]													=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_A )






      @slow
      def lowercase_							(					self				:    str ):


          '''simple docstring'''


          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__			:		str													=				ConvNextVaModel.from_pretrained(_A )
              self.assertIsNotNone(_A )





def 					a__       (					)    ->	Union[str, Any]:
    UpperCAmelCase__			:		int													=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
    return image







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






      @cached_property
      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


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






      @slow
      def lowercase_							(					self				:    Union[str, Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Optional[int]													=				ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_A )

          UpperCAmelCase__			:		Dict													=				self.default_image_processor
          UpperCAmelCase__			:		Dict													=				prepare_img()
          UpperCAmelCase__			:		Optional[Any]													=				preprocessor(images=_A						,						return_tensors='''pt''' ).to(_A )

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

          # verify the logits
          UpperCAmelCase__			:		List[str]													=				torch.Size((1, 1_000) )
          self.assertEqual(outputs.logits.shape						,						_A )

          UpperCAmelCase__			:		Union[str, Any]													=				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 ) )




'''simple docstring'''
import math




class 			lowerCamelCase_   :






      def lowercase_							(					self				:    Optional[Any]						,						_A				:    list[list[float]]						,						_A				:    list[int] ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[str]													=				0.0
          UpperCAmelCase__			:		Union[str, Any]													=				0.0
          for i in range(len(_A ) ):
              da += math.pow((sample[i] - weights[0][i])						,						2 )
              da += math.pow((sample[i] - weights[1][i])						,						2 )
              return 0 if da > da else 1
          return 0






      def lowercase_							(					self				:    Dict						,						_A				:    list[list[int | float]]						,						_A				:    list[int]						,						_A				:    int						,						_A				:    float ):


          '''simple docstring'''


          for i in range(len(_A ) ):
              weights[j][i] += alpha * (sample[i] - weights[j][i])
          return weights





def 					a__       (					)    ->	None:
    # Training Examples ( m, n )
    UpperCAmelCase__			:		Optional[Any]													=				[[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

    # weight initialization ( n, C )
    UpperCAmelCase__			:		str													=				[[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

    # training
    UpperCAmelCase__			:		Optional[Any]													=				SelfOrganizingMap()
    UpperCAmelCase__			:		Tuple													=				3
    UpperCAmelCase__			:		Dict													=				0.5

    for _ in range(lowerCAmelCase__						):
        for j in range(len(lowerCAmelCase__						)						):
            # training sample
            UpperCAmelCase__			:		Optional[int]													=				training_samples[j]

            # Compute the winning vector
            UpperCAmelCase__			:		str													=				self_organizing_map.get_winner(lowerCAmelCase__  ,					lowerCAmelCase__						)

            # Update the winning vector
            UpperCAmelCase__			:		int													=				self_organizing_map.update(lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__						)

    # classify test sample
    UpperCAmelCase__			:		str													=				[0, 0, 0, 1]
    UpperCAmelCase__			:		int													=				self_organizing_map.get_winner(lowerCAmelCase__  ,					lowerCAmelCase__						)

    # results
    print(F"""Clusters that the test sample belongs to : {winner}"""						)
    print(F"""Weights that have been trained : {weights}"""						)


# running the main() function
if __name__ == "__main__":
  main()
