



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,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_=13,      SCREAMING_SNAKE_CASE_=32,      SCREAMING_SNAKE_CASE_=3,      SCREAMING_SNAKE_CASE_=4,      SCREAMING_SNAKE_CASE_=[10, 20, 30, 40],      SCREAMING_SNAKE_CASE_=[2, 2, 3, 2],      SCREAMING_SNAKE_CASE_=True,      SCREAMING_SNAKE_CASE_=True,      SCREAMING_SNAKE_CASE_=37,      SCREAMING_SNAKE_CASE_="gelu",      SCREAMING_SNAKE_CASE_=10,      SCREAMING_SNAKE_CASE_=0.02,      SCREAMING_SNAKE_CASE_=["stage2", "stage3", "stage4"],      SCREAMING_SNAKE_CASE_=[2, 3, 4],      SCREAMING_SNAKE_CASE_=None,      )					->		Optional[int]:
          UpperCamelCase   :  Tuple						     =     parent
          UpperCamelCase   :  int						     =     batch_size
          UpperCamelCase   :  Any						     =     image_size
          UpperCamelCase   :  Optional[Any]						     =     num_channels
          UpperCamelCase   :  Optional[Any]						     =     num_stages
          UpperCamelCase   :  Optional[Any]						     =     hidden_sizes
          UpperCamelCase   :  str						     =     depths
          UpperCamelCase   :  Tuple						     =     is_training
          UpperCamelCase   :  Dict						     =     use_labels
          UpperCamelCase   :  Union[str, Any]						     =     intermediate_size
          UpperCamelCase   :  Optional[Any]						     =     hidden_act
          UpperCamelCase   :  Dict						     =     num_labels
          UpperCamelCase   :  List[str]						     =     initializer_range
          UpperCamelCase   :  Optional[Any]						     =     out_features
          UpperCamelCase   :  List[Any]						     =     out_indices
          UpperCamelCase   :  str						     =     scope
       def  snake_case_	(      self	)					->		List[Any]:
          UpperCamelCase   :  Optional[int]						     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

          UpperCamelCase   :  List[str]						     =     self.get_config()

          return config, pixel_values, labels
       def  snake_case_	(      self	)					->		Any:
          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  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		str:
          UpperCamelCase   :  int						     =     ConvNextVaModel(config=_A	)
          model.to(_A	)
          model.eval()
          UpperCamelCase   :  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  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		Optional[int]:
          UpperCamelCase   :  List[str]						     =     ConvNextVaForImageClassification(_A	)
          model.to(_A	)
          model.eval()
          UpperCamelCase   :  int						     =     model(_A,      labels=_A	)
          self.parent.assertEqual(result.logits.shape,      (self.batch_size, self.num_labels)	)
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		Any:
          UpperCamelCase   :  Optional[int]						     =     ConvNextVaBackbone(config=_A	)
          model.to(_A	)
          model.eval()
          UpperCamelCase   :  Optional[Any]						     =     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   :  Dict						     =     ConvNextVaBackbone(config=_A	)
          model.to(_A	)
          model.eval()
          UpperCamelCase   :  int						     =     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  snake_case_	(      self	)					->		Union[str, Any]:
          UpperCamelCase   :  Optional[int]						     =     self.prepare_config_and_inputs()
          UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase   :  Any						     =     config_and_inputs
          UpperCamelCase   :  Tuple						     =     {'pixel_values': pixel_values}
          return config, inputs_dict






       def  snake_case_	(      self	)					->		Optional[int]:
          UpperCamelCase   :  int						     =     self.prepare_config_and_inputs()
          UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase   :  str						     =     config_and_inputs
          UpperCamelCase   :  Tuple						     =     {'pixel_values': pixel_values, 'labels': labels}
          return config, inputs_dict






@require_torch
class     lowerCAmelCase_		(  snake_case__	,   snake_case__	,   unittest.TestCase							):
       UpperCAmelCase__    : str       					=  (
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       UpperCAmelCase__    : Optional[int]       					=  (
           {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       UpperCAmelCase__    : Optional[int]       					=  False
       UpperCAmelCase__    : Dict       					=  False
       UpperCAmelCase__    : Tuple       					=  False
       UpperCAmelCase__    : List[str]       					=  False
       UpperCAmelCase__    : Union[str, Any]       					=  False
       def  snake_case_	(      self	)					->		Dict:
          UpperCamelCase   :  int						     =     ConvNextVaModelTester(self	)
          UpperCamelCase   :  List[str]						     =     ConfigTester(self,      config_class=_A,      has_text_modality=_A,      hidden_size=37	)
       def  snake_case_	(      self	)					->		Union[str, Any]:
          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  snake_case_	(      self	)					->		Dict:
          return
       @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'	)
       def  snake_case_	(      self	)					->		Dict:
          pass
       @unittest.skip(reason='ConvNextV2 does not support input and output embeddings'	)
       def  snake_case_	(      self	)					->		List[Any]:
          pass
       @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'	)
       def  snake_case_	(      self	)					->		Union[str, Any]:
          pass
       def  snake_case_	(      self	)					->		Optional[Any]:



          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   :  List[str]						     =     True

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

             UpperCamelCase   :  List[Any]						     =     model_class(_A	)
             model.to(_A	)
             model.train()
             UpperCamelCase   :  List[Any]						     =     self._prepare_for_class(_A,      _A,      return_labels=_A	)
             UpperCamelCase   :  List[Any]						     =     model(**_A	).loss
             loss.backward()
       def  snake_case_	(      self	)					->		Any:



          if not self.model_tester.is_training:
             return

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

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

             UpperCamelCase   :  Optional[Any]						     =     model_class(_A	)
             model.to(_A	)
             model.gradient_checkpointing_enable()
             model.train()
             UpperCamelCase   :  Optional[Any]						     =     self._prepare_for_class(_A,      _A,      return_labels=_A	)
             UpperCamelCase   :  Optional[Any]						     =     model(**_A	).loss
             loss.backward()
       def  snake_case_	(      self	)					->		Tuple:
          UpperCamelCase     ,					UpperCamelCase   :  int						     =     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   :  str						     =     inspect.signature(model.forward	)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             UpperCamelCase   :  List[str]						     =     [*signature.parameters.keys()]

             UpperCamelCase   :  Union[str, Any]						     =     ['pixel_values']
             self.assertListEqual(arg_names[:1],      _A	)
       def  snake_case_	(      self	)					->		Optional[Any]:
          UpperCamelCase   :  Optional[int]						     =     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_A	)
       def  snake_case_	(      self	)					->		Any:



          def check_hidden_states_output(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	):
             UpperCamelCase   :  Tuple						     =     model_class(_A	)
             model.to(_A	)
             model.eval()

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

             UpperCamelCase   :  Tuple						     =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             UpperCamelCase   :  int						     =     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   :  Optional[Any]						     =     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   :  Optional[Any]						     =     True

             check_hidden_states_output(_A,      _A,      _A	)
       def  snake_case_	(      self	)					->		List[str]:
          UpperCamelCase   :  List[str]						     =     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_A	)






       @slow
       def  snake_case_	(      self	)					->		Tuple:



          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase   :  Optional[int]						     =     ConvNextVaModel.from_pretrained(_A	)
             self.assertIsNotNone(_A	)






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



@require_torch
@require_vision
class     lowerCAmelCase_		(  unittest.TestCase							):
       @cached_property
       def  snake_case_	(      self	)					->		str:
          return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'	) if is_vision_available() else None






       @slow
       def  snake_case_	(      self	)					->		Union[str, Any]:
          UpperCamelCase   :  Union[str, Any]						     =     ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'	).to(_A	)

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

          # forward pass
          with torch.no_grad():
             UpperCamelCase   :  int						     =     model(**_A	)

          # verify the logits
          UpperCamelCase   :  Optional[int]						     =     torch.Size((1, 1000)	)
          self.assertEqual(outputs.logits.shape,      _A	)

          UpperCamelCase   :  List[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	)	)









import re
def 		UpperCamelCase     (       snake_case__	:   str     )     ->					str:

   if len(re.findall('[ATCG]'	,					snake_case__     )     ) != len(snake_case__     ):
      raise ValueError('Invalid Strand'     )

   return dna.translate(dna.maketrans('ATCG'	,					'TAGC'     )     )


if __name__ == "__main__":
    import doctest

    doctest.testmod()



