


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







    """simple docstring"""




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






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		Optional[Any]      							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

      a						:		List[str]      							=			self.get_config()

      return config, pixel_values, labels






    def 	__snake_case							(					self				:    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 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    Tuple):
      a						:		Tuple      							=			SwinvaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		str      							=			model(__UpperCAmelCase)

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

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

      a						:		int      							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
      a						:		Optional[int]      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape				, (self.batch_size, 1, self.image_size, self.image_size))






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






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		Optional[Any]      							=			self.prepare_config_and_inputs()
      a							,		a							,		a						:		Dict      							=			config_and_inputs
      a						:		Optional[Any]      							=			{"pixel_values": pixel_values}
      return config, inputs_dict






@require_torch
class 						_A  (  _a    ,_a    ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							Any	=       (
        (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
    )
    UpperCAmelCase       :							Dict	=       (
        {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification}
        if is_torch_available()
        else {}
    )

    UpperCAmelCase       :							List[str]	=       False
    UpperCAmelCase       :							Dict	=       False
    UpperCAmelCase       :							Dict	=       False
    UpperCAmelCase       :							Optional[int]	=       False






    def 	__snake_case							(					self				:    Tuple):
      a						:		Optional[int]      							=			SwinvaModelTester(self)
      a						:		Dict      							=			ConfigTester(self				, config_class=__UpperCAmelCase				, embed_dim=37)






    def 	__snake_case							(					self				:    int):
      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				:    Optional[Any]):
      a						:		Any      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0.")
    def 	__snake_case							(					self				:    List[Any]):
      pass






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






    def 	__snake_case							(					self				:    Tuple):
      a							,		a						:		Dict      							=			self.model_tester.prepare_config_and_inputs_for_common()

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






    def 	__snake_case							(					self				:    str):
      a							,		a						:		Optional[Any]      							=			self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Dict      							=			["pixel_values"]
        self.assertListEqual(arg_names[:1]				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    int):
      a							,		a						:		Dict      							=			self.model_tester.prepare_config_and_inputs_for_common()
      a						:		Optional[int]      							=			True

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

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

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

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

        if hasattr(self.model_tester				, "num_hidden_states_types"):
          a						:		Union[str, Any]      							=			self.model_tester.num_hidden_states_types
        else:
          # also another +1 for reshaped_hidden_states
          a						:		Any      							=			2
        self.assertEqual(out_len + added_hidden_states				, len(__UpperCAmelCase))

        a						:		Any      							=			outputs.attentions

        self.assertEqual(len(__UpperCAmelCase)				, __UpperCAmelCase)

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






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    Union[str, Any]):
      a						:		Union[str, Any]      							=			model_class(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()

      with torch.no_grad():
        a						:		Any      							=			model(**self._prepare_for_class(__UpperCAmelCase				, __UpperCAmelCase))

      a						:		Optional[int]      							=			outputs.hidden_states

      a						:		Optional[int]      							=			getattr(
          self.model_tester				, "expected_num_hidden_layers"				, len(self.model_tester.depths) + 1)
      self.assertEqual(len(__UpperCAmelCase)				, __UpperCAmelCase)

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

      a						:		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]				, )

      a						:		Optional[int]      							=			outputs.reshaped_hidden_states
      self.assertEqual(len(__UpperCAmelCase)				, __UpperCAmelCase)

      a							,		a							,		a							,		a						:		str      							=			reshaped_hidden_states[0].shape
      a						:		str      							=			(
          reshaped_hidden_states[0].view(__UpperCAmelCase				, __UpperCAmelCase				, 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):
      a							,		a						:		int      							=			self.model_tester.prepare_config_and_inputs_for_common()

      a						:		Optional[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:
        a						:		str      							=			True
        self.check_hidden_states_output(__UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase)

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

        self.check_hidden_states_output(__UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    Any):
      a							,		a						:		Union[str, Any]      							=			self.model_tester.prepare_config_and_inputs_for_common()
      a						:		Dict      							=			3

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

      a						:		Optional[int]      							=			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
      a						:		str      							=			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

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

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






    def 	__snake_case							(					self				:    int):
      a						:		Optional[Any]      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    List[Any]):
      a						:		Optional[int]      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    @slow
    def 	__snake_case							(					self				:    List[str]):
      for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		Optional[Any]      							=			SwinvaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






    def 	__snake_case							(					self				:    str):
      a							,		a						:		Any      							=			self.model_tester.prepare_config_and_inputs_for_common()

      a						:		Optional[Any]      							=			_config_zero_init(__UpperCAmelCase)
      for model_class in self.all_model_classes:
        a						:		int      							=			model_class(config=__UpperCAmelCase)
        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 						_A  (  unittest.TestCase  ):







    """simple docstring"""




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






    @slow
    def 	__snake_case							(					self				:    Dict):
      a						:		str      							=			SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256").to(
          __UpperCAmelCase)
      a						:		Union[str, Any]      							=			self.default_image_processor

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

      # forward pass
      with torch.no_grad():
        a						:		Any      							=			model(**__UpperCAmelCase)

      # verify the logits
      a						:		str      							=			torch.Size((1, 1000))
      self.assertEqual(outputs.logits.shape				, __UpperCAmelCase)
      a						:		Dict      							=			torch.tensor([-0.3_947, -0.4_306, 0.0_026]).to(__UpperCAmelCase)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]				, __UpperCAmelCase				, atol=1e-4))










"""simple docstring"""







from __future__ import annotations

from numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray


def      lowercase			(				A_  ,   A_  ,   A_ = False       )->      list[float]:
  '''simple docstring'''







  if radian_mode:
    return [magnitude * cos(A_       ), magnitude * sin(A_       )]
  return [magnitude * cos(radians(A_       )       ), magnitude * sin(radians(A_       )       )]


def      lowercase			(				A_  ,   A_  ,   A_ = 10**-1       )->      bool:
  '''simple docstring'''







  a						:		NDArray[floataa]      							=			cross(A_  ,   A_       )
  a						:		float      							=			sum(A_       )
  return abs(A_       ) < eps


if __name__ == "__main__":
 # Test to check if it works
 __lowercase    					=      array(
     [
         polar_force(7_18.4, 180 - 30),
         polar_force(8_79.54, 45),
         polar_force(100, -90),
     ]
 )

 __lowercase    					=      array([[0, 0], [0, 0], [0, 0]])

 assert in_static_equilibrium(forces, location)

 # Problem 1 in image_data/2D_problems.jpg
 __lowercase    					=      array(
     [
         polar_force(30 * 9.81, 15),
         polar_force(215, 180 - 45),
         polar_force(264, 90 - 30),
     ]
 )

 __lowercase    					=      array([[0, 0], [0, 0], [0, 0]])

 assert in_static_equilibrium(forces, location)

 # Problem in image_data/2D_problems_1.jpg
 __lowercase    					=      array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])

 __lowercase    					=      array([[0, 0], [6, 0], [10, 0], [12, 0]])

 assert in_static_equilibrium(forces, location)

 import doctest

 doctest.testmod()






