
import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


def     UpperCAmelCase_  (						__lowerCAmelCase	) ->						Any:
    return 1.0 / (1.0 + np.exp(-_outputs	))


def     UpperCAmelCase_  (						__lowerCAmelCase	) ->						str:
    __lowercase		:			Any	    =       np.max(_outputs	,					axis=-1	,					keepdims=__lowerCAmelCase	)
    __lowercase		:			Optional[int]	    =       np.exp(_outputs - maxes	)
    return shifted_exp / shifted_exp.sum(axis=-1	,					keepdims=__lowerCAmelCase	)


class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			int        =    '''sigmoid'''
      A__	:			Optional[Any]        =    '''softmax'''
      A__	:			Union[str, Any]        =    '''none'''






@add_end_docstrings(
    lowerCAmelCase_ , r'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    ''' , )
class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Dict        =    False
      A__	:			str        =    ClassificationFunction.NONE




      def __init__(      self		:       Optional[Any]				,       **_snake_case		:       int				):
          super().__init__(**_snake_case				)

          self.check_model_type(
              TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
              if self.framework == '''tf'''
              else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING				)




      def 		snake_case_			(      self		:       Any				,       _snake_case		:       List[Any]=None				,       _snake_case		:       Optional[Any]=None				,       _snake_case		:       Dict=""				,       **_snake_case		:       str				):
          # Using "" as default argument because we're going to use `top_k=None` in user code to declare
          # "No top_k"
          __lowercase		:			int	    =       tokenizer_kwargs

          __lowercase		:			List[str]	    =       {}
          if hasattr(self.model.config				,       '''return_all_scores'''				) and return_all_scores is None:
              __lowercase		:			Optional[Any]	    =       self.model.config.return_all_scores

          if isinstance(_snake_case				,       _snake_case				) or top_k is None:
              __lowercase		:			int	    =       top_k
              __lowercase		:			str	    =       False
          elif return_all_scores is not None:
              warnings.warn(
                  '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
                  ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''				,       _snake_case				,       )
              if return_all_scores:
                  __lowercase		:			int	    =       None
              else:
                  __lowercase		:			Optional[Any]	    =       1

          if isinstance(_snake_case				,       _snake_case				):
              __lowercase		:			List[str]	    =       ClassificationFunction[function_to_apply.upper()]

          if function_to_apply is not None:
              __lowercase		:			List[Any]	    =       function_to_apply
          return preprocess_params, {}, postprocess_params




      def __call__(      self		:       Any				,       *_snake_case		:       List[Any]				,       **_snake_case		:       Tuple				):
          __lowercase		:			str	    =       super().__call__(*_snake_case				,       **_snake_case				)
          # TODO try and retrieve it in a nicer way from _sanitize_parameters.
          __lowercase		:			Dict	    =       '''top_k''' not in kwargs
          if isinstance(args[0]				,       _snake_case				) and _legacy:
              # This pipeline is odd, and return a list when single item is run
              return [result]
          else:
              return result




      def 		snake_case_			(      self		:       List[Any]				,       _snake_case		:       List[Any]				,       **_snake_case		:       Optional[Any]				):
          __lowercase		:			int	    =       self.framework
          if isinstance(_snake_case				,       _snake_case				):
              return self.tokenizer(**_snake_case				,       return_tensors=_snake_case				,       **_snake_case				)
          elif isinstance(_snake_case				,       _snake_case				) and len(_snake_case				) == 1 and isinstance(inputs[0]				,       _snake_case				) and len(inputs[0]				) == 2:
              # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
              return self.tokenizer(
                  text=inputs[0][0]				,       text_pair=inputs[0][1]				,       return_tensors=_snake_case				,       **_snake_case				)
          elif isinstance(_snake_case				,       _snake_case				):
              # This is likely an invalid usage of the pipeline attempting to pass text pairs.
              raise ValueError(
                  '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
                  ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''				)
          return self.tokenizer(_snake_case				,       return_tensors=_snake_case				,       **_snake_case				)




      def 		snake_case_			(      self		:       List[str]				,       _snake_case		:       Dict				):
          return self.model(**_snake_case				)




      def 		snake_case_			(      self		:       int				,       _snake_case		:       List[str]				,       _snake_case		:       List[str]=None				,       _snake_case		:       Dict=1				,       _snake_case		:       Optional[int]=True				):
          # `_legacy` is used to determine if we're running the naked pipeline and in backward
          # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
          # the more natural result containing the list.
          # Default value before `set_parameters`
          if function_to_apply is None:
              if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                  __lowercase		:			Optional[Any]	    =       ClassificationFunction.SIGMOID
              elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                  __lowercase		:			Dict	    =       ClassificationFunction.SOFTMAX
              elif hasattr(self.model.config				,       '''function_to_apply'''				) and function_to_apply is None:
                  __lowercase		:			Any	    =       self.model.config.function_to_apply
              else:
                  __lowercase		:			Union[str, Any]	    =       ClassificationFunction.NONE

          __lowercase		:			Any	    =       model_outputs['''logits'''][0]
          __lowercase		:			Optional[Any]	    =       outputs.numpy()

          if function_to_apply == ClassificationFunction.SIGMOID:
              __lowercase		:			Union[str, Any]	    =       sigmoid(_snake_case				)
          elif function_to_apply == ClassificationFunction.SOFTMAX:
              __lowercase		:			Optional[int]	    =       softmax(_snake_case				)
          elif function_to_apply == ClassificationFunction.NONE:
              __lowercase		:			List[str]	    =       outputs
          else:
              raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}'				)

          if top_k == 1 and _legacy:
              return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

          __lowercase		:			Union[str, Any]	    =       [
              {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_snake_case				)
          ]
          if not _legacy:
              dict_scores.sort(key=lambda _snake_case				: x["score"]				,       reverse=_snake_case				)
              if top_k is not None:
                  __lowercase		:			Dict	    =       dict_scores[:top_k]
          return dict_scores




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 						__lowerCAmelCase	:



      """simple docstring"""







      def __init__(      self		:       int				,       _snake_case		:       Optional[Any]				,       _snake_case		:       Union[str, Any]=13				,       _snake_case		:       Optional[Any]=32				,       _snake_case		:       str=2				,       _snake_case		:       Optional[Any]=3				,       _snake_case		:       Tuple=16				,       _snake_case		:       Optional[int]=[1, 2, 1]				,       _snake_case		:       Dict=[2, 2, 4]				,       _snake_case		:       int=2				,       _snake_case		:       Any=2.0				,       _snake_case		:       Dict=True				,       _snake_case		:       Optional[Any]=0.0				,       _snake_case		:       Any=0.0				,       _snake_case		:       str=0.1				,       _snake_case		:       List[Any]="gelu"				,       _snake_case		:       str=False				,       _snake_case		:       Optional[int]=True				,       _snake_case		:       Dict=0.02				,       _snake_case		:       List[Any]=1E-5				,       _snake_case		:       Union[str, Any]=True				,       _snake_case		:       int=None				,       _snake_case		:       Optional[Any]=True				,       _snake_case		:       Optional[Any]=10				,       _snake_case		:       List[Any]=8				,       ):
          __lowercase		:			str	    =       parent
          __lowercase		:			Union[str, Any]	    =       batch_size
          __lowercase		:			int	    =       image_size
          __lowercase		:			int	    =       patch_size
          __lowercase		:			Any	    =       num_channels
          __lowercase		:			Optional[int]	    =       embed_dim
          __lowercase		:			List[str]	    =       depths
          __lowercase		:			List[str]	    =       num_heads
          __lowercase		:			Optional[Any]	    =       window_size
          __lowercase		:			Union[str, Any]	    =       mlp_ratio
          __lowercase		:			int	    =       qkv_bias
          __lowercase		:			Tuple	    =       hidden_dropout_prob
          __lowercase		:			List[str]	    =       attention_probs_dropout_prob
          __lowercase		:			Union[str, Any]	    =       drop_path_rate
          __lowercase		:			str	    =       hidden_act
          __lowercase		:			Optional[Any]	    =       use_absolute_embeddings
          __lowercase		:			Union[str, Any]	    =       patch_norm
          __lowercase		:			Any	    =       layer_norm_eps
          __lowercase		:			int	    =       initializer_range
          __lowercase		:			Optional[Any]	    =       is_training
          __lowercase		:			str	    =       scope
          __lowercase		:			Any	    =       use_labels
          __lowercase		:			Union[str, Any]	    =       type_sequence_label_size
          __lowercase		:			Union[str, Any]	    =       encoder_stride




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

          __lowercase		:			str	    =       None
          if self.use_labels:
              __lowercase		:			List[str]	    =       ids_tensor([self.batch_size]				,       self.type_sequence_label_size				)

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

          return config, pixel_values, labels




      def 		snake_case_			(      self		:       Tuple				):
          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 		snake_case_			(      self		:       int				,       _snake_case		:       str				,       _snake_case		:       Union[str, Any]				,       _snake_case		:       int				):
          __lowercase		:			int	    =       SwinvaModel(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			Dict	    =       model(_snake_case				)

          __lowercase		:			Union[str, Any]	    =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths				) - 1))
          __lowercase		:			Union[str, 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 		snake_case_			(      self		:       str				,       _snake_case		:       List[Any]				,       _snake_case		:       str				,       _snake_case		:       str				):
          __lowercase		:			List[Any]	    =       SwinvaForMaskedImageModeling(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			str	    =       model(_snake_case				)
          self.parent.assertEqual(
              result.logits.shape				,       (self.batch_size, self.num_channels, self.image_size, self.image_size)				)

          # test greyscale images
          __lowercase		:			Optional[Any]	    =       1
          __lowercase		:			int	    =       SwinvaForMaskedImageModeling(_snake_case				)
          model.to(_snake_case				)
          model.eval()

          __lowercase		:			List[str]	    =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
          __lowercase		:			Union[str, Any]	    =       model(_snake_case				)
          self.parent.assertEqual(result.logits.shape				,       (self.batch_size, 1, self.image_size, self.image_size)				)




      def 		snake_case_			(      self		:       Dict				,       _snake_case		:       Optional[Any]				,       _snake_case		:       str				,       _snake_case		:       Optional[Any]				):
          __lowercase		:			Any	    =       self.type_sequence_label_size
          __lowercase		:			Optional[Any]	    =       SwinvaForImageClassification(_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			List[str]	    =       model(_snake_case				,       labels=_snake_case				)
          self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.type_sequence_label_size)				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			int	    =       self.prepare_config_and_inputs()
          __lowercase    ,      __lowercase    ,      __lowercase		:			Optional[int]	    =       config_and_inputs
          __lowercase		:			Union[str, Any]	    =       {'''pixel_values''': pixel_values}
          return config, inputs_dict






@require_torch
class 						__lowerCAmelCase	(	lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase      ):



      """simple docstring"""







      A__	:			Optional[Any]        =    (
          (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
      )
      A__	:			Dict        =    (
          {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
          if is_torch_available()
          else {}
      )

      A__	:			Any        =    False
      A__	:			List[str]        =    False
      A__	:			int        =    False
      A__	:			Tuple        =    False




      def 		snake_case_			(      self		:       List[Any]				):
          __lowercase		:			Optional[int]	    =       SwinvaModelTester(self				)
          __lowercase		:			List[Any]	    =       ConfigTester(self				,       config_class=_snake_case				,       embed_dim=37				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          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		:       List[str]				):
          __lowercase		:			Optional[int]	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_snake_case				)




      @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''				)
      def 		snake_case_			(      self		:       Optional[int]				):
          pass




      @unittest.skip(reason='''Swinv2 does not use inputs_embeds'''				)
      def 		snake_case_			(      self		:       Optional[int]				):
          pass




      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase    ,      __lowercase		:			Optional[int]	    =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __lowercase		:			Optional[Any]	    =       model_class(_snake_case				)
              self.assertIsInstance(model.get_input_embeddings()				,       (nn.Module)				)
              __lowercase		:			Tuple	    =       model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(_snake_case				,       nn.Linear				)				)




      def 		snake_case_			(      self		:       List[Any]				):
          __lowercase    ,      __lowercase		:			Tuple	    =       self.model_tester.prepare_config_and_inputs_for_common()

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

              __lowercase		:			List[Any]	    =       ['''pixel_values''']
              self.assertListEqual(arg_names[:1]				,       _snake_case				)




      def 		snake_case_			(      self		:       List[Any]				):
          __lowercase    ,      __lowercase		:			Optional[int]	    =       self.model_tester.prepare_config_and_inputs_for_common()
          __lowercase		:			Dict	    =       True

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

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

              self.assertListEqual(
                  list(attentions[0].shape[-3:]				)				,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,       )
              __lowercase		:			List[Any]	    =       len(_snake_case				)

              # Check attention is always last and order is fine
              __lowercase		:			Dict	    =       True
              __lowercase		:			Dict	    =       True
              __lowercase		:			Optional[Any]	    =       model_class(_snake_case				)
              model.to(_snake_case				)
              model.eval()
              with torch.no_grad():
                  __lowercase		:			Dict	    =       model(**self._prepare_for_class(_snake_case				,       _snake_case				)				)

              if hasattr(self.model_tester				,       '''num_hidden_states_types'''				):
                  __lowercase		:			int	    =       self.model_tester.num_hidden_states_types
              else:
                  # also another +1 for reshaped_hidden_states
                  __lowercase		:			Optional[Any]	    =       2
              self.assertEqual(out_len + added_hidden_states				,       len(_snake_case				)				)

              __lowercase		:			Any	    =       outputs.attentions

              self.assertEqual(len(_snake_case				)				,       _snake_case				)

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




      def 		snake_case_			(      self		:       str				,       _snake_case		:       List[str]				,       _snake_case		:       Optional[Any]				,       _snake_case		:       int				,       _snake_case		:       str				):
          __lowercase		:			List[Any]	    =       model_class(_snake_case				)
          model.to(_snake_case				)
          model.eval()

          with torch.no_grad():
              __lowercase		:			Optional[int]	    =       model(**self._prepare_for_class(_snake_case				,       _snake_case				)				)

          __lowercase		:			Union[str, Any]	    =       outputs.hidden_states

          __lowercase		:			Any	    =       getattr(
              self.model_tester				,       '''expected_num_hidden_layers'''				,       len(self.model_tester.depths				) + 1				)
          self.assertEqual(len(_snake_case				)				,       _snake_case				)

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

          __lowercase		:			Tuple	    =       (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]				,       )

          __lowercase		:			Any	    =       outputs.reshaped_hidden_states
          self.assertEqual(len(_snake_case				)				,       _snake_case				)

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




      def 		snake_case_			(      self		:       int				):
          __lowercase    ,      __lowercase		:			List[Any]	    =       self.model_tester.prepare_config_and_inputs_for_common()

          __lowercase		:			List[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:
              __lowercase		:			List[str]	    =       True
              self.check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				,       _snake_case				)

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

              self.check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       List[Any]				):
          __lowercase    ,      __lowercase		:			Optional[int]	    =       self.model_tester.prepare_config_and_inputs_for_common()
          __lowercase		:			Any	    =       3

          __lowercase		:			Optional[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)
          )
          __lowercase		:			Optional[Any]	    =       (
              config.patch_size
              if isinstance(config.patch_size				,       collections.abc.Iterable				)
              else (config.patch_size, config.patch_size)
          )

          __lowercase		:			Optional[Any]	    =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
          __lowercase		:			Optional[Any]	    =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

          for model_class in self.all_model_classes:
              __lowercase		:			List[Any]	    =       True
              self.check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				,       (padded_height, padded_width)				)

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




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			Any	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			Dict	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_snake_case				)




      @slow
      def 		snake_case_			(      self		:       Dict				):
          for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowercase		:			Optional[Any]	    =       SwinvaModel.from_pretrained(_snake_case				)
              self.assertIsNotNone(_snake_case				)




      def 		snake_case_			(      self		:       str				):
          __lowercase    ,      __lowercase		:			Optional[int]	    =       self.model_tester.prepare_config_and_inputs_for_common()

          __lowercase		:			Optional[int]	    =       _config_zero_init(_snake_case				)
          for model_class in self.all_model_classes:
              __lowercase		:			Tuple	    =       model_class(config=_snake_case				)
              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 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      @cached_property
      def 		snake_case_			(      self		:       str				):
          return (
              AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''				)
              if is_vision_available()
              else None
          )




      @slow
      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			Optional[Any]	    =       SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''				).to(
              _snake_case				)
          __lowercase		:			int	    =       self.default_image_processor

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

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

          # verify the logits
          __lowercase		:			List[str]	    =       torch.Size((1, 1000)				)
          self.assertEqual(outputs.logits.shape				,       _snake_case				)
          __lowercase		:			Optional[Any]	    =       torch.tensor([-0.39_47, -0.43_06, 0.00_26]				).to(_snake_case				)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]				,       _snake_case				,       atol=1E-4				)				)


