

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

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






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

  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[Any]        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

   UpperCAmelCase__       :	Union[str, Any]        =       self.get_config()

   return config, pixel_values, labels

  def  __lowercase							(	self		:      int     ):






   '''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		:      str       ,A		:      List[Any]       ,A		:      Union[str, Any]       ,A		:      Optional[Any]     ):






   '''simple docstring'''
   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  __lowercase							(	self		:      Union[str, Any]       ,A		:      Union[str, Any]       ,A		:      Optional[Any]       ,A		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Dict        =       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  __lowercase							(	self		:      int       ,A		:      Optional[int]       ,A		:      Optional[int]       ,A		:      Union[str, Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       ConvNextVaBackbone(config=A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	Tuple        =       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__       :	List[Any]        =       None
   UpperCAmelCase__       :	str        =       ConvNextVaBackbone(config=A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	str        =       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		:      str     ):






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




  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Any        =       self.prepare_config_and_inputs()
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	int        =       config_and_inputs
   UpperCAmelCase__       :	Dict        =       {"""pixel_values""": pixel_values, """labels""": labels}
   return config, inputs_dict







@require_torch
class   __lowercase      (     __lowerCamelCase						,      __lowerCamelCase						,      unittest.TestCase       ):
  snake_case_												=							(
      (
          ConvNextVaModel,
          ConvNextVaForImageClassification,
          ConvNextVaBackbone,
      )
      if is_torch_available()
      else ()
  )
  snake_case_												=							(
      {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
      if is_torch_available()
      else {}
  )

  snake_case_												=							False
  snake_case_												=							False
  snake_case_												=							False
  snake_case_												=							False
  snake_case_												=							False

  def  __lowercase							(	self		:      Tuple     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Tuple        =       ConvNextVaModelTester(self     )
   UpperCAmelCase__       :	Any        =       ConfigTester(self       ,config_class=A       ,has_text_modality=A       ,hidden_size=37     )

  def  __lowercase							(	self		:      List[str]     ):






   '''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		:      List[str]     ):






   '''simple docstring'''
   return

  @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds"""     )
  def  __lowercase							(	self		:      Union[str, Any]     ):






   '''simple docstring'''
   pass

  @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings"""     )
  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   pass

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






   '''simple docstring'''
   pass

  def  __lowercase							(	self		:      List[Any]     ):






   '''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__       :	int        =       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[Any]        =       self._prepare_for_class(A       ,A       ,return_labels=A     )
    UpperCAmelCase__       :	Optional[int]        =       model(**A     ).loss
    loss.backward()

  def  __lowercase							(	self		:      Tuple     ):






   '''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__       :	int        =       False
    UpperCAmelCase__       :	List[Any]        =       True

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

    UpperCAmelCase__       :	Dict        =       model_class(A     )
    model.to(A     )
    model.gradient_checkpointing_enable()
    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'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    UpperCAmelCase__       :	List[Any]        =       model_class(A     )
    UpperCAmelCase__       :	Any        =       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  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[int]        =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*A     )

  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   def check_hidden_states_output(A		:      Optional[Any]       ,A		:      Union[str, Any]       ,A		:      str     ):
    UpperCAmelCase__       :	List[str]        =       model_class(A     )
    model.to(A     )
    model.eval()

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

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

    UpperCAmelCase__       :	List[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__       :	Any        =       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__       :	Tuple        =       True

    check_hidden_states_output(A       ,A       ,A     )

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*A     )




  @slow
  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    UpperCAmelCase__       :	Tuple        =       ConvNextVaModel.from_pretrained(A     )
    self.assertIsNotNone(A     )







def 	lowerCAmelCase    (       ):
 '''simple docstring'''





 UpperCAmelCase__       :	List[str]        =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
 return image







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

  @cached_property
  def  __lowercase							(	self		:      int     ):






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




  @slow
  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""     ).to(A     )

   UpperCAmelCase__       :	Any        =       self.default_image_processor
   UpperCAmelCase__       :	str        =       prepare_img()
   UpperCAmelCase__       :	List[Any]        =       preprocessor(images=A       ,return_tensors="""pt"""     ).to(A     )

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__       :	Optional[int]        =       model(**A     )

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

   UpperCAmelCase__       :	Optional[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     )     )









import baseaa





def 						_lowerCAmelCase							(     _lowerCAmelCase			)    ->						bytes:


						'''simple docstring'''






						return baseaa.baaencode(string.encode("utf-8"			)			)





def 						_lowerCAmelCase							(     _lowerCAmelCase			)    ->						str:


						'''simple docstring'''






						return baseaa.baadecode(_lowerCAmelCase			).decode("utf-8"			)


if __name__ == "__main__":
	A				:       Dict      =  'Hello World!'
	A				:       Any      =  baseaa_encode(test)
	print(encoded)

	A				:       Optional[int]      =  baseaa_decode(encoded)
	print(decoded)





