






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		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=30		,		_UpperCAmelCase=2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=32		,		_UpperCAmelCase=5		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=10		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=None		,		_UpperCAmelCase=2		,		)			-> Tuple:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     type_sequence_label_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     scope
     UpperCamelCase_									=     encoder_stride

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




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

     UpperCamelCase_									=     self.get_config()

     return config, pixel_values, labels




  def    _UpperCAmelCase     (     self )			-> Any:
     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=_UpperCAmelCase		,		initializer_range=self.initializer_range		,		encoder_stride=self.encoder_stride		,		)




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> str:
     UpperCamelCase_									=     DeiTModel(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_									=     DeiTForMaskedImageModeling(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(
         result.reconstruction.shape		,		(self.batch_size, self.num_channels, self.image_size, self.image_size) )

     # test greyscale images
     UpperCamelCase_									=     1
     UpperCamelCase_									=     DeiTForMaskedImageModeling(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()

     UpperCamelCase_									=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.reconstruction.shape		,		(self.batch_size, 1, self.image_size, self.image_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     self.type_sequence_label_size
     UpperCamelCase_									=     DeiTForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     UpperCamelCase_									=     1
     UpperCamelCase_									=     DeiTForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()

     UpperCamelCase_									=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     (
         (
         UpperCamelCase_
     )		,      (
         UpperCamelCase_
     )		,      (
         UpperCamelCase_
     )		,      
     )									=     config_and_inputs
     UpperCamelCase_									=     {'pixel_values': pixel_values}
     return config, inputs_dict




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






  """simple docstring"""





  A_						=   (
      (
          DeiTModel,
          DeiTForImageClassification,
          DeiTForImageClassificationWithTeacher,
          DeiTForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  A_						=   (
      {
          """feature-extraction""": DeiTModel,
          """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
      }
      if is_torch_available()
      else {}
  )

  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_									=     DeiTModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		has_text_modality=_UpperCAmelCase		,		hidden_size=37 )




  def    _UpperCAmelCase     (     self )			-> Optional[int]:
     self.config_tester.run_common_tests()




  @unittest.skip(reason='DeiT does not use inputs_embeds' )
  def    _UpperCAmelCase     (     self )			-> List[Any]:
     pass




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module) )
        UpperCamelCase_									=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(_UpperCAmelCase		,		nn.Linear ) )




  def    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase_									=     ['pixel_values']
        self.assertListEqual(arg_names[:1]		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=False )			-> List[str]:
     UpperCamelCase_									=     super()._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase		,		return_labels=_UpperCAmelCase )

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

     return inputs_dict




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     if not self.model_tester.is_training:
        return

     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()
     UpperCamelCase_									=     True

     for model_class in self.all_model_classes:
        # DeiTForImageClassificationWithTeacher supports inference-only
        if (
            model_class in get_values(_UpperCAmelCase )
            or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
        ):
           continue
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        model.to(_UpperCAmelCase )
        model.train()
        UpperCamelCase_									=     self._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase		,		return_labels=_UpperCAmelCase )
        UpperCamelCase_									=     model(**_UpperCAmelCase ).loss
        loss.backward()




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()
     if not self.model_tester.is_training:
        return

     UpperCamelCase_									=     False
     UpperCamelCase_									=     True

     for model_class in self.all_model_classes:
        if model_class in get_values(_UpperCAmelCase ) or not model_class.supports_gradient_checkpointing:
           continue
        # DeiTForImageClassificationWithTeacher supports inference-only
        if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
           continue
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        model.gradient_checkpointing_enable()
        model.to(_UpperCAmelCase )
        model.train()
        UpperCamelCase_									=     self._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase		,		return_labels=_UpperCAmelCase )
        UpperCamelCase_									=     model(**_UpperCAmelCase ).loss
        loss.backward()




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

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

        for problem_type in problem_types:
           with self.subTest(msg=f"""Testing {model_class} with {problem_type["title"]}""" ):
              UpperCamelCase_									=     problem_type['title']
              UpperCamelCase_									=     problem_type['num_labels']

              UpperCamelCase_									=     model_class(_UpperCAmelCase )
              model.to(_UpperCAmelCase )
              model.train()

              UpperCamelCase_									=     self._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase		,		return_labels=_UpperCAmelCase )

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

              UpperCamelCase_									=     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=_UpperCAmelCase ) as warning_list:
                 UpperCamelCase_									=     model(**_UpperCAmelCase ).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 )			-> Union[str, Any]:
     for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     DeiTModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )






def     _snake_case    ():
   UpperCamelCase_									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
   return image


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






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return (
         DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' )
         if is_vision_available()
         else None
     )




  @slow
  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to(
         _UpperCAmelCase )

     UpperCamelCase_									=     self.default_image_processor
     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

     # forward pass
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )

     # verify the logits
     UpperCamelCase_									=     torch.Size((1, 1000) )
     self.assertEqual(outputs.logits.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     torch.tensor([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1] ).to(_UpperCAmelCase )

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




  @slow
  @require_accelerate
  @require_torch_gpu
  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     DeiTModel.from_pretrained(
         'facebook/deit-base-distilled-patch16-224'		,		torch_dtype=torch.floataa		,		device_map='auto' )
     UpperCamelCase_									=     self.default_image_processor

     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' )
     UpperCamelCase_									=     inputs.pixel_values.to(_UpperCAmelCase )

     # forward pass to make sure inference works in fp16
     with torch.no_grad():
        UpperCamelCase_									=     model(_UpperCAmelCase )













import os
from math import logaa






def     _snake_case    (__lowercase = "base_exp.txt"):
   UpperCamelCase_									=     0
   UpperCamelCase_									=     0
   for i, line in enumerate(open(os.path.join(os.path.dirname(__lowercase)    ,      __lowercase))):
      UpperCamelCase_		,      UpperCamelCase_									=     list(map(__lowercase    ,      line.split(',')))
      if x * logaa(__lowercase) > largest:
         UpperCamelCase_									=     x * logaa(__lowercase)
         UpperCamelCase_									=     i + 1
   return result


if __name__ == "__main__":
 print(solution())





