






"""simple docstring"""





import collections
import inspect
import unittest

from transformers import SwinvaConfig
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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
    from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class      _lowercase :


      def __init__(    self				:	int							,   a				:	Optional[int]							,   a				:	str=1_3							,   a				:	Union[str, Any]=3_2							,   a				:	Optional[int]=2							,   a				:	str=3							,   a				:	Tuple=1_6							,   a				:	str=[1, 2, 1]							,   a				:	Optional[Any]=[2, 2, 4]							,   a				:	str=2							,   a				:	List[Any]=2.0							,   a				:	int=True							,   a				:	str=0.0							,   a				:	Optional[Any]=0.0							,   a				:	Optional[int]=0.1							,   a				:	Tuple="gelu"							,   a				:	List[Any]=False							,   a				:	Tuple=True							,   a				:	List[Any]=0.0_2							,   a				:	List[str]=1e-5							,   a				:	List[Any]=True							,   a				:	Any=None							,   a				:	List[str]=True							,   a				:	Any=1_0							,   a				:	List[str]=8							,   ):





            """simple docstring"""







            __snake_case      :    Optional[int]  			=parent
            __snake_case      :    List[str]  			=batch_size
            __snake_case      :    List[Any]  			=image_size
            __snake_case      :    Optional[int]  			=patch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    int  			=embed_dim
            __snake_case      :    List[Any]  			=depths
            __snake_case      :    int  			=num_heads
            __snake_case      :    Optional[Any]  			=window_size
            __snake_case      :    Dict  			=mlp_ratio
            __snake_case      :    Any  			=qkv_bias
            __snake_case      :    List[str]  			=hidden_dropout_prob
            __snake_case      :    Dict  			=attention_probs_dropout_prob
            __snake_case      :    List[Any]  			=drop_path_rate
            __snake_case      :    str  			=hidden_act
            __snake_case      :    Dict  			=use_absolute_embeddings
            __snake_case      :    int  			=patch_norm
            __snake_case      :    Optional[Any]  			=layer_norm_eps
            __snake_case      :    Union[str, Any]  			=initializer_range
            __snake_case      :    Union[str, Any]  			=is_training
            __snake_case      :    Any  			=scope
            __snake_case      :    Any  			=use_labels
            __snake_case      :    Optional[Any]  			=type_sequence_label_size
            __snake_case      :    Dict  			=encoder_stride


      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[str]  			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

            __snake_case      :    List[Any]  			=None
            if self.use_labels:
                  __snake_case      :    Optional[Any]  			=ids_tensor([self.batch_size]							,   self.type_sequence_label_size						)

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

            return config, pixel_values, labels


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            return SwinvaConfig(
                image_size=self.image_size							,   patch_size=self.patch_size							,   num_channels=self.num_channels							,   embed_dim=self.embed_dim							,   depths=self.depths							,   num_heads=self.num_heads							,   window_size=self.window_size							,   mlp_ratio=self.mlp_ratio							,   qkv_bias=self.qkv_bias							,   hidden_dropout_prob=self.hidden_dropout_prob							,   attention_probs_dropout_prob=self.attention_probs_dropout_prob							,   drop_path_rate=self.drop_path_rate							,   hidden_act=self.hidden_act							,   use_absolute_embeddings=self.use_absolute_embeddings							,   path_norm=self.patch_norm							,   layer_norm_eps=self.layer_norm_eps							,   initializer_range=self.initializer_range							,   encoder_stride=self.encoder_stride							,   )


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	List[Any]							,   a				:	Dict							,   a				:	Any						):





            """simple docstring"""







            __snake_case      :    Optional[int]  			=SwinvaModel(config=a						)
            model.to(a						)
            model.eval()
            __snake_case      :    int  			=model(a						)

            __snake_case      :    int  			=((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
            __snake_case      :    Any  			=int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

            self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, expected_seq_len, expected_dim)						)


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	Optional[int]							,   a				:	Dict							,   a				:	Any						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=SwinvaForMaskedImageModeling(config=a						)
            model.to(a						)
            model.eval()
            __snake_case      :    int  			=model(a						)
            self.parent.assertEqual(
                result.logits.shape							,   (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

            # test greyscale images
            __snake_case      :    Union[str, Any]  			=1
            __snake_case      :    Optional[int]  			=SwinvaForMaskedImageModeling(a						)
            model.to(a						)
            model.eval()

            __snake_case      :    Tuple  			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
            __snake_case      :    Dict  			=model(a						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, 1, self.image_size, self.image_size)						)


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	Union[str, Any]							,   a				:	Any							,   a				:	Tuple						):





            """simple docstring"""







            __snake_case      :    List[str]  			=self.type_sequence_label_size
            __snake_case      :    Optional[int]  			=SwinvaForImageClassification(a						)
            model.to(a						)
            model.eval()
            __snake_case      :    int  			=model(a							,   labels=a						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.type_sequence_label_size)						)







      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.prepare_config_and_inputs()
            __snake_case			,				__snake_case			,				__snake_case      :    List[Any]  			=config_and_inputs
            __snake_case      :    int  			={'''pixel_values''': pixel_values}
            return config, inputs_dict



@require_torch
class      _lowercase (     lowerCAmelCase		,  lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   (
          (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
      )
      _a   :     str								=   (
          {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
          if is_torch_available()
          else {}
      )

      _a   :     List[str]								=   False
      _a   :     Optional[Any]								=   False
      _a   :     int								=   False
      _a   :     Optional[Any]								=   False


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            __snake_case      :    List[str]  			=SwinvaModelTester(self						)
            __snake_case      :    Union[str, Any]  			=ConfigTester(self							,   config_class=a							,   embed_dim=3_7						)


      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







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





            """simple docstring"""







            __snake_case      :    Union[str, Any]  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*a						)


      @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''						)
      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @unittest.skip(reason='''Swinv2 does not use inputs_embeds'''						)
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            pass


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Optional[int]  			=self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __snake_case      :    List[Any]  			=model_class(a						)
                  self.assertIsInstance(model.get_input_embeddings()							,   (nn.Module)						)
                  __snake_case      :    Union[str, Any]  			=model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(a							,   nn.Linear						)						)


      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs_for_common()

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

                  __snake_case      :    Optional[Any]  			=['''pixel_values''']
                  self.assertListEqual(arg_names[:1]							,   a						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    List[str]  			=self.model_tester.prepare_config_and_inputs_for_common()
            __snake_case      :    Union[str, Any]  			=True

            for model_class in self.all_model_classes:
                  __snake_case      :    Tuple  			=True
                  __snake_case      :    Optional[int]  			=False
                  __snake_case      :    List[Any]  			=True
                  __snake_case      :    List[str]  			=model_class(a						)
                  model.to(a						)
                  model.eval()
                  with torch.no_grad():
                        __snake_case      :    Optional[int]  			=model(**self._prepare_for_class(a							,   a						)						)
                  __snake_case      :    Tuple  			=outputs.attentions
                  __snake_case      :    Tuple  			=len(self.model_tester.depths						)
                  self.assertEqual(len(a						)							,   a						)

                  # check that output_attentions also work using config
                  del inputs_dict["output_attentions"]
                  __snake_case      :    Optional[int]  			=True
                  __snake_case      :    Tuple  			=config.window_size**2
                  __snake_case      :    Tuple  			=model_class(a						)
                  model.to(a						)
                  model.eval()
                  with torch.no_grad():
                        __snake_case      :    str  			=model(**self._prepare_for_class(a							,   a						)						)
                  __snake_case      :    Union[str, Any]  			=outputs.attentions
                  self.assertEqual(len(a						)							,   a						)

                  self.assertListEqual(
                      list(attentions[0].shape[-3:]						)							,   [self.model_tester.num_heads[0], window_size_squared, window_size_squared]							,   )
                  __snake_case      :    str  			=len(a						)

                  # Check attention is always last and order is fine
                  __snake_case      :    List[Any]  			=True
                  __snake_case      :    List[Any]  			=True
                  __snake_case      :    str  			=model_class(a						)
                  model.to(a						)
                  model.eval()
                  with torch.no_grad():
                        __snake_case      :    Tuple  			=model(**self._prepare_for_class(a							,   a						)						)

                  if hasattr(self.model_tester							,   '''num_hidden_states_types'''						):
                        __snake_case      :    Any  			=self.model_tester.num_hidden_states_types
                  else:
                        # also another +1 for reshaped_hidden_states
                        __snake_case      :    int  			=2
                  self.assertEqual(out_len + added_hidden_states							,   len(a						)						)

                  __snake_case      :    Optional[Any]  			=outputs.attentions

                  self.assertEqual(len(a						)							,   a						)

                  self.assertListEqual(
                      list(self_attentions[0].shape[-3:]						)							,   [self.model_tester.num_heads[0], window_size_squared, window_size_squared]							,   )


      def _UpperCamelCase						(    self				:	Optional[Any]							,   a				:	Any							,   a				:	str							,   a				:	int							,   a				:	str						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=model_class(a						)
            model.to(a						)
            model.eval()

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

            __snake_case      :    str  			=outputs.hidden_states

            __snake_case      :    List[Any]  			=getattr(
                self.model_tester							,   '''expected_num_hidden_layers'''							,   len(self.model_tester.depths						) + 1						)
            self.assertEqual(len(a						)							,   a						)

            # Swinv2 has a different seq_length
            __snake_case      :    List[Any]  			=(
                config.patch_size
                if isinstance(config.patch_size							,   collections.abc.Iterable						)
                else (config.patch_size, config.patch_size)
            )

            __snake_case      :    str  			=(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

            self.assertListEqual(
                list(hidden_states[0].shape[-2:]						)							,   [num_patches, self.model_tester.embed_dim]							,   )

            __snake_case      :    List[Any]  			=outputs.reshaped_hidden_states
            self.assertEqual(len(a						)							,   a						)

            __snake_case			,				__snake_case			,				__snake_case			,				__snake_case      :    List[str]  			=reshaped_hidden_states[0].shape
            __snake_case      :    Tuple  			=(
                reshaped_hidden_states[0].view(a							,   a							,   height * width						).permute(0							,   2							,   1						)
            )
            self.assertListEqual(
                list(reshaped_hidden_states.shape[-2:]						)							,   [num_patches, self.model_tester.embed_dim]							,   )


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs_for_common()

            __snake_case      :    str  			=(
                self.model_tester.image_size
                if isinstance(self.model_tester.image_size							,   collections.abc.Iterable						)
                else (self.model_tester.image_size, self.model_tester.image_size)
            )

            for model_class in self.all_model_classes:
                  __snake_case      :    int  			=True
                  self.check_hidden_states_output(a							,   a							,   a							,   a						)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  __snake_case      :    str  			=True

                  self.check_hidden_states_output(a							,   a							,   a							,   a						)


      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs_for_common()
            __snake_case      :    Dict  			=3

            __snake_case      :    Any  			=(
                self.model_tester.image_size
                if isinstance(self.model_tester.image_size							,   collections.abc.Iterable						)
                else (self.model_tester.image_size, self.model_tester.image_size)
            )
            __snake_case      :    List[str]  			=(
                config.patch_size
                if isinstance(config.patch_size							,   collections.abc.Iterable						)
                else (config.patch_size, config.patch_size)
            )

            __snake_case      :    List[Any]  			=image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
            __snake_case      :    Tuple  			=image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

            for model_class in self.all_model_classes:
                  __snake_case      :    int  			=True
                  self.check_hidden_states_output(a							,   a							,   a							,   (padded_height, padded_width)						)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  __snake_case      :    Any  			=True
                  self.check_hidden_states_output(a							,   a							,   a							,   (padded_height, padded_width)						)


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case      :    Union[str, Any]  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*a						)


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    str  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*a						)


      @slow
      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __snake_case      :    List[Any]  			=SwinvaModel.from_pretrained(a						)
                  self.assertIsNotNone(a						)







      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Any  			=self.model_tester.prepare_config_and_inputs_for_common()

            __snake_case      :    List[Any]  			=_config_zero_init(a						)
            for model_class in self.all_model_classes:
                  __snake_case      :    List[Any]  			=model_class(config=a						)
                  for name, param in model.named_parameters():
                        if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
                              self.assertIn(
                                  ((param.data.mean() * 1e9).round() / 1e9).item()							,   [0.0, 1.0]							,   msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''							,   )



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


      @cached_property
      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return (
                AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''						)
                if is_vision_available()
                else None
            )







      @slow
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Any  			=SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''						).to(
                a						)
            __snake_case      :    Optional[Any]  			=self.default_image_processor

            __snake_case      :    Optional[int]  			=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
            __snake_case      :    str  			=image_processor(images=a							,   return_tensors='''pt'''						).to(a						)

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

            # verify the logits
            __snake_case      :    Any  			=torch.Size((1, 1_0_0_0)						)
            self.assertEqual(outputs.logits.shape							,   a						)
            __snake_case      :    int  			=torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6]						).to(a						)
            self.assertTrue(torch.allclose(outputs.logits[0, :3]							,   a							,   atol=1e-4						)						)










"""simple docstring"""





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


UpperCamelCase_	:				Optional[int]										= logging.get_logger(__name__)

UpperCamelCase_	:				Union[str, Any]										= {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""}


class      _lowercase (     lowerCAmelCase						):
      _a   :     str								=   '''ctrl'''
      _a   :     Optional[int]								=   ['''past_key_values''']
      _a   :     List[Any]								=   {
          '''max_position_embeddings''': '''n_positions''',
          '''hidden_size''': '''n_embd''',
          '''num_attention_heads''': '''n_head''',
          '''num_hidden_layers''': '''n_layer''',
      }


      def __init__(    self				:	str							,   a				:	Optional[int]=2_4_6_5_3_4							,   a				:	Optional[int]=2_5_6							,   a				:	Optional[int]=1_2_8_0							,   a				:	Any=8_1_9_2							,   a				:	int=4_8							,   a				:	Optional[Any]=1_6							,   a				:	str=0.1							,   a				:	str=0.1							,   a				:	Any=1e-6							,   a				:	Optional[int]=0.0_2							,   a				:	int=True							,   **a				:	str							,   ):





            """simple docstring"""







            __snake_case      :    Tuple  			=vocab_size
            __snake_case      :    Optional[Any]  			=n_positions
            __snake_case      :    List[Any]  			=n_embd
            __snake_case      :    Any  			=n_layer
            __snake_case      :    Any  			=n_head
            __snake_case      :    str  			=dff
            __snake_case      :    List[str]  			=resid_pdrop
            __snake_case      :    str  			=embd_pdrop
            __snake_case      :    Union[str, Any]  			=layer_norm_epsilon
            __snake_case      :    List[Any]  			=initializer_range

            __snake_case      :    Any  			=use_cache

            super().__init__(**a						)


