

'''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			:					Union[str, Any]					,      lowercase_			:					Optional[Any]					,      lowercase_			:					Optional[Any]=13					,      lowercase_			:					int=32					,      lowercase_			:					Optional[Any]=2					,      lowercase_			:					List[Any]=3					,      lowercase_			:					Optional[int]=16					,      lowercase_			:					List[str]=[1, 2, 1]					,      lowercase_			:					Optional[Any]=[2, 2, 4]					,      lowercase_			:					List[Any]=2					,      lowercase_			:					Dict=2.0					,      lowercase_			:					List[Any]=True					,      lowercase_			:					Any=0.0					,      lowercase_			:					Any=0.0					,      lowercase_			:					Union[str, Any]=0.1					,      lowercase_			:					List[str]="gelu"					,      lowercase_			:					int=False					,      lowercase_			:					List[Any]=True					,      lowercase_			:					Optional[Any]=0.02					,      lowercase_			:					Tuple=1E-5					,      lowercase_			:					str=True					,      lowercase_			:					List[Any]=None					,      lowercase_			:					int=True					,      lowercase_			:					str=10					,      lowercase_			:					Union[str, Any]=8					,      )						->     Union[str, Any]:
      UpperCAmelCase	:     Any						 =			parent
      UpperCAmelCase	:     Optional[int]						 =			batch_size
      UpperCAmelCase	:     List[Any]						 =			image_size
      UpperCAmelCase	:     int						 =			patch_size
      UpperCAmelCase	:     Tuple						 =			num_channels
      UpperCAmelCase	:     Optional[int]						 =			embed_dim
      UpperCAmelCase	:     Dict						 =			depths
      UpperCAmelCase	:     Tuple						 =			num_heads
      UpperCAmelCase	:     List[str]						 =			window_size
      UpperCAmelCase	:     Tuple						 =			mlp_ratio
      UpperCAmelCase	:     Optional[Any]						 =			qkv_bias
      UpperCAmelCase	:     List[Any]						 =			hidden_dropout_prob
      UpperCAmelCase	:     Dict						 =			attention_probs_dropout_prob
      UpperCAmelCase	:     List[Any]						 =			drop_path_rate
      UpperCAmelCase	:     Tuple						 =			hidden_act
      UpperCAmelCase	:     Union[str, Any]						 =			use_absolute_embeddings
      UpperCAmelCase	:     Tuple						 =			patch_norm
      UpperCAmelCase	:     str						 =			layer_norm_eps
      UpperCAmelCase	:     Dict						 =			initializer_range
      UpperCAmelCase	:     List[str]						 =			is_training
      UpperCAmelCase	:     Tuple						 =			scope
      UpperCAmelCase	:     Optional[int]						 =			use_labels
      UpperCAmelCase	:     Optional[Any]						 =			type_sequence_label_size
      UpperCAmelCase	:     List[Any]						 =			encoder_stride


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

      UpperCAmelCase	:     Tuple						 =			None
      if self.use_labels:
       UpperCAmelCase	:     Tuple						 =			ids_tensor([self.batch_size]					,      self.type_sequence_label_size	)

      UpperCAmelCase	:     int						 =			self.get_config()

      return config, pixel_values, labels


     def        UpperCAmelCase_	(		self			:					Any	)						->     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        UpperCAmelCase_	(		self			:					str					,      lowercase_			:					Dict					,      lowercase_			:					Dict					,      lowercase_			:					Optional[int]	)						->     Union[str, Any]:
      UpperCAmelCase	:     Union[str, Any]						 =			SwinvaModel(config=lowercase_	)
      model.to(lowercase_	)
      model.eval()
      UpperCAmelCase	:     str						 =			model(lowercase_	)

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

      # test greyscale images
      UpperCAmelCase	:     Optional[Any]						 =			1
      UpperCAmelCase	:     Tuple						 =			SwinvaForMaskedImageModeling(lowercase_	)
      model.to(lowercase_	)
      model.eval()

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


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




     def        UpperCAmelCase_	(		self			:					Optional[int]	)						->     int:
      UpperCAmelCase	:     List[Any]						 =			self.prepare_config_and_inputs()
      UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase	:     List[Any]						 =			config_and_inputs
      UpperCAmelCase	:     Optional[Any]						 =			{'pixel_values': pixel_values}
      return config, inputs_dict




@require_torch
class 	A_			(    _snake_case	,       _snake_case	,       unittest.TestCase							):






     '''simple docstring'''



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

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


     def        UpperCAmelCase_	(		self			:					Optional[int]	)						->     Any:
      UpperCAmelCase	:     Union[str, Any]						 =			SwinvaModelTester(self	)
      UpperCAmelCase	:     Tuple						 =			ConfigTester(self					,      config_class=lowercase_					,      embed_dim=37	)


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


     @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'	)
     def        UpperCAmelCase_	(		self			:					Optional[Any]	)						->     str:
      pass


     @unittest.skip(reason='Swinv2 does not use inputs_embeds'	)
     def        UpperCAmelCase_	(		self			:					Tuple	)						->     int:
      pass


     def        UpperCAmelCase_	(		self			:					List[Any]	)						->     Dict:
      UpperCAmelCase ,			UpperCAmelCase	:     Any						 =			self.model_tester.prepare_config_and_inputs_for_common()

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


     def        UpperCAmelCase_	(		self			:					List[str]	)						->     Optional[Any]:
      UpperCAmelCase ,			UpperCAmelCase	:     Tuple						 =			self.model_tester.prepare_config_and_inputs_for_common()

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

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


     def        UpperCAmelCase_	(		self			:					Optional[Any]	)						->     Optional[int]:
      UpperCAmelCase ,			UpperCAmelCase	:     Dict						 =			self.model_tester.prepare_config_and_inputs_for_common()
      UpperCAmelCase	:     Optional[Any]						 =			True

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

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

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

       # Check attention is always last and order is fine
       UpperCAmelCase	:     str						 =			True
       UpperCAmelCase	:     str						 =			True
       UpperCAmelCase	:     Optional[int]						 =			model_class(lowercase_	)
       model.to(lowercase_	)
       model.eval()
       with torch.no_grad():
        UpperCAmelCase	:     Tuple						 =			model(**self._prepare_for_class(lowercase_					,      lowercase_	)	)

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

       UpperCAmelCase	:     str						 =			outputs.attentions

       self.assertEqual(len(lowercase_	)					,      lowercase_	)

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


     def        UpperCAmelCase_	(		self			:					List[str]					,      lowercase_			:					List[str]					,      lowercase_			:					Optional[Any]					,      lowercase_			:					Dict					,      lowercase_			:					Any	)						->     Tuple:
      UpperCAmelCase	:     str						 =			model_class(lowercase_	)
      model.to(lowercase_	)
      model.eval()

      with torch.no_grad():
       UpperCAmelCase	:     Dict						 =			model(**self._prepare_for_class(lowercase_					,      lowercase_	)	)

      UpperCAmelCase	:     str						 =			outputs.hidden_states

      UpperCAmelCase	:     Optional[Any]						 =			getattr(
          self.model_tester					,      'expected_num_hidden_layers'					,      len(self.model_tester.depths	) + 1	)
      self.assertEqual(len(lowercase_	)					,      lowercase_	)

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

      UpperCAmelCase	:     List[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(lowercase_	)					,      lowercase_	)

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


     def        UpperCAmelCase_	(		self			:					int	)						->     List[Any]:
      UpperCAmelCase ,			UpperCAmelCase	:     List[str]						 =			self.model_tester.prepare_config_and_inputs_for_common()

      UpperCAmelCase	:     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:
       UpperCAmelCase	:     Any						 =			True
       self.check_hidden_states_output(lowercase_					,      lowercase_					,      lowercase_					,      lowercase_	)

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

       self.check_hidden_states_output(lowercase_					,      lowercase_					,      lowercase_					,      lowercase_	)


     def        UpperCAmelCase_	(		self			:					int	)						->     Optional[int]:
      UpperCAmelCase ,			UpperCAmelCase	:     str						 =			self.model_tester.prepare_config_and_inputs_for_common()
      UpperCAmelCase	:     str						 =			3

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

      UpperCAmelCase	:     Tuple						 =			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	:     Optional[Any]						 =			True
       self.check_hidden_states_output(lowercase_					,      lowercase_					,      lowercase_					,      (padded_height, padded_width)	)

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


     def        UpperCAmelCase_	(		self			:					Dict	)						->     List[str]:
      UpperCAmelCase	:     str						 =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_	)


     def        UpperCAmelCase_	(		self			:					Optional[int]	)						->     Dict:
      UpperCAmelCase	:     Optional[Any]						 =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowercase_	)


     @slow
     def        UpperCAmelCase_	(		self			:					Optional[int]	)						->     Optional[Any]:
      for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase	:     int						 =			SwinvaModel.from_pretrained(lowercase_	)
       self.assertIsNotNone(lowercase_	)




     def        UpperCAmelCase_	(		self			:					List[str]	)						->     str:
      UpperCAmelCase ,			UpperCAmelCase	:     List[str]						 =			self.model_tester.prepare_config_and_inputs_for_common()

      UpperCAmelCase	:     str						 =			_config_zero_init(lowercase_	)
      for model_class in self.all_model_classes:
       UpperCAmelCase	:     List[Any]						 =			model_class(config=lowercase_	)
       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        UpperCAmelCase_	(		self			:					Optional[int]	)						->     Dict:
      return (
          AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256'	)
          if is_vision_available()
          else None
      )




     @slow
     def        UpperCAmelCase_	(		self			:					str	)						->     Any:
      UpperCAmelCase	:     Dict						 =			SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256'	).to(
          lowercase_	)
      UpperCAmelCase	:     List[str]						 =			self.default_image_processor

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

      # forward pass
      with torch.no_grad():
       UpperCAmelCase	:     int						 =			model(**lowercase_	)

      # verify the logits
      UpperCAmelCase	:     Union[str, Any]						 =			torch.Size((1, 1_000)	)
      self.assertEqual(outputs.logits.shape					,      lowercase_	)
      UpperCAmelCase	:     Optional[Any]						 =			torch.tensor([-0.3947, -0.4306, 0.0026]	).to(lowercase_	)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]					,      lowercase_					,      atol=1E-4	)	)







'''simple docstring'''

def 				UpperCamelCase(					UpperCAmelCase_  ,	UpperCAmelCase_     ):
 while a != 0:
  UpperCAmelCase ,			UpperCAmelCase	:     Tuple						 =			b % a, a
 return b




def 				UpperCamelCase(					UpperCAmelCase_  ,	UpperCAmelCase_     ):
 if gcd(UpperCAmelCase_  ,	UpperCAmelCase_     ) != 1:
  UpperCAmelCase	:     List[str]						 =			F"""mod inverse of {a!r} and {m!r} does not exist"""
  raise ValueError(UpperCAmelCase_     )
 UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase	:     Any						 =			1, 0, a
 UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase	:     Dict						 =			0, 1, m
 while va != 0:
  UpperCAmelCase	:     Tuple						 =			ua // va
  UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase	:     List[Any]						 =			(ua - q * va), (ua - q * va), (ua - q * va), va, va, va
 return ua % m




