

'''simple docstring'''





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 				__lowerCAmelCase  :




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






        _lowercase			 =parent
        _lowercase			 =batch_size
        _lowercase			 =image_size
        _lowercase			 =patch_size
        _lowercase			 =num_channels
        _lowercase			 =is_training
        _lowercase			 =use_labels
        _lowercase			 =hidden_size
        _lowercase			 =num_hidden_layers
        _lowercase			 =num_attention_heads
        _lowercase			 =intermediate_size
        _lowercase			 =hidden_act
        _lowercase			 =hidden_dropout_prob
        _lowercase			 =attention_probs_dropout_prob
        _lowercase			 =type_sequence_label_size
        _lowercase			 =initializer_range
        _lowercase			 =num_labels
        _lowercase			 =scope
        _lowercase			 =n_targets
        _lowercase			 =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
        _lowercase			 =(image_size[1] // patch_size) * (image_size[0] // patch_size)
        _lowercase			 =num_patches + 1 + self.num_detection_tokens




  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






        _lowercase			 =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]      )

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

        _lowercase			 =self.get_config()

        return config, pixel_values, labels




  def 						A__  (       self      )						->				Optional[Any]:
        '''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=lowerCAmelCase							,     initializer_range=self.initializer_range							,     num_detection_tokens=self.num_detection_tokens							,     num_labels=self.num_labels							,     )




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Tuple:
        '''simple docstring'''






        _lowercase			 =YolosModel(config=lowerCAmelCase      )
        model.to(lowerCAmelCase      )
        model.eval()
        _lowercase			 =model(lowerCAmelCase      )
        self.parent.assertEqual(
            result.last_hidden_state.shape							,     (self.batch_size, self.expected_seq_len, self.hidden_size)      )




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Any:
        '''simple docstring'''






        _lowercase			 =YolosForObjectDetection(lowerCAmelCase      )
        model.to(lowerCAmelCase      )
        model.eval()

        _lowercase			 =model(pixel_values=lowerCAmelCase      )
        _lowercase			 =model(lowerCAmelCase      )

        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)      )

        _lowercase			 =model(pixel_values=lowerCAmelCase							,     labels=lowerCAmelCase      )

        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 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






        _lowercase			 =self.prepare_config_and_inputs()
        _lowercase			 =config_and_inputs
        _lowercase			 ={'''pixel_values''': pixel_values}
        return config, inputs_dict





@require_torch
class 				__lowerCAmelCase  (      __A    ,    __A    ,    unittest.TestCase							):
  _a		    =						(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
  _a		    =						(
      {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
  )

  _a		    =						False
  _a		    =						False
  _a		    =						False
  _a		    =						False




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase=False      )						->				Any:
        '''simple docstring'''






        _lowercase			 =super()._prepare_for_class(lowerCAmelCase							,     lowerCAmelCase							,     return_labels=lowerCAmelCase      )

        if return_labels:
              if model_class.__name__ == "YolosForObjectDetection":
                    _lowercase			 =[]
                    for i in range(self.model_tester.batch_size      ):
                          _lowercase			 ={}
                          _lowercase			 =torch.ones(
                              size=(self.model_tester.n_targets,)							,     device=lowerCAmelCase							,     dtype=torch.long      )
                          _lowercase			 =torch.ones(
                              self.model_tester.n_targets							,     4							,     device=lowerCAmelCase							,     dtype=torch.float      )
                          labels.append(lowerCAmelCase      )
                    _lowercase			 =labels

        return inputs_dict




  def 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






        _lowercase			 =YolosModelTester(self      )
        _lowercase			 =ConfigTester(self							,     config_class=lowerCAmelCase							,     has_text_modality=lowerCAmelCase							,     hidden_size=37      )




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        self.config_tester.run_common_tests()




  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






        pass




  def 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()

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




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()

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

              _lowercase			 =['''pixel_values''']
              self.assertListEqual(arg_names[:1]							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase      )




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()
        _lowercase			 =True

        # in YOLOS, the seq_len is different
        _lowercase			 =self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
              _lowercase			 =True
              _lowercase			 =False
              _lowercase			 =True
              _lowercase			 =model_class(lowerCAmelCase      )
              model.to(lowerCAmelCase      )
              model.eval()
              with torch.no_grad():
                    _lowercase			 =model(**self._prepare_for_class(lowerCAmelCase							,     lowerCAmelCase      )      )
              _lowercase			 =outputs.attentions
              self.assertEqual(len(lowerCAmelCase      )							,     self.model_tester.num_hidden_layers      )

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

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

              # Check attention is always last and order is fine
              _lowercase			 =True
              _lowercase			 =True
              _lowercase			 =model_class(lowerCAmelCase      )
              model.to(lowerCAmelCase      )
              model.eval()
              with torch.no_grad():
                    _lowercase			 =model(**self._prepare_for_class(lowerCAmelCase							,     lowerCAmelCase      )      )

              _lowercase			 =1
              self.assertEqual(out_len + added_hidden_states							,     len(lowerCAmelCase      )      )

              _lowercase			 =outputs.attentions

              self.assertEqual(len(lowerCAmelCase      )							,     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 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        def check_hidden_states_output(lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      ):
              _lowercase			 =model_class(lowerCAmelCase      )
              model.to(lowerCAmelCase      )
              model.eval()

              with torch.no_grad():
                    _lowercase			 =model(**self._prepare_for_class(lowerCAmelCase							,     lowerCAmelCase      )      )

              _lowercase			 =outputs.hidden_states

              _lowercase			 =getattr(
                  self.model_tester							,     'expected_num_hidden_layers'							,     self.model_tester.num_hidden_layers + 1      )
              self.assertEqual(len(lowerCAmelCase      )							,     lowerCAmelCase      )

              # YOLOS has a different seq_length
              _lowercase			 =self.model_tester.expected_seq_len

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

        _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _lowercase			 =True
              check_hidden_states_output(lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              _lowercase			 =True

              check_hidden_states_output(lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*lowerCAmelCase      )




  @slow
  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowercase			 =YolosModel.from_pretrained(lowerCAmelCase      )
              self.assertIsNotNone(lowerCAmelCase      )
def   a   (    )					->   List[str]:





      """simple docstring"""



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







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




  @cached_property
  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






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




  @slow
  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        _lowercase			 =YolosForObjectDetection.from_pretrained('hustvl/yolos-small'      ).to(lowerCAmelCase      )

        _lowercase			 =self.default_image_processor
        _lowercase			 =prepare_img()
        _lowercase			 =image_processor(images=lowerCAmelCase							,     return_tensors='pt'      ).to(lowerCAmelCase      )

        # forward pass
        with torch.no_grad():
              _lowercase			 =model(inputs.pixel_values      )

        # verify outputs
        _lowercase			 =torch.Size((1, 100, 92)      )
        self.assertEqual(outputs.logits.shape							,     lowerCAmelCase      )

        _lowercase			 =torch.tensor(
            [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]]							,     device=lowerCAmelCase							,     )
        _lowercase			 =torch.tensor(
            [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]							,     device=lowerCAmelCase      )
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]							,     lowerCAmelCase							,     atol=1e-4      )      )
        self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]							,     lowerCAmelCase							,     atol=1e-4      )      )

        # verify postprocessing
        _lowercase			 =image_processor.post_process_object_detection(
            lowerCAmelCase							,     threshold=0.3							,     target_sizes=[image.size[::-1]]      )[0]
        _lowercase			 =torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]      ).to(lowerCAmelCase      )
        _lowercase			 =[75, 75, 17, 63, 17]
        _lowercase			 =torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]      ).to(lowerCAmelCase      )

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





import os
def   a   (    )					->   Optional[int]:





      """simple docstring"""



      with open(os.path.dirname(A__  ) + '/grid.txt'  ) as f:
            _lowercase			 =[]  # noqa: E741
            for _ in range(20  ):
                  l.append([int(A__  ) for x in f.readline().split()]  )

            _lowercase			 =0

            # right
            for i in range(20  ):
                  for j in range(17  ):
                        _lowercase			 =l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3]
                        if temp > maximum:
                              _lowercase			 =temp

        # down
            for i in range(17  ):
                  for j in range(20  ):
                        _lowercase			 =l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j]
                        if temp > maximum:
                              _lowercase			 =temp

        # diagonal 1
            for i in range(17  ):
                  for j in range(17  ):
                        _lowercase			 =l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3]
                        if temp > maximum:
                              _lowercase			 =temp

        # diagonal 2
            for i in range(17  ):
                  for j in range(3   ,     20  ):
                        _lowercase			 =l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3]
                        if temp > maximum:
                              _lowercase			 =temp
            return maximum


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


