





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    :





     def __init__(     self				,							_UpperCamelCase				,							_UpperCamelCase=13				,							_UpperCamelCase=32				,							_UpperCamelCase=3				,							_UpperCamelCase=4				,							_UpperCamelCase=[10, 20, 30, 40]				,							_UpperCamelCase=[2, 2, 3, 2]				,							_UpperCamelCase=True				,							_UpperCamelCase=True				,							_UpperCamelCase=37				,							_UpperCamelCase="gelu"				,							_UpperCamelCase=10				,							_UpperCamelCase=0.02				,							_UpperCamelCase=["stage2", "stage3", "stage4"]				,							_UpperCamelCase=[2, 3, 4]				,							_UpperCamelCase=None				,							):
        _UpperCAmelCase           =   parent
        _UpperCAmelCase           =   batch_size
        _UpperCAmelCase           =   image_size
        _UpperCAmelCase           =   num_channels
        _UpperCAmelCase           =   num_stages
        _UpperCAmelCase           =   hidden_sizes
        _UpperCAmelCase           =   depths
        _UpperCAmelCase           =   is_training
        _UpperCAmelCase           =   use_labels
        _UpperCAmelCase           =   intermediate_size
        _UpperCAmelCase           =   hidden_act
        _UpperCAmelCase           =   num_labels
        _UpperCAmelCase           =   initializer_range
        _UpperCAmelCase           =   out_features
        _UpperCAmelCase           =   out_indices
        _UpperCAmelCase           =   scope





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

        _UpperCAmelCase           =   self.get_config()

        return config, pixel_values, labels





     def 		UpperCamelCase(     self					):
        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=_UpperCamelCase				,							initializer_range=self.initializer_range				,							out_features=self.out_features				,							out_indices=self.out_indices				,							num_labels=self.num_labels				,							)





     def 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        _UpperCAmelCase           =   ConvNextVaModel(config=_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase					)
        # 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 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        _UpperCAmelCase           =   ConvNextVaForImageClassification(_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase				,							labels=_UpperCamelCase					)
        self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)					)





     def 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        _UpperCAmelCase           =   ConvNextVaBackbone(config=_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase					)

        # 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           =   None
        _UpperCAmelCase           =   ConvNextVaBackbone(config=_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase					)

        # 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 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.prepare_config_and_inputs()
        _UpperCAmelCase       ,      _UpperCAmelCase       ,      _UpperCAmelCase           =   config_and_inputs
        _UpperCAmelCase           =   {'''pixel_values''': pixel_values}
        return config, inputs_dict





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




@require_torch
class 			__UpperCamelCase    (							A__	, A__	, unittest.TestCase    ):
     __A	:  Dict							  =   (
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     __A	:  Union[str, Any]							  =   (
         {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     __A	:  str							  =   False
     __A	:  Dict							  =   False
     __A	:  Any							  =   False
     __A	:  Tuple							  =   False
     __A	:  Optional[Any]							  =   False





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   ConvNextVaModelTester(self					)
        _UpperCAmelCase           =   ConfigTester(self				,							config_class=_UpperCamelCase				,							has_text_modality=_UpperCamelCase				,							hidden_size=37					)





     def 		UpperCamelCase(     self					):
        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 		UpperCamelCase(     self					):
        return





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





     @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''					)
     def 		UpperCamelCase(     self					):
        pass





     @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''					)
     def 		UpperCamelCase(     self					):
        pass





     def 		UpperCamelCase(     self					):
        if not self.model_tester.is_training:
           return

        for model_class in self.all_model_classes:
           _UpperCAmelCase       ,      _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs_with_labels()
           _UpperCAmelCase           =   True

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

           _UpperCAmelCase           =   model_class(_UpperCamelCase					)
           model.to(_UpperCamelCase					)
           model.train()
           _UpperCAmelCase           =   self._prepare_for_class(_UpperCamelCase				,							_UpperCamelCase				,							return_labels=_UpperCamelCase					)
           _UpperCAmelCase           =   model(**_UpperCamelCase					).loss
           loss.backward()





     def 		UpperCamelCase(     self					):
        if not self.model_tester.is_training:
           return

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

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

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





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase       ,      _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs_for_common()

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

           _UpperCAmelCase           =   ['''pixel_values''']
           self.assertListEqual(arg_names[:1]				,							_UpperCamelCase					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_UpperCamelCase					)





     def 		UpperCamelCase(     self					):
        def check_hidden_states_output(_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
           _UpperCAmelCase           =   model_class(_UpperCamelCase					)
           model.to(_UpperCamelCase					)
           model.eval()

           with torch.no_grad():
              _UpperCAmelCase           =   model(**self._prepare_for_class(_UpperCamelCase				,							_UpperCamelCase					)					)

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

           _UpperCAmelCase           =   self.model_tester.num_stages
           self.assertEqual(len(_UpperCamelCase					)				,							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           =   self.model_tester.prepare_config_and_inputs_for_common()

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

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

           check_hidden_states_output(_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase					)





     @slow
     def 		UpperCamelCase(     self					):
        for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _UpperCAmelCase           =   ConvNextVaModel.from_pretrained(_UpperCamelCase					)
           self.assertIsNotNone(_UpperCamelCase					)




def      A__       (    )  ->  str:






   """simple docstring"""







   _UpperCAmelCase           =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
   return image




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





     @cached_property
     def 		UpperCamelCase(     self					):
        return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''					) if is_vision_available() else None





     @slow
     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''					).to(_UpperCamelCase					)

        _UpperCAmelCase           =   self.default_image_processor
        _UpperCAmelCase           =   prepare_img()
        _UpperCAmelCase           =   preprocessor(images=_UpperCamelCase				,							return_tensors='''pt'''					).to(_UpperCamelCase					)

        # forward pass
        with torch.no_grad():
           _UpperCAmelCase           =   model(**_UpperCamelCase					)

        # verify the logits
        _UpperCAmelCase           =   torch.Size((1, 1000)					)
        self.assertEqual(outputs.logits.shape				,							_UpperCamelCase					)

        _UpperCAmelCase           =   torch.tensor([0.9996, 0.1966, -0.4386]					).to(_UpperCamelCase					)
        self.assertTrue(torch.allclose(outputs.logits[0, :3]				,							_UpperCamelCase				,							atol=1e-4					)					)






def      A__       (    SCREAMING_SNAKE_CASE_   :      int = 2_00_00_00						)  ->  int:






   """simple docstring"""







   _UpperCAmelCase           =   [0 for i in range(n + 1						)]
   _UpperCAmelCase           =   1
   _UpperCAmelCase           =   1

   for i in range(2				,	int(n**0.5						) + 1						):
      if primality_list[i] == 0:
         for j in range(i * i				,	n + 1				,	SCREAMING_SNAKE_CASE_						):
            _UpperCAmelCase           =   1
   _UpperCAmelCase           =   0
   for i in range(SCREAMING_SNAKE_CASE_						):
      if primality_list[i] == 0:
         sum_of_primes += i
   return sum_of_primes


if __name__ == "__main__":
   print(f'''{solution() = }''')