





import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
        MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
        MODEL_MAPPING,
        DeiTForImageClassification,
        DeiTForImageClassificationWithTeacher,
        DeiTForMaskedImageModeling,
        DeiTModel,
    )
    from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import DeiTImageProcessor





class  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=30					,  lowercase=2					,  lowercase=3					,  lowercase=True					,  lowercase=True					,  lowercase=32					,  lowercase=5					,  lowercase=4					,  lowercase=37					,  lowercase="gelu"					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=10					,  lowercase=0.02					,  lowercase=3					,  lowercase=None					,  lowercase=2					,  )			->						Optional[int]:







          '''simple docstring'''

          a__						:	List[Any] =				parent
          a__						:	str =				batch_size
          a__						:	Any =				image_size
          a__						:	int =				patch_size
          a__						:	Tuple =				num_channels
          a__						:	Optional[int] =				is_training
          a__						:	int =				use_labels
          a__						:	Union[str, Any] =				hidden_size
          a__						:	str =				num_hidden_layers
          a__						:	List[Any] =				num_attention_heads
          a__						:	Dict =				intermediate_size
          a__						:	Any =				hidden_act
          a__						:	Any =				hidden_dropout_prob
          a__						:	List[str] =				attention_probs_dropout_prob
          a__						:	Dict =				type_sequence_label_size
          a__						:	List[Any] =				initializer_range
          a__						:	Dict =				scope
          a__						:	List[Any] =				encoder_stride

          # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
          a__						:	Any =				(image_size // patch_size) ** 2
          a__						:	Any =				num_patches + 2

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







          '''simple docstring'''

          a__						:	Tuple =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:	int =				None
          if self.use_labels:
                 a__						:	str =				ids_tensor([self.batch_size]					,  self.type_sequence_label_size)

          a__						:	Tuple =				self.get_config()

          return config, pixel_values, labels

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          return DeiTConfig(
              image_size=self.image_size					,  patch_size=self.patch_size					,  num_channels=self.num_channels					,  hidden_size=self.hidden_size					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  is_decoder=lowercase					,  initializer_range=self.initializer_range					,  encoder_stride=self.encoder_stride					,  )

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						int:







          '''simple docstring'''

          a__						:	int =				DeiTModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Union[str, Any] =				model(lowercase)
          self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						str:







          '''simple docstring'''

          a__						:	List[str] =				DeiTForMaskedImageModeling(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	List[Any] =				model(lowercase)
          self.parent.assertEqual(
              result.reconstruction.shape					,  (self.batch_size, self.num_channels, self.image_size, self.image_size))

          # test greyscale images
          a__						:	Tuple =				1
          a__						:	Optional[Any] =				DeiTForMaskedImageModeling(lowercase)
          model.to(lowercase)
          model.eval()

          a__						:	Union[str, Any] =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          a__						:	Dict =				model(lowercase)
          self.parent.assertEqual(result.reconstruction.shape					,  (self.batch_size, 1, self.image_size, self.image_size))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						Optional[int]:







          '''simple docstring'''

          a__						:	int =				self.type_sequence_label_size
          a__						:	List[str] =				DeiTForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Tuple =				model(lowercase					,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

          # test greyscale images
          a__						:	Union[str, Any] =				1
          a__						:	Optional[Any] =				DeiTForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()

          a__						:	Dict =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          a__						:	str =				model(lowercase					,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	Tuple =				self.prepare_config_and_inputs()
          (
              (
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							
          )						:	Union[str, Any] =				config_and_inputs
          a__						:	Dict =				{'pixel_values': pixel_values}
          return config, inputs_dict





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Dict         =  (
       (
           DeiTModel,
           DeiTForImageClassification,
           DeiTForImageClassificationWithTeacher,
           DeiTForMaskedImageModeling,
       )
       if is_torch_available()
       else ()
   )
   __A   :				str         =  (
       {
           '''feature-extraction''': DeiTModel,
           '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
       }
       if is_torch_available()
       else {}
   )

   __A   :				List[str]         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				Optional[Any]         =  False

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







          '''simple docstring'''

          a__						:	List[str] =				DeiTModelTester(self)
          a__						:	str =				ConfigTester(self					,  config_class=lowercase					,  has_text_modality=lowercase					,  hidden_size=37)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='DeiT does not use inputs_embeds')
   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__ ,							a__						:	Optional[int] =				self.model_tester.prepare_config_and_inputs_for_common()

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

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__ ,							a__						:	List[str] =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 a__						:	Any =				['pixel_values']
                 self.assertListEqual(arg_names[:1]					,  lowercase)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	int =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Optional[int] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*lowercase)

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	List[Any] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase)

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase=False)			->						Tuple:







          '''simple docstring'''

          a__						:	Optional[int] =				super()._prepare_for_class(lowercase					,  lowercase					,  return_labels=lowercase)

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

          return inputs_dict

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







          '''simple docstring'''

          if not self.model_tester.is_training:
                 return

          a__ ,							a__						:	int =				self.model_tester.prepare_config_and_inputs_for_common()
          a__						:	List[Any] =				True

          for model_class in self.all_model_classes:
                 # DeiTForImageClassificationWithTeacher supports inference-only
                 if (
                     model_class in get_values(lowercase)
                     or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
                 ):
                        continue
                 a__						:	List[str] =				model_class(lowercase)
                 model.to(lowercase)
                 model.train()
                 a__						:	str =				self._prepare_for_class(lowercase					,  lowercase					,  return_labels=lowercase)
                 a__						:	str =				model(**lowercase).loss
                 loss.backward()

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__ ,							a__						:	Optional[Any] =				self.model_tester.prepare_config_and_inputs_for_common()
          if not self.model_tester.is_training:
                 return

          a__						:	List[str] =				False
          a__						:	List[str] =				True

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

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__ ,							a__						:	Optional[int] =				self.model_tester.prepare_config_and_inputs_for_common()

          a__						:	Tuple =				[
              {'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(lowercase),
                         *get_values(lowercase),
                     ]
                     or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
                 ):
                        continue

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

                               a__						:	Union[str, Any] =				model_class(lowercase)
                               model.to(lowercase)
                               model.train()

                               a__						:	List[Any] =				self._prepare_for_class(lowercase					,  lowercase					,  return_labels=lowercase)

                               if problem_type["num_labels"] > 1:
                                      a__						:	Any =				inputs['labels'].unsqueeze(1).repeat(1					,  problem_type['num_labels'])

                               a__						:	Tuple =				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=lowercase) as warning_list:
                                      a__						:	Optional[Any] =				model(**lowercase).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 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	Any =				DeiTModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



def A_	(		)  ->		Any:
       a__						:	Any =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





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




   """simple docstring"""



   @cached_property
   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          return (
              DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224')
              if is_vision_available()
              else None
          )

   @slow
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[Any] =				DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224').to(
              lowercase)

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

          # forward pass
          with torch.no_grad():
                 a__						:	int =				model(**lowercase)

          # verify the logits
          a__						:	Tuple =				torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape					,  lowercase)

          a__						:	int =				torch.tensor([-1.02_66, 0.19_12, -1.28_61]).to(lowercase)

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

   @slow
   @require_accelerate
   @require_torch_gpu
   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Dict =				DeiTModel.from_pretrained(
              'facebook/deit-base-distilled-patch16-224'					,  torch_dtype=torch.floataa					,  device_map='auto')
          a__						:	Union[str, Any] =				self.default_image_processor

          a__						:	List[str] =				prepare_img()
          a__						:	int =				image_processor(images=lowercase					,  return_tensors='pt')
          a__						:	str =				inputs.pixel_values.to(lowercase)

          # forward pass to make sure inference works in fp16
          with torch.no_grad():
                 a__						:	Any =				model(lowercase)









from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean



def A_	(		A__				)  ->		Tuple:

       # A local function to see if a dot lands in the circle.
       def is_in_circle(A__		,      A__				) -> bool:
              a__						:	List[str] =				sqrt((x**2) + (y**2)				)
              # Our circle has a radius of 1, so a distance
              # greater than 1 would land outside the circle.
              return distance_from_centre <= 1

       # The proportion of guesses that landed in the circle
       a__						:	List[str] =				mean(
           int(is_in_circle(uniform(-1.0		,      1.0				)		,      uniform(-1.0		,      1.0				)				)				)
           for _ in range(A__				)				)
       # The ratio of the area for circle to square is pi/4.
       a__						:	Optional[Any] =				proportion * 4
       print(F'The estimated value of pi is {pi_estimate}'				)
       print(F'The numpy value of pi is {pi}'				)
       print(F'The total error is {abs(pi - pi_estimate				)}'				)



def A_	(		A__		,      A__		,      A__ = 0.0		,      A__ = 1.0		,      )  ->		float:
       return mean(
           function_to_integrate(uniform(A__		,      A__				)				) for _ in range(A__				)				) * (max_value - min_value)



def A_	(		A__		,      A__ = 0.0		,      A__ = 1.0				)  ->		None:

       def identity_function(A__				) -> float:
              return x

       a__						:	List[Any] =				area_under_curve_estimator(
           A__		,      A__		,      A__		,      A__				)
       a__						:	Union[str, Any] =				(max_value * max_value - min_value * min_value) / 2

       print('******************'				)
       print(F'Estimating area under y=x where x varies from {min_value} to {max_value}'				)
       print(F'Estimated value is {estimated_value}'				)
       print(F'Expected value is {expected_value}'				)
       print(F'Total error is {abs(estimated_value - expected_value				)}'				)
       print('******************'				)



def A_	(		A__				)  ->		None:

       def function_to_integrate(A__				) -> float:
              return sqrt(4.0 - x * x				)

       a__						:	Dict =				area_under_curve_estimator(
           A__		,      A__		,      0.0		,      2.0				)

       print('******************'				)
       print('Estimating pi using area_under_curve_estimator'				)
       print(F'Estimated value is {estimated_value}'				)
       print(F'Expected value is {pi}'				)
       print(F'Total error is {abs(estimated_value - pi				)}'				)
       print('******************'				)


if __name__ == "__main__":
    import doctest

    doctest.testmod()


