





"""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      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


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

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Any:
        _UpperCamelCase      :	Optional[Any]						=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

        _UpperCamelCase      :	int						=       self.get_config()

        return config, pixel_values, labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				List[str]:
        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    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]					,   __a   :       Union[str, Any]					,   __a   :       Union[str, Any]					,   __a   :       Dict	)		->				Optional[Any]:
        _UpperCamelCase      :	List[Any]						=       SwinvaModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Optional[Any]						=       model(__a	)

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

        # test greyscale images
        _UpperCamelCase      :	List[Any]						=       1
        _UpperCamelCase      :	Tuple						=       SwinvaForMaskedImageModeling(__a	)
        model.to(__a	)
        model.eval()

        _UpperCamelCase      :	Dict						=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
        _UpperCamelCase      :	int						=       model(__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, 1, self.image_size, self.image_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       Union[str, Any]					,   __a   :       Optional[int]					,   __a   :       str	)		->				List[Any]:
        _UpperCamelCase      :	int						=       self.type_sequence_label_size
        _UpperCamelCase      :	Any						=       SwinvaForImageClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	List[str]						=       model(__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				int:
        _UpperCamelCase      :	Dict						=       self.prepare_config_and_inputs()
        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	Any						=       config_and_inputs
        _UpperCamelCase      :	Union[str, Any]						=       {"pixel_values": pixel_values}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:List[str]	     =					(
      (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
  )
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					(
      {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__							:Optional[Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Dict	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        _UpperCamelCase      :	List[str]						=       SwinvaModelTester(self	)
        _UpperCamelCase      :	List[Any]						=       ConfigTester(self					,   config_class=__a					,   embed_dim=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Tuple:
        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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				List[Any]:
        _UpperCamelCase      :	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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				List[str]:
        pass

  @unittest.skip(reason="Swinv2 does not use inputs_embeds"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Any:
        pass

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        _UpperCamelCase,  _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Union[str, Any]:
        _UpperCamelCase,  _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase      :	List[str]						=       ["pixel_values"]
              self.assertListEqual(arg_names[:1]					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				str:
        _UpperCamelCase,  _UpperCamelCase      :	List[str]						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	int						=       True

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

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              _UpperCamelCase      :	Union[str, Any]						=       True
              _UpperCamelCase      :	str						=       config.window_size**2
              _UpperCamelCase      :	List[str]						=       model_class(__a	)
              model.to(__a	)
              model.eval()
              with torch.no_grad():
                    _UpperCamelCase      :	Optional[Any]						=       model(**self._prepare_for_class(__a					,   __a	)	)
              _UpperCamelCase      :	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]					,   )
              _UpperCamelCase      :	Any						=       len(__a	)

              # Check attention is always last and order is fine
              _UpperCamelCase      :	Dict						=       True
              _UpperCamelCase      :	List[str]						=       True
              _UpperCamelCase      :	int						=       model_class(__a	)
              model.to(__a	)
              model.eval()
              with torch.no_grad():
                    _UpperCamelCase      :	str						=       model(**self._prepare_for_class(__a					,   __a	)	)

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

              _UpperCamelCase      :	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    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]					,   __a   :       str					,   __a   :       List[str]					,   __a   :       int					,   __a   :       str	)		->				int:
        _UpperCamelCase      :	Optional[int]						=       model_class(__a	)
        model.to(__a	)
        model.eval()

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

        _UpperCamelCase      :	Tuple						=       outputs.hidden_states

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

        _UpperCamelCase      :	Any						=       (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]					,   )

        _UpperCamelCase      :	List[str]						=       outputs.reshaped_hidden_states
        self.assertEqual(len(__a	)					,   __a	)

        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	List[str]						=       reshaped_hidden_states[0].shape
        _UpperCamelCase      :	Dict						=       (
            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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				str:
        _UpperCamelCase,  _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase      :	int						=       (
            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:
              _UpperCamelCase      :	Union[str, Any]						=       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"]
              _UpperCamelCase      :	Tuple						=       True

              self.check_hidden_states_output(__a					,   __a					,   __a					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Optional[int]:
        _UpperCamelCase,  _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	List[Any]						=       3

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

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

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Dict						=       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"]
              _UpperCamelCase      :	Optional[Any]						=       True
              self.check_hidden_states_output(__a					,   __a					,   __a					,   (padded_height, padded_width)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__a	)

  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Dict:
        for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Tuple						=       SwinvaModel.from_pretrained(__a	)
              self.assertIsNotNone(__a	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				List[str]:
        _UpperCamelCase,  _UpperCamelCase      :	Optional[int]						=       self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase      :	List[str]						=       _config_zero_init(__a	)
        for model_class in self.all_model_classes:
              _UpperCamelCase      :	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      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  @cached_property
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        return (
            AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256"	)
            if is_vision_available()
            else None
        )


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Tuple:
        _UpperCamelCase      :	Optional[Any]						=       SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256"	).to(
            __a	)
        _UpperCamelCase      :	Optional[int]						=       self.default_image_processor

        _UpperCamelCase      :	List[str]						=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
        _UpperCamelCase      :	Any						=       image_processor(images=__a					,   return_tensors="pt"	).to(__a	)

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

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







"""simple docstring"""


class      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Optional[Any]					,   __a   :       list[int]	)		->				None:
        _UpperCamelCase      :	Tuple						=       len(__a	)
        _UpperCamelCase      :	Dict						=       [0] * len_array

        if len_array > 0:
              _UpperCamelCase      :	Optional[Any]						=       array[0]

        for i in range(1					,   __a	):
              _UpperCamelCase      :	Tuple						=       self.prefix_sum[i - 1] + array[i]

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       int					,   __a   :       int	)		->				int:
        if start == 0:
              return self.prefix_sum[end]

        return self.prefix_sum[end] - self.prefix_sum[start - 1]


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       int	)		->				bool:
        _UpperCamelCase      :	int						=       {0}
        for sum_item in self.prefix_sum:
              if sum_item - target_sum in sums:
                    return True

              sums.add(__a	)

        return False


if __name__ == "__main__":
  import doctest

  doctest.testmod()
