





"""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      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Union[str, Any]					,   __a   :       str					,   __a   :       Union[str, Any]=13					,   __a   :       str=32					,   __a   :       Any=3					,   __a   :       List[str]=4					,   __a   :       int=[10, 20, 30, 40]					,   __a   :       int=[2, 2, 3, 2]					,   __a   :       Union[str, Any]=True					,   __a   :       str=True					,   __a   :       Dict=37					,   __a   :       Tuple="gelu"					,   __a   :       List[str]=10					,   __a   :       List[str]=0.02					,   __a   :       List[str]=["stage2", "stage3", "stage4"]					,   __a   :       Any=[2, 3, 4]					,   __a   :       List[Any]=None					,   )		->				Dict:
        _UpperCamelCase      :	str						=       parent
        _UpperCamelCase      :	Union[str, Any]						=       batch_size
        _UpperCamelCase      :	Tuple						=       image_size
        _UpperCamelCase      :	Any						=       num_channels
        _UpperCamelCase      :	List[Any]						=       num_stages
        _UpperCamelCase      :	str						=       hidden_sizes
        _UpperCamelCase      :	Union[str, Any]						=       depths
        _UpperCamelCase      :	Union[str, Any]						=       is_training
        _UpperCamelCase      :	Any						=       use_labels
        _UpperCamelCase      :	Optional[int]						=       intermediate_size
        _UpperCamelCase      :	Optional[Any]						=       hidden_act
        _UpperCamelCase      :	List[str]						=       num_labels
        _UpperCamelCase      :	List[str]						=       initializer_range
        _UpperCamelCase      :	List[Any]						=       out_features
        _UpperCamelCase      :	Any						=       out_indices
        _UpperCamelCase      :	Any						=       scope

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Any:
        _UpperCamelCase      :	int						=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

        _UpperCamelCase      :	Optional[int]						=       self.get_config()

        return config, pixel_values, labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        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    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       List[Any]					,   __a   :       Union[str, Any]					,   __a   :       Any	)		->				Union[str, Any]:
        _UpperCamelCase      :	Union[str, Any]						=       ConvNextVaModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Union[str, Any]						=       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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       List[Any]					,   __a   :       Tuple					,   __a   :       str	)		->				Optional[int]:
        _UpperCamelCase      :	Tuple						=       ConvNextVaForImageClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Optional[int]						=       model(__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       List[str]					,   __a   :       List[Any]					,   __a   :       Tuple	)		->				Tuple:
        _UpperCamelCase      :	Union[str, Any]						=       ConvNextVaBackbone(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	List[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      :	Dict						=       None
        _UpperCamelCase      :	str						=       ConvNextVaBackbone(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Union[str, Any]						=       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    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Optional[Any]:
        _UpperCamelCase      :	int						=       self.prepare_config_and_inputs()
        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	int						=       config_and_inputs
        _UpperCamelCase      :	str						=       {"pixel_values": pixel_values}
        return config, inputs_dict


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				List[Any]:
        _UpperCamelCase      :	List[Any]						=       self.prepare_config_and_inputs()
        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	int						=       config_and_inputs
        _UpperCamelCase      :	Optional[int]						=       {"pixel_values": pixel_values, "labels": labels}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


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

  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				List[Any]:
        _UpperCamelCase      :	List[Any]						=       ConvNextVaModelTester(self	)
        _UpperCamelCase      :	Dict						=       ConfigTester(self					,   config_class=__a					,   has_text_modality=__a					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        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    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				str:
        return

  @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        pass

  @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        pass

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Tuple:
        if not self.model_tester.is_training:
              return

        for model_class in self.all_model_classes:
              _UpperCamelCase,  _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs_with_labels()
              _UpperCamelCase      :	Any						=       True

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

              _UpperCamelCase      :	Tuple						=       model_class(__a	)
              model.to(__a	)
              model.train()
              _UpperCamelCase      :	List[str]						=       self._prepare_for_class(__a					,   __a					,   return_labels=__a	)
              _UpperCamelCase      :	Optional[Any]						=       model(**__a	).loss
              loss.backward()

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[int]:
        if not self.model_tester.is_training:
              return

        for model_class in self.all_model_classes:
              _UpperCamelCase,  _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs_with_labels()
              _UpperCamelCase      :	Dict						=       False
              _UpperCamelCase      :	Optional[int]						=       True

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

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				List[Any]:
        _UpperCamelCase,  _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase      :	Tuple						=       ["pixel_values"]
              self.assertListEqual(arg_names[:1]					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Tuple:
        def check_hidden_states_output(__a   :       Optional[Any]					,   __a   :       Optional[Any]					,   __a   :       List[Any]	):
              _UpperCamelCase      :	int						=       model_class(__a	)
              model.to(__a	)
              model.eval()

              with torch.no_grad():
                    _UpperCamelCase      :	List[Any]						=       model(**self._prepare_for_class(__a					,   __a	)	)

              _UpperCamelCase      :	List[Any]						=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _UpperCamelCase      :	Optional[Any]						=       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      :	Dict						=       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Dict						=       True
              check_hidden_states_output(__a					,   __a					,   __a	)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              _UpperCamelCase      :	Optional[int]						=       True

              check_hidden_states_output(__a					,   __a					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__a	)


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Any						=       ConvNextVaModel.from_pretrained(__a	)
              self.assertIsNotNone(__a	)





def 					lowercase__    (					)					->		Dict:




      """simple docstring"""

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



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







  '''simple docstring'''


  @cached_property
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				List[str]:
        return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"	) if is_vision_available() else None


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Union[str, Any]:
        _UpperCamelCase      :	Tuple						=       ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"	).to(__a	)

        _UpperCamelCase      :	List[Any]						=       self.default_image_processor
        _UpperCamelCase      :	Optional[Any]						=       prepare_img()
        _UpperCamelCase      :	List[Any]						=       preprocessor(images=__a					,   return_tensors="pt"	).to(__a	)

        # forward pass
        with torch.no_grad():
              _UpperCamelCase      :	List[str]						=       model(**__a	)

        # verify the logits
        _UpperCamelCase      :	Union[str, Any]						=       torch.Size((1, 1000)	)
        self.assertEqual(outputs.logits.shape					,   __a	)

        _UpperCamelCase      :	Union[str, Any]						=       torch.tensor([0.99_96, 0.19_66, -0.43_86]	).to(__a	)
        self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   __a					,   atol=1e-4	)	)







"""simple docstring"""


import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(".")




def 					lowercase__    (					lowercase_			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       test_file.split(os.path.sep			)
      if components[0:2] != ["tests", "models"]:
            raise ValueError(
                "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got "
                F'''{test_file} instead.'''			)
      _UpperCamelCase      :	str						=       components[-1]
      if not test_fn.endswith("py"			):
            raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.'''			)
      if not test_fn.startswith("test_modeling_"			):
            raise ValueError(
                F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.'''			)

      _UpperCamelCase      :	Dict						=       components[:-1] + [test_fn.replace(".py"		,""			)]
      _UpperCamelCase      :	List[str]						=       ".".join(lowercase_			)

      return test_module_path




def 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_module_path(lowercase_			)
      _UpperCamelCase      :	str						=       importlib.import_module(lowercase_			)

      return test_module




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Union[str, Any]						=       []
      _UpperCamelCase      :	List[Any]						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            if attr.endswith("ModelTester"			):
                  tester_classes.append(getattr(lowercase_		,lowercase_			)			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       []
      _UpperCamelCase      :	Any						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            _UpperCamelCase      :	int						=       getattr(lowercase_		,lowercase_			)
            # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
            # `all_model_classes` is not empty (which also excludes other special classes).
            _UpperCamelCase      :	Optional[Any]						=       getattr(lowercase_		,"all_model_classes"		,[]			)
            if len(lowercase_			) > 0:
                  test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Any:




      """simple docstring"""

      _UpperCamelCase      :	Dict						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	int						=       set()
      for test_class in test_classes:
            model_classes.update(test_class.all_model_classes			)

      # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       test_class()
      if hasattr(lowercase_		,"setUp"			):
            test.setUp()

      _UpperCamelCase      :	Tuple						=       None
      if hasattr(lowercase_		,"model_tester"			):
            # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
            if test.model_tester is not None:
                  _UpperCamelCase      :	Tuple						=       test.model_tester.__class__

      return model_tester




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       get_test_classes(lowercase_			)

      _UpperCamelCase      :	Dict						=       []
      for test_class in test_classes:
            if model_class in test_class.all_model_classes:
                  target_test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Dict:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes_for_model(lowercase_		,lowercase_			)

      _UpperCamelCase      :	List[Any]						=       []
      for test_class in test_classes:
            _UpperCamelCase      :	List[Any]						=       get_model_tester_from_test_class(lowercase_			)
            if tester_class is not None:
                  tester_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {test_class: get_model_tester_from_test_class(lowercase_			) for test_class in test_classes}
      return test_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Optional[int]						=       {
          model_class: get_test_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_test_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {
          model_class: get_tester_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_to_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Optional[int]:




      """simple docstring"""

      if isinstance(lowercase_		,lowercase_			):
            return o
      elif isinstance(lowercase_		,lowercase_			):
            return o.__name__
      elif isinstance(lowercase_		,(list, tuple)			):
            return [to_json(lowercase_			) for x in o]
      elif isinstance(lowercase_		,lowercase_			):
            return {to_json(lowercase_			): to_json(lowercase_			) for k, v in o.items()}
      else:
            return o
