"""simple docstring"""




import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
     from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor
class 						__A							:






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






     def     __A  (		self  ):
       _lowerCAmelCase						:       Union[str, Any]  			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

       _lowerCAmelCase						:       Dict  			=     self.get_config()
       return config, pixel_values, labels






     def     __A  (		self  ):
       return ConvNextConfig(
           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     __A  (		self				,     a__				,     a__				,     a__  ):
       _lowerCAmelCase						:       Dict  			=     ConvNextModel(config=a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:       Tuple  			=     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     __A  (		self				,     a__				,     a__				,     a__  ):
       _lowerCAmelCase						:       Optional[Any]  			=     ConvNextForImageClassification(a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:       List[Any]  			=     model(a__				,     labels=a__  )
       self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_labels)  )






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







@require_torch
class 						__A							( SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	unittest.TestCase		):
     _UpperCamelCase							:			Tuple							=		(
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     _UpperCamelCase							:			List[Any]							=		(
         {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     _UpperCamelCase							:			Optional[int]							=		True
     _UpperCamelCase							:			List[str]							=		False
     _UpperCamelCase							:			Dict							=		False
     _UpperCamelCase							:			str							=		False
     _UpperCamelCase							:			Dict							=		False






     def     __A  (		self  ):
       _lowerCAmelCase						:       Optional[Any]  			=     ConvNextModelTester(self  )
       _lowerCAmelCase						:       Optional[Any]  			=     ConfigTester(self				,     config_class=a__				,     has_text_modality=a__				,     hidden_size=37  )






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






     @unittest.skip(reason="""ConvNext does not use inputs_embeds"""  )
     def     __A  (		self  ):
       pass






     @unittest.skip(reason="""ConvNext does not support input and output embeddings"""  )
     def     __A  (		self  ):
       pass






     @unittest.skip(reason="""ConvNext does not use feedforward chunking"""  )
     def     __A  (		self  ):
       pass






     def     __A  (		self  ):
       _lowerCAmelCase			,	_lowerCAmelCase						:       Optional[Any]  			=     self.model_tester.prepare_config_and_inputs_for_common()

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

         _lowerCAmelCase						:       Optional[int]  			=     ["""pixel_values"""]
         self.assertListEqual(arg_names[:1]				,     a__  )






     def     __A  (		self  ):
       _lowerCAmelCase						:       List[Any]  			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a__  )






     def     __A  (		self  ):
       _lowerCAmelCase						:       int  			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*a__  )






     def     __A  (		self  ):
       def check_hidden_states_output(a__				,     a__				,     a__  ):
         _lowerCAmelCase						:       Dict  			=     model_class(a__  )
         model.to(a__  )
         model.eval()

         with torch.no_grad():
           _lowerCAmelCase						:       List[str]  			=     model(**self._prepare_for_class(a__				,     a__  )  )

         _lowerCAmelCase						:       Optional[int]  			=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _lowerCAmelCase						:       str  			=     self.model_tester.num_stages
         self.assertEqual(len(a__  )				,     expected_num_stages + 1  )

         # ConvNext'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]				,     )

       _lowerCAmelCase			,	_lowerCAmelCase						:       Optional[Any]  			=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _lowerCAmelCase						:       Optional[int]  			=     True
         check_hidden_states_output(a__				,     a__				,     a__  )

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

         check_hidden_states_output(a__				,     a__				,     a__  )






     def     __A  (		self  ):
       _lowerCAmelCase						:       Optional[int]  			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a__  )






     @slow
     def     __A  (		self  ):
       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowerCAmelCase						:       int  			=     ConvNextModel.from_pretrained(a__  )
         self.assertIsNotNone(a__  )







def 							SCREAMING_SNAKE_CASE     (			)       ->      List[str]:
  _lowerCAmelCase						:       int  			=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
  return image
@require_torch
@require_vision
class 						__A							( unittest.TestCase		):






     @cached_property
     def     __A  (		self  ):
       return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""  ) if is_vision_available() else None






     @slow
     def     __A  (		self  ):
       _lowerCAmelCase						:       Optional[Any]  			=     ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""  ).to(a__  )

       _lowerCAmelCase						:       Dict  			=     self.default_image_processor
       _lowerCAmelCase						:       int  			=     prepare_img()
       _lowerCAmelCase						:       Union[str, Any]  			=     image_processor(images=a__				,     return_tensors="""pt"""  ).to(a__  )

       # forward pass
       with torch.no_grad():
         _lowerCAmelCase						:       int  			=     model(**a__  )

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

       _lowerCAmelCase						:       Tuple  			=     torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]  ).to(a__  )

       self.assertTrue(torch.allclose(outputs.logits[0, :3]				,     a__				,     atol=1e-4  )  )







@require_torch
class 						__A							( unittest.TestCase    ,	SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:			List[str]							=		(ConvNextBackbone,) if is_torch_available() else ()
     _UpperCamelCase							:			int							=		ConvNextConfig

     _UpperCamelCase							:			Dict							=		False






     def     __A  (		self  ):
       _lowerCAmelCase						:       str  			=     ConvNextModelTester(self  )





"""simple docstring"""




from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a      :		List[Any]           =   logging.get_logger(__name__)

_a      :		Any           =   {
    'microsoft/swinv2-tiny-patch4-window8-256': (
        'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'
    ),
}
class 						__A							( SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:			int							=		"swinv2"

     _UpperCamelCase							:			List[str]							=		{
         "num_attention_heads": "num_heads",
         "num_hidden_layers": "num_layers",
     }






     def __init__(		self				,     a__=224				,     a__=4				,     a__=3				,     a__=96				,     a__=[2, 2, 6, 2]				,     a__=[3, 6, 12, 24]				,     a__=7				,     a__=4.0				,     a__=True				,     a__=0.0				,     a__=0.0				,     a__=0.1				,     a__="gelu"				,     a__=False				,     a__=0.0_2				,     a__=1e-5				,     a__=32				,     **a__				,     ):
       super().__init__(**a__  )

       _lowerCAmelCase						:       int  			=     image_size
       _lowerCAmelCase						:       Optional[Any]  			=     patch_size
       _lowerCAmelCase						:       Any  			=     num_channels
       _lowerCAmelCase						:       List[Any]  			=     embed_dim
       _lowerCAmelCase						:       Optional[int]  			=     depths
       _lowerCAmelCase						:       List[Any]  			=     len(a__  )
       _lowerCAmelCase						:       Any  			=     num_heads
       _lowerCAmelCase						:       Tuple  			=     window_size
       _lowerCAmelCase						:       Tuple  			=     mlp_ratio
       _lowerCAmelCase						:       Any  			=     qkv_bias
       _lowerCAmelCase						:       Optional[int]  			=     hidden_dropout_prob
       _lowerCAmelCase						:       Tuple  			=     attention_probs_dropout_prob
       _lowerCAmelCase						:       str  			=     drop_path_rate
       _lowerCAmelCase						:       List[str]  			=     hidden_act
       _lowerCAmelCase						:       List[str]  			=     use_absolute_embeddings
       _lowerCAmelCase						:       Optional[int]  			=     layer_norm_eps
       _lowerCAmelCase						:       List[Any]  			=     initializer_range
       _lowerCAmelCase						:       Any  			=     encoder_stride
       # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
       # this indicates the channel dimension after the last stage of the model
       _lowerCAmelCase						:       Tuple  			=     int(embed_dim * 2 ** (len(a__  ) - 1)  )
       _lowerCAmelCase						:       Tuple  			=     (0, 0, 0, 0)




