


import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 transformers import (
           MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
           MODEL_MAPPING,
           LevitForImageClassification,
           LevitForImageClassificationWithTeacher,
           LevitModel,
       )
       from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import LevitImageProcessor

class       __magic_name__	(     _A):


     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   self.config_class(**self.inputs_dict			)
      self.parent.assertTrue(hasattr(lowerCamelCase__							,	'''hidden_sizes'''			)			)
      self.parent.assertTrue(hasattr(lowerCamelCase__							,	'''num_attention_heads'''			)			)



class       __magic_name__	:


     def __init__(      self							:     int							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     Tuple=13							,	lowerCamelCase__							:     Tuple=64							,	lowerCamelCase__							:     List[Any]=3							,	lowerCamelCase__							:     Any=3							,	lowerCamelCase__							:     str=2							,	lowerCamelCase__							:     Optional[Any]=1							,	lowerCamelCase__							:     Optional[Any]=16							,	lowerCamelCase__							:     Dict=[128, 256, 384]							,	lowerCamelCase__							:     str=[4, 6, 8]							,	lowerCamelCase__							:     Union[str, Any]=[2, 3, 4]							,	lowerCamelCase__							:     int=[16, 16, 16]							,	lowerCamelCase__							:     Optional[Any]=0							,	lowerCamelCase__							:     Dict=[2, 2, 2]							,	lowerCamelCase__							:     Optional[int]=[2, 2, 2]							,	lowerCamelCase__							:     Optional[Any]=0.02							,	lowerCamelCase__							:     Tuple=True							,	lowerCamelCase__							:     Optional[Any]=True							,	lowerCamelCase__							:     Any=2							,	)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   parent
      UpperCamelCase__					:    str          =   batch_size
      UpperCamelCase__					:    Optional[Any]          =   image_size
      UpperCamelCase__					:    str          =   num_channels
      UpperCamelCase__					:    Tuple          =   kernel_size
      UpperCamelCase__					:    str          =   stride
      UpperCamelCase__					:    Optional[int]          =   padding
      UpperCamelCase__					:    List[Any]          =   hidden_sizes
      UpperCamelCase__					:    List[str]          =   num_attention_heads
      UpperCamelCase__					:    Any          =   depths
      UpperCamelCase__					:    Union[str, Any]          =   key_dim
      UpperCamelCase__					:    List[Any]          =   drop_path_rate
      UpperCamelCase__					:    List[Any]          =   patch_size
      UpperCamelCase__					:    List[str]          =   attention_ratio
      UpperCamelCase__					:    List[Any]          =   mlp_ratio
      UpperCamelCase__					:    Optional[Any]          =   initializer_range
      UpperCamelCase__					:    Union[str, Any]          =   [
          ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
          ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
      ]
      UpperCamelCase__					:    List[Any]          =   is_training
      UpperCamelCase__					:    Any          =   use_labels
      UpperCamelCase__					:    str          =   num_labels
      UpperCamelCase__					:    Union[str, Any]          =   initializer_range


     def      UpperCAmelCase__	(      self							:     str			)  ->      Optional[int]:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      UpperCamelCase__					:    Any          =   None
      if self.use_labels:
       UpperCamelCase__					:    Union[str, Any]          =   ids_tensor([self.batch_size]							,	self.num_labels			)

      UpperCamelCase__					:    str          =   self.get_config()
      return config, pixel_values, labels


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





      '''simple docstring'''






      return LevitConfig(
          image_size=self.image_size							,	num_channels=self.num_channels							,	kernel_size=self.kernel_size							,	stride=self.stride							,	padding=self.padding							,	patch_size=self.patch_size							,	hidden_sizes=self.hidden_sizes							,	num_attention_heads=self.num_attention_heads							,	depths=self.depths							,	key_dim=self.key_dim							,	drop_path_rate=self.drop_path_rate							,	mlp_ratio=self.mlp_ratio							,	attention_ratio=self.attention_ratio							,	initializer_range=self.initializer_range							,	down_ops=self.down_ops							,	)


     def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Optional[int]							,	lowerCamelCase__							:     Optional[int]			)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   LevitModel(config=lowerCamelCase__			)
      model.to(lowerCamelCase__			)
      model.eval()
      UpperCamelCase__					:    int          =   model(lowerCamelCase__			)
      UpperCamelCase__					:    Tuple          =   (self.image_size, self.image_size)
      UpperCamelCase__					:    int          =   image_size[0], image_size[1]
      for _ in range(4			):
       UpperCamelCase__					:    int          =   floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1			)
       UpperCamelCase__					:    Optional[int]          =   floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1			)
      self.parent.assertEqual(
          result.last_hidden_state.shape							,	(self.batch_size, ceil(height / 4			) * ceil(width / 4			), self.hidden_sizes[-1])							,	)


     def      UpperCAmelCase__	(      self							:     List[Any]							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     Optional[Any]			)  ->      Dict:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   self.num_labels
      UpperCamelCase__					:    Any          =   LevitForImageClassification(lowerCamelCase__			)
      model.to(lowerCamelCase__			)
      model.eval()
      UpperCamelCase__					:    str          =   model(lowerCamelCase__							,	labels=lowerCamelCase__			)
      self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_labels)			)


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





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   self.prepare_config_and_inputs()
      UpperCamelCase__					:    List[str]          =   config_and_inputs
      UpperCamelCase__					:    int          =   {"pixel_values": pixel_values}
      return config, inputs_dict



@require_torch
class       __magic_name__	(     _A					,				_A					,				unittest.TestCase):
     A:		Optional[Any]			=      (
         (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
         if is_torch_available()
         else ()
     )
     A:		str			=      (
         {
             "feature-extraction": LevitModel,
             "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
         }
         if is_torch_available()
         else {}
     )

     A:		Tuple			=      False
     A:		Dict			=      False
     A:		str			=      False
     A:		Optional[Any]			=      False
     A:		Union[str, Any]			=      False


     def      UpperCAmelCase__	(      self							:     int			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   LevitModelTester(self			)
      UpperCamelCase__					:    Tuple          =   ConfigTester(self							,	config_class=lowerCamelCase__							,	has_text_modality=lowerCamelCase__							,	hidden_size=37			)


     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      Any:





      '''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      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      Dict:





      '''simple docstring'''






      return


     @unittest.skip(reason='''Levit does not use inputs_embeds'''			)
     def      UpperCAmelCase__	(      self							:     int			)  ->      Any:





      '''simple docstring'''






      pass


     @unittest.skip(reason='''Levit does not support input and output embeddings'''			)
     def      UpperCAmelCase__	(      self							:     List[str]			)  ->      Dict:





      '''simple docstring'''






      pass


     @unittest.skip(reason='''Levit does not output attentions'''			)
     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      int:





      '''simple docstring'''






      pass


     def      UpperCAmelCase__	(      self							:     Any			)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCamelCase__					:    Tuple          =   model_class(lowerCamelCase__			)
       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__					:    Optional[int]          =   ["pixel_values"]
       self.assertListEqual(arg_names[:1]							,	lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      Optional[int]:





      '''simple docstring'''






      def check_hidden_states_output(lowerCamelCase__							:     str							,	lowerCamelCase__							:     Tuple							,	lowerCamelCase__							:     Dict			):
       UpperCamelCase__					:    Union[str, Any]          =   model_class(lowerCamelCase__			)
       model.to(lowerCamelCase__			)
       model.eval()

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

       UpperCamelCase__					:    Tuple          =   outputs.hidden_states

       UpperCamelCase__					:    str          =   len(self.model_tester.depths			) + 1
       self.assertEqual(len(lowerCamelCase__			)							,	lowerCamelCase__			)

       UpperCamelCase__					:    Optional[Any]          =   (self.model_tester.image_size, self.model_tester.image_size)
       UpperCamelCase__					:    List[str]          =   image_size[0], image_size[1]
       for _ in range(4			):
        UpperCamelCase__					:    str          =   floor(
            (
                (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                / self.model_tester.stride
            )
            + 1			)
        UpperCamelCase__					:    List[str]          =   floor(
            (
                (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                / self.model_tester.stride
            )
            + 1			)
       # verify the first hidden states (first block)
       self.assertListEqual(
           list(hidden_states[0].shape[-2:]			)							,	[
               height * width,
               self.model_tester.hidden_sizes[0],
           ]							,	)

      UpperCamelCase__					:    Dict          =   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCamelCase__					:    Dict          =   True
       check_hidden_states_output(lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__			)

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

       check_hidden_states_output(lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__			)


     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      Optional[Any]:





      '''simple docstring'''






      pass


     def      UpperCAmelCase__	(      self							:     Union[str, Any]							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     Tuple							,	lowerCamelCase__							:     Any=False			)  ->      str:





      '''simple docstring'''






      UpperCamelCase__					:    Tuple          =   super()._prepare_for_class(lowerCamelCase__							,	lowerCamelCase__							,	return_labels=lowerCamelCase__			)

      if return_labels:
       if model_class.__name__ == "LevitForImageClassificationWithTeacher":
        del inputs_dict["labels"]

      return inputs_dict


     def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     Optional[Any]			)  ->      Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      List[str]:





      '''simple docstring'''






      if not self.model_tester.is_training:
       return

      UpperCamelCase__					:    Union[str, Any]          =   self.model_tester.prepare_config_and_inputs_for_common()
      UpperCamelCase__					:    int          =   True

      for model_class in self.all_model_classes:
       # LevitForImageClassificationWithTeacher supports inference-only
       if (
           model_class in get_values(lowerCamelCase__			)
           or model_class.__name__ == "LevitForImageClassificationWithTeacher"
       ):
        continue
       UpperCamelCase__					:    Optional[int]          =   model_class(lowerCamelCase__			)
       model.to(lowerCamelCase__			)
       model.train()
       UpperCamelCase__					:    Dict          =   self._prepare_for_class(lowerCamelCase__							,	lowerCamelCase__							,	return_labels=lowerCamelCase__			)
       UpperCamelCase__					:    List[Any]          =   model(**lowerCamelCase__			).loss
       loss.backward()


     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      Dict:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[int]          =   self.model_tester.prepare_config_and_inputs_for_common()
      if not self.model_tester.is_training:
       return

      UpperCamelCase__					:    int          =   False
      UpperCamelCase__					:    Any          =   True

      for model_class in self.all_model_classes:
       if model_class in get_values(lowerCamelCase__			) or not model_class.supports_gradient_checkpointing:
        continue
       # LevitForImageClassificationWithTeacher supports inference-only
       if model_class.__name__ == "LevitForImageClassificationWithTeacher":
        continue
       UpperCamelCase__					:    str          =   model_class(lowerCamelCase__			)
       model.gradient_checkpointing_enable()
       model.to(lowerCamelCase__			)
       model.train()
       UpperCamelCase__					:    Any          =   self._prepare_for_class(lowerCamelCase__							,	lowerCamelCase__							,	return_labels=lowerCamelCase__			)
       UpperCamelCase__					:    List[Any]          =   model(**lowerCamelCase__			).loss
       loss.backward()


     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   self.model_tester.prepare_config_and_inputs_for_common()

      UpperCamelCase__					:    Dict          =   [
          {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
          {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
          {"title": "regression", "num_labels": 1, "dtype": torch.float},
      ]

      for model_class in self.all_model_classes:
       if (
           model_class
           not in [
               *get_values(lowerCamelCase__			),
           ]
           or model_class.__name__ == "LevitForImageClassificationWithTeacher"
       ):
        continue

       for problem_type in problem_types:
        with self.subTest(msg=F"Testing {model_class} with {problem_type['title']}"			):
         UpperCamelCase__					:    int          =   problem_type["title"]
         UpperCamelCase__					:    Union[str, Any]          =   problem_type["num_labels"]

         UpperCamelCase__					:    Any          =   model_class(lowerCamelCase__			)
         model.to(lowerCamelCase__			)
         model.train()

         UpperCamelCase__					:    Optional[int]          =   self._prepare_for_class(lowerCamelCase__							,	lowerCamelCase__							,	return_labels=lowerCamelCase__			)

         if problem_type["num_labels"] > 1:
          UpperCamelCase__					:    Optional[int]          =   inputs["labels"].unsqueeze(1			).repeat(1							,	problem_type['''num_labels''']			)

         UpperCamelCase__					:    Dict          =   inputs["labels"].to(problem_type['''dtype''']			)

         # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
         # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
         # they have the same size." which is a symptom something in wrong for the regression problem.
         # See https://github.com/huggingface/transformers/issues/11780
         with warnings.catch_warnings(record=lowerCamelCase__			) as warning_list:
          UpperCamelCase__					:    Optional[int]          =   model(**lowerCamelCase__			).loss
         for w in warning_list:
          if "Using a target size that is different to the input size" in str(w.message			):
           raise ValueError(
               F"Something is going wrong in the regression problem: intercepted {w.message}"			)

         loss.backward()


     @slow
     def      UpperCAmelCase__	(      self							:     Dict			)  ->      Optional[int]:





      '''simple docstring'''






      for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCamelCase__					:    List[Any]          =   LevitModel.from_pretrained(lowerCamelCase__			)
       self.assertIsNotNone(lowerCamelCase__			)



def 			_a  (				):







 """simple docstring"""



 UpperCamelCase__					:    Union[str, Any]          =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
 return image






@require_torch
@require_vision
class       __magic_name__	(     unittest.TestCase):


     @cached_property
     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      Tuple:





      '''simple docstring'''






      return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)


     @slow
     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(
          lowerCamelCase__			)

      UpperCamelCase__					:    Union[str, Any]          =   self.default_image_processor
      UpperCamelCase__					:    Optional[int]          =   prepare_img()
      UpperCamelCase__					:    int          =   image_processor(images=lowerCamelCase__							,	return_tensors='''pt'''			).to(lowerCamelCase__			)

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

      # verify the logits
      UpperCamelCase__					:    Union[str, Any]          =   torch.Size((1, 1000)			)
      self.assertEqual(outputs.logits.shape							,	lowerCamelCase__			)

      UpperCamelCase__					:    str          =   torch.tensor([1.0448, -0.3745, -1.8317]			).to(lowerCamelCase__			)

      self.assertTrue(torch.allclose(outputs.logits[0, :3]							,	lowerCamelCase__							,	atol=1E-4			)			)






from math import factorial, radians

def 			_a  (				SCREAMING_SNAKE_CASE	:				float    , SCREAMING_SNAKE_CASE	:				int = 18    , SCREAMING_SNAKE_CASE	:				int = 10     ):







 """simple docstring"""



 UpperCamelCase__					:    Dict          =   angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0)

 # Converting from degrees to radians
 UpperCamelCase__					:    int          =   radians(SCREAMING_SNAKE_CASE     )

 UpperCamelCase__					:    Tuple          =   angle_in_radians
 UpperCamelCase__					:    str          =   3
 UpperCamelCase__					:    int          =   -1

 for _ in range(SCREAMING_SNAKE_CASE     ):
  result += (b * (angle_in_radians**a)) / factorial(SCREAMING_SNAKE_CASE     )

  UpperCamelCase__					:    List[Any]          =   -b  # One positive term and the next will be negative and so on...
  a += 2  # Increased by 2 for every term.

 return round(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )


if __name__ == "__main__":
       __import__("doctest").testmod()


