


def 				__lowerCamelCase						( UpperCAmelCase_						:		int						):




      """simple docstring"""





      if p < 2:
            raise ValueError('''p should not be less than 2!'''						)
      elif p == 2:
            return True

      a						:int 							=       4
      a						:Union[str, Any] 							=       (1 << p) - 1
      for _ in range(p - 2						):
            a						:List[Any] 							=       ((s * s) - 2) % m
      return s == 0


if __name__ == "__main__":
     print(lucas_lehmer_test(7))
     print(lucas_lehmer_test(11))







import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import MaskFormerSwinBackbone
    from transformers.models.maskformer import MaskFormerSwinModel




class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Optional[int]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Tuple=13			,							UpperCamelCase__			: Optional[Any]=32			,							UpperCamelCase__			: Dict=2			,							UpperCamelCase__			: Dict=3			,							UpperCamelCase__			: Union[str, Any]=16			,							UpperCamelCase__			: Any=[1, 2, 1]			,							UpperCamelCase__			: int=[2, 2, 4]			,							UpperCamelCase__			: int=2			,							UpperCamelCase__			: Optional[int]=2.0			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: Any=0.0			,							UpperCamelCase__			: str=0.0			,							UpperCamelCase__			: Optional[Any]=0.1			,							UpperCamelCase__			: Tuple="gelu"			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: Any=True			,							UpperCamelCase__			: List[str]=0.02			,							UpperCamelCase__			: Union[str, Any]=1E-5			,							UpperCamelCase__			: str=True			,							UpperCamelCase__			: List[str]=None			,							UpperCamelCase__			: Union[str, Any]=True			,							UpperCamelCase__			: Tuple=10			,							UpperCamelCase__			: Dict=8			,							UpperCamelCase__			: Tuple=["stage1", "stage2", "stage3"]			,							UpperCamelCase__			: Tuple=[1, 2, 3]			,							)			->	Dict:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       image_size
    __magic_name__				     =       patch_size
    __magic_name__				     =       num_channels
    __magic_name__				     =       embed_dim
    __magic_name__				     =       depths
    __magic_name__				     =       num_heads
    __magic_name__				     =       window_size
    __magic_name__				     =       mlp_ratio
    __magic_name__				     =       qkv_bias
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       drop_path_rate
    __magic_name__				     =       hidden_act
    __magic_name__				     =       use_absolute_embeddings
    __magic_name__				     =       patch_norm
    __magic_name__				     =       layer_norm_eps
    __magic_name__				     =       initializer_range
    __magic_name__				     =       is_training
    __magic_name__				     =       scope
    __magic_name__				     =       use_labels
    __magic_name__				     =       type_sequence_label_size
    __magic_name__				     =       encoder_stride
    __magic_name__				     =       out_features
    __magic_name__				     =       out_indices
  def 							_lowercase							( self			: str    )			->	Optional[int]:







    """simple docstring"""






    __magic_name__				     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

    __magic_name__				     =       self.get_config()

    return config, pixel_values, labels
  def 							_lowercase							( self			: Tuple    )			->	str:







    """simple docstring"""






    return MaskFormerSwinConfig(
        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			,							out_features=self.out_features			,							out_indices=self.out_indices			,							)
  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: Optional[int]    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModel(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__    )

    __magic_name__				     =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
    __magic_name__				     =       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 							_lowercase							( self			: List[str]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: List[str]    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinBackbone(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__    )

    # verify feature maps
    self.parent.assertEqual(len(result.feature_maps    )			,							len(config.out_features    )    )
    self.parent.assertListEqual(list(result.feature_maps[0].shape    )			,							[13, 16, 16, 16]    )

    # verify channels
    self.parent.assertEqual(len(model.channels    )			,							len(config.out_features    )    )
    self.parent.assertListEqual(model.channels			,							[16, 32, 64]    )

    # verify ValueError
    with self.parent.assertRaises(UpperCamelCase__    ):
      __magic_name__				     =       ["""stem"""]
      __magic_name__				     =       MaskFormerSwinBackbone(config=UpperCamelCase__    )





  def 							_lowercase							( self			: Any    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       self.prepare_config_and_inputs()
    __magic_name__     ,    __magic_name__     ,    __magic_name__				     =       config_and_inputs
    __magic_name__				     =       {"""pixel_values""": pixel_values}
    return config, inputs_dict







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


  '''simple docstring'''







  a__           =		(
      (
          MaskFormerSwinModel,
          MaskFormerSwinBackbone,
      )
      if is_torch_available()
      else ()
  )
  a__           =		{"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
  a__           =		False
  a__           =		False
  a__           =		False
  a__           =		False
  a__           =		False
  def 							_lowercase							( self			: Any    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModelTester(self    )
    __magic_name__				     =       ConfigTester(self			,							config_class=UpperCamelCase__			,							embed_dim=37    )
  @require_torch_multi_gpu
  @unittest.skip(
      reason=(
          """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
          """ `nn.DataParallel`"""
      )    )
  def 							_lowercase							( self			: List[str]    )			->	Optional[int]:







    """simple docstring"""






    pass
  def 							_lowercase							( self			: str    )			->	Dict:







    """simple docstring"""






    self.create_and_test_config_common_properties()
    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 							_lowercase							( self			: Optional[int]    )			->	List[str]:







    """simple docstring"""






    return
  def 							_lowercase							( self			: str    )			->	str:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: int    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*UpperCamelCase__    )
  @unittest.skip("""Swin does not use inputs_embeds"""    )
  def 							_lowercase							( self			: Any    )			->	int:







    """simple docstring"""






    pass
  @unittest.skip("""Swin does not support feedforward chunking"""    )
  def 							_lowercase							( self			: str    )			->	List[Any]:







    """simple docstring"""






    pass
  def 							_lowercase							( self			: Union[str, Any]    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __magic_name__				     =       model_class(UpperCamelCase__    )
      self.assertIsInstance(model.get_input_embeddings()			,							(nn.Module)    )
      __magic_name__				     =       model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(UpperCamelCase__			,							nn.Linear    )    )
  def 							_lowercase							( self			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

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

      __magic_name__				     =       ["""pixel_values"""]
      self.assertListEqual(arg_names[:1]			,							UpperCamelCase__    )
  @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""    )
  def 							_lowercase							( self			: Tuple    )			->	int:







    """simple docstring"""






    pass
  @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""    )
  def 							_lowercase							( self			: List[str]    )			->	Dict:







    """simple docstring"""






    pass
  def 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Union[str, Any]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       model_class(UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()

    with torch.no_grad():
      __magic_name__				     =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )    )

    __magic_name__				     =       outputs.hidden_states

    __magic_name__				     =       getattr(
        self.model_tester			,							"""expected_num_hidden_layers"""			,							len(self.model_tester.depths    ) + 1    )
    self.assertEqual(len(UpperCamelCase__    )			,							UpperCamelCase__    )

    # Swin has a different seq_length
    __magic_name__				     =       (
        config.patch_size
        if isinstance(config.patch_size			,							collections.abc.Iterable    )
        else (config.patch_size, config.patch_size)
    )

    __magic_name__				     =       (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]			,							)
  def 							_lowercase							( self			: Dict    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    __magic_name__				     =       (
        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:
      __magic_name__				     =       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"]
      __magic_name__				     =       True

      self.check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()
    __magic_name__				     =       3

    __magic_name__				     =       (
        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)
    )
    __magic_name__				     =       (
        config.patch_size
        if isinstance(config.patch_size			,							collections.abc.Iterable    )
        else (config.patch_size, config.patch_size)
    )

    __magic_name__				     =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
    __magic_name__				     =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

    for model_class in self.all_model_classes:
      __magic_name__				     =       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"]
      __magic_name__				     =       True
      self.check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							(padded_height, padded_width)    )
  @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""    )
  def 							_lowercase							( self			: Optional[int]    )			->	int:







    """simple docstring"""






    pass
  @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""    )
  def 							_lowercase							( self			: List[str]    )			->	List[Any]:







    """simple docstring"""






    pass
  @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""    )
  def 							_lowercase							( self			: Dict    )			->	Optional[Any]:







    """simple docstring"""






    pass





  def 							_lowercase							( self			: Dict    )			->	Any:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    def set_nan_tensor_to_zero(UpperCamelCase__			: Union[str, Any]    ):
      __magic_name__				     =       0
      return t

    def check_equivalence(UpperCamelCase__			: str			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: int={}    ):
      with torch.no_grad():
        __magic_name__				     =       model(**UpperCamelCase__			,							return_dict=UpperCamelCase__			,							**UpperCamelCase__    )
        __magic_name__				     =       model(**UpperCamelCase__			,							return_dict=UpperCamelCase__			,							**UpperCamelCase__    ).to_tuple()

        def recursive_check(UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: List[Any]    ):
          if isinstance(UpperCamelCase__			,							(List, Tuple)    ):
            for tuple_iterable_value, dict_iterable_value in zip(UpperCamelCase__			,							UpperCamelCase__    ):
              recursive_check(UpperCamelCase__			,							UpperCamelCase__    )
          elif isinstance(UpperCamelCase__			,							UpperCamelCase__    ):
            for tuple_iterable_value, dict_iterable_value in zip(
                tuple_object.values()			,							dict_object.values()    ):
              recursive_check(UpperCamelCase__			,							UpperCamelCase__    )
          elif tuple_object is None:
            return
          else:
            self.assertTrue(
                torch.allclose(
                    set_nan_tensor_to_zero(UpperCamelCase__    )			,							set_nan_tensor_to_zero(UpperCamelCase__    )			,							atol=1E-5    )			,							msg=(
                    """Tuple and dict output are not equal. Difference:"""
                    F''' {torch.max(torch.abs(tuple_object - dict_object    )    )}. Tuple has `nan`:'''
                    F''' {torch.isnan(UpperCamelCase__    ).any()} and `inf`: {torch.isinf(UpperCamelCase__    )}. Dict has'''
                    F''' `nan`: {torch.isnan(UpperCamelCase__    ).any()} and `inf`: {torch.isinf(UpperCamelCase__    )}.'''
                )			,							)

        recursive_check(UpperCamelCase__			,							UpperCamelCase__    )

    for model_class in self.all_model_classes:
      __magic_name__				     =       model_class(UpperCamelCase__    )
      model.to(UpperCamelCase__    )
      model.eval()

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							{"""output_hidden_states""": True}    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							{"""output_hidden_states""": True}    )







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


  '''simple docstring'''







  a__           =		(MaskFormerSwinBackbone,) if is_torch_available() else ()
  a__           =		MaskFormerSwinConfig
  def 							_lowercase							( self			: Union[str, Any]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModelTester(self    )





  def 							_lowercase							( self			: List[str]    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()
    __magic_name__				     =       inputs_dict["""pixel_values"""].shape[0]

    for backbone_class in self.all_model_classes:
      __magic_name__				     =       backbone_class(UpperCamelCase__    )
      backbone.to(UpperCamelCase__    )
      backbone.eval()

      __magic_name__				     =       backbone(**UpperCamelCase__    )

      # Test default outputs and verify feature maps
      self.assertIsInstance(outputs.feature_maps			,							UpperCamelCase__    )
      self.assertTrue(len(outputs.feature_maps    ) == len(backbone.channels    )    )
      for feature_map, n_channels in zip(outputs.feature_maps			,							backbone.channels    ):
        self.assertTrue(feature_map.shape[:2]			,							(batch_size, n_channels)    )
      self.assertIsNone(outputs.hidden_states    )
      self.assertIsNone(outputs.attentions    )

      # Test output_hidden_states=True
      __magic_name__				     =       backbone(**UpperCamelCase__			,							output_hidden_states=UpperCamelCase__    )
      self.assertIsNotNone(outputs.hidden_states    )
      self.assertTrue(len(outputs.hidden_states    )			,							len(backbone.stage_names    )    )
      # We skip the stem layer
      for hidden_states, n_channels in zip(outputs.hidden_states[1:]			,							backbone.channels    ):
        for hidden_state in hidden_states:
          # Hidden states are in the format (batch_size, (height * width), n_channels)
          __magic_name__     ,    __magic_name__     ,    __magic_name__				     =       hidden_state.shape
          self.assertTrue((h_batch_size, h_n_channels)			,							(batch_size, n_channels)    )

            # Test output_attentions=True
      if self.has_attentions:
        __magic_name__				     =       backbone(**UpperCamelCase__			,							output_attentions=UpperCamelCase__    )
        self.assertIsNotNone(outputs.attentions    )

