

import inspect
import unittest

from transformers import YolosConfig
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, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import YolosForObjectDetection, YolosModel
    from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor
class  _A		:

  def __init__(				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE=13 ,					_SCREAMING_SNAKE_CASE=[30, 30] ,					_SCREAMING_SNAKE_CASE=2 ,					_SCREAMING_SNAKE_CASE=3 ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=32 ,					_SCREAMING_SNAKE_CASE=5 ,					_SCREAMING_SNAKE_CASE=4 ,					_SCREAMING_SNAKE_CASE=37 ,					_SCREAMING_SNAKE_CASE="gelu" ,					_SCREAMING_SNAKE_CASE=0.1 ,					_SCREAMING_SNAKE_CASE=0.1 ,					_SCREAMING_SNAKE_CASE=10 ,					_SCREAMING_SNAKE_CASE=0.02 ,					_SCREAMING_SNAKE_CASE=3 ,					_SCREAMING_SNAKE_CASE=None ,					_SCREAMING_SNAKE_CASE=8 ,					_SCREAMING_SNAKE_CASE=10 ,					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Dict           =     parent
        SCREAMING_SNAKE_CASE_				:  Dict           =     batch_size
        SCREAMING_SNAKE_CASE_				:  Tuple           =     image_size
        SCREAMING_SNAKE_CASE_				:  str           =     patch_size
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     num_channels
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     is_training
        SCREAMING_SNAKE_CASE_				:  int           =     use_labels
        SCREAMING_SNAKE_CASE_				:  int           =     hidden_size
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     num_hidden_layers
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     num_attention_heads
        SCREAMING_SNAKE_CASE_				:  List[str]           =     intermediate_size
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     hidden_act
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     hidden_dropout_prob
        SCREAMING_SNAKE_CASE_				:  Any           =     attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE_				:  int           =     type_sequence_label_size
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     initializer_range
        SCREAMING_SNAKE_CASE_				:  int           =     num_labels
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     scope
        SCREAMING_SNAKE_CASE_				:  Dict           =     n_targets
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     num_detection_tokens
        # we set the expected sequence length (which is used in several tests)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
        SCREAMING_SNAKE_CASE_				:  Tuple           =     (image_size[1] // patch_size) * (image_size[0] // patch_size)
        SCREAMING_SNAKE_CASE_				:  int           =     num_patches + 1 + self.num_detection_tokens

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  int           =     floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]					)

        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     None
        if self.use_labels:
              # labels is a list of Dict (each Dict being the labels for a given example in the batch)
              SCREAMING_SNAKE_CASE_				:  int           =     []
              for i in range(self.batch_size					):
                    SCREAMING_SNAKE_CASE_				:  Dict           =     {}
                    SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     torch.randint(
                        high=self.num_labels ,					size=(self.n_targets,) ,					device=_SCREAMING_SNAKE_CASE					)
                    SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     torch.rand(self.n_targets ,					4 ,					device=_SCREAMING_SNAKE_CASE					)
                    labels.append(_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  Any           =     self.get_config()

        return config, pixel_values, labels

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        return YolosConfig(
            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=_SCREAMING_SNAKE_CASE ,					initializer_range=self.initializer_range ,					num_detection_tokens=self.num_detection_tokens ,					num_labels=self.num_labels ,					)

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     YolosModel(config=_SCREAMING_SNAKE_CASE					)
        model.to(_SCREAMING_SNAKE_CASE					)
        model.eval()
        SCREAMING_SNAKE_CASE_				:  List[str]           =     model(_SCREAMING_SNAKE_CASE					)
        self.parent.assertEqual(
            result.last_hidden_state.shape ,					(self.batch_size, self.expected_seq_len, self.hidden_size)					)

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  List[str]           =     YolosForObjectDetection(_SCREAMING_SNAKE_CASE					)
        model.to(_SCREAMING_SNAKE_CASE					)
        model.eval()

        SCREAMING_SNAKE_CASE_				:  Tuple           =     model(pixel_values=_SCREAMING_SNAKE_CASE					)
        SCREAMING_SNAKE_CASE_				:  Dict           =     model(_SCREAMING_SNAKE_CASE					)

        self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_detection_tokens, self.num_labels + 1)					)
        self.parent.assertEqual(result.pred_boxes.shape ,					(self.batch_size, self.num_detection_tokens, 4)					)

        SCREAMING_SNAKE_CASE_				:  str           =     model(pixel_values=_SCREAMING_SNAKE_CASE ,					labels=_SCREAMING_SNAKE_CASE					)

        self.parent.assertEqual(result.loss.shape ,					()					)
        self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_detection_tokens, self.num_labels + 1)					)
        self.parent.assertEqual(result.pred_boxes.shape ,					(self.batch_size, self.num_detection_tokens, 4)					)



  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Tuple           =     self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     config_and_inputs
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     {'pixel_values': pixel_values}
        return config, inputs_dict

@require_torch
class  _A		(  __magic_name__   ,     __magic_name__   ,     unittest.TestCase):
  SCREAMING_SNAKE_CASE    :      Dict       =  (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE    :      str       =  (
      {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
  )

  SCREAMING_SNAKE_CASE    :      Any       =  False
  SCREAMING_SNAKE_CASE    :      Union[str, Any]       =  False
  SCREAMING_SNAKE_CASE    :      Tuple       =  False
  SCREAMING_SNAKE_CASE    :      Dict       =  False

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE=False					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  List[str]           =     super()._prepare_for_class(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					return_labels=_SCREAMING_SNAKE_CASE					)

        if return_labels:
              if model_class.__name__ == "YolosForObjectDetection":
                    SCREAMING_SNAKE_CASE_				:  int           =     []
                    for i in range(self.model_tester.batch_size					):
                          SCREAMING_SNAKE_CASE_				:  List[Any]           =     {}
                          SCREAMING_SNAKE_CASE_				:  List[Any]           =     torch.ones(
                              size=(self.model_tester.n_targets,) ,					device=_SCREAMING_SNAKE_CASE ,					dtype=torch.long					)
                          SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     torch.ones(
                              self.model_tester.n_targets ,					4 ,					device=_SCREAMING_SNAKE_CASE ,					dtype=torch.float					)
                          labels.append(_SCREAMING_SNAKE_CASE					)
                    SCREAMING_SNAKE_CASE_				:  List[Any]           =     labels

        return inputs_dict

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Tuple           =     YolosModelTester(self					)
        SCREAMING_SNAKE_CASE_				:  str           =     ConfigTester(self ,					config_class=_SCREAMING_SNAKE_CASE ,					has_text_modality=_SCREAMING_SNAKE_CASE ,					hidden_size=37					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        self.config_tester.run_common_tests()

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        pass

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Dict           =     self.model_tester.prepare_config_and_inputs_for_common()

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

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_				:  Any           =     ['pixel_values']
              self.assertListEqual(arg_names[:1] ,					_SCREAMING_SNAKE_CASE					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







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

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  int           =     self.model_tester.prepare_config_and_inputs_for_common()
        SCREAMING_SNAKE_CASE_				:  List[str]           =     True

        # in YOLOS, the seq_len is different
        SCREAMING_SNAKE_CASE_				:  str           =     self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     True
              SCREAMING_SNAKE_CASE_				:  str           =     False
              SCREAMING_SNAKE_CASE_				:  Dict           =     True
              SCREAMING_SNAKE_CASE_				:  Any           =     model_class(_SCREAMING_SNAKE_CASE					)
              model.to(_SCREAMING_SNAKE_CASE					)
              model.eval()
              with torch.no_grad():
                    SCREAMING_SNAKE_CASE_				:  Tuple           =     model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)					)
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     outputs.attentions
              self.assertEqual(len(_SCREAMING_SNAKE_CASE					) ,					self.model_tester.num_hidden_layers					)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              SCREAMING_SNAKE_CASE_				:  List[Any]           =     True
              SCREAMING_SNAKE_CASE_				:  int           =     model_class(_SCREAMING_SNAKE_CASE					)
              model.to(_SCREAMING_SNAKE_CASE					)
              model.eval()
              with torch.no_grad():
                    SCREAMING_SNAKE_CASE_				:  Dict           =     model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)					)
              SCREAMING_SNAKE_CASE_				:  str           =     outputs.attentions
              self.assertEqual(len(_SCREAMING_SNAKE_CASE					) ,					self.model_tester.num_hidden_layers					)

              self.assertListEqual(
                  list(attentions[0].shape[-3:]					) ,					[self.model_tester.num_attention_heads, seq_len, seq_len] ,					)
              SCREAMING_SNAKE_CASE_				:  str           =     len(_SCREAMING_SNAKE_CASE					)

              # Check attention is always last and order is fine
              SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     True
              SCREAMING_SNAKE_CASE_				:  List[str]           =     True
              SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     model_class(_SCREAMING_SNAKE_CASE					)
              model.to(_SCREAMING_SNAKE_CASE					)
              model.eval()
              with torch.no_grad():
                    SCREAMING_SNAKE_CASE_				:  Tuple           =     model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)					)

              SCREAMING_SNAKE_CASE_				:  Dict           =     1
              self.assertEqual(out_len + added_hidden_states ,					len(_SCREAMING_SNAKE_CASE					)					)

              SCREAMING_SNAKE_CASE_				:  str           =     outputs.attentions

              self.assertEqual(len(_SCREAMING_SNAKE_CASE					) ,					self.model_tester.num_hidden_layers					)
              self.assertListEqual(
                  list(self_attentions[0].shape[-3:]					) ,					[self.model_tester.num_attention_heads, seq_len, seq_len] ,					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):
              SCREAMING_SNAKE_CASE_				:  Any           =     model_class(_SCREAMING_SNAKE_CASE					)
              model.to(_SCREAMING_SNAKE_CASE					)
              model.eval()

              with torch.no_grad():
                    SCREAMING_SNAKE_CASE_				:  List[Any]           =     model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)					)

              SCREAMING_SNAKE_CASE_				:  Tuple           =     outputs.hidden_states

              SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     getattr(
                  self.model_tester ,					'expected_num_hidden_layers' ,					self.model_tester.num_hidden_layers + 1					)
              self.assertEqual(len(_SCREAMING_SNAKE_CASE					) ,					_SCREAMING_SNAKE_CASE					)

              # YOLOS has a different seq_length
              SCREAMING_SNAKE_CASE_				:  int           =     self.model_tester.expected_seq_len

              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]					) ,					[seq_length, self.model_tester.hidden_size] ,					)

        SCREAMING_SNAKE_CASE_				:  int           =     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     True
              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)

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

              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*_SCREAMING_SNAKE_CASE					)



  @slow
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_				:  List[str]           =     YolosModel.from_pretrained(_SCREAMING_SNAKE_CASE					)
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)





def    A_  (							):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  Dict           =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
      return image



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

  @cached_property
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        return AutoImageProcessor.from_pretrained('hustvl/yolos-small'					) if is_vision_available() else None



  @slow
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     YolosForObjectDetection.from_pretrained('hustvl/yolos-small'					).to(_SCREAMING_SNAKE_CASE					)

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

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     model(inputs.pixel_values					)

        # verify outputs
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     torch.Size((1, 100, 92)					)
        self.assertEqual(outputs.logits.shape ,					_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     torch.tensor(
            [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ,					device=_SCREAMING_SNAKE_CASE ,					)
        SCREAMING_SNAKE_CASE_				:  int           =     torch.tensor(
            [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ,					device=_SCREAMING_SNAKE_CASE					)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)
        self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)

        # verify postprocessing
        SCREAMING_SNAKE_CASE_				:  Tuple           =     image_processor.post_process_object_detection(
            _SCREAMING_SNAKE_CASE ,					threshold=0.3 ,					target_sizes=[image.size[::-1]]					)[0]
        SCREAMING_SNAKE_CASE_				:  Tuple           =     torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]					).to(_SCREAMING_SNAKE_CASE					)
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     [75, 75, 17, 63, 17]
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]					).to(_SCREAMING_SNAKE_CASE					)

        self.assertEqual(len(results['scores']					) ,					5					)
        self.assertTrue(torch.allclose(results['scores'] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)
        self.assertSequenceEqual(results['labels'].tolist() ,					_SCREAMING_SNAKE_CASE					)
        self.assertTrue(torch.allclose(results['boxes'][0, :] ,					_SCREAMING_SNAKE_CASE					)					)









def    A_  (							a  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  List[Any]           =     0
      while num > 0:
            digit_sum += num % 1_0
            num //= 1_0
      return digit_sum

def    A_  (							a = 1_0_0  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  List[str]           =     1
      SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     2

      for i in range(2					,   max_n + 1  ):
            SCREAMING_SNAKE_CASE_				:  List[str]           =     pre_numerator
            SCREAMING_SNAKE_CASE_				:  str           =     2 * i // 3 if i % 3 == 0 else 1
            SCREAMING_SNAKE_CASE_				:  Tuple           =     cur_numerator
            SCREAMING_SNAKE_CASE_				:  Tuple           =     e_cont * pre_numerator + temp

      return sum_digits(a  )


if __name__ == "__main__":
    print(F'{solution() = }')






