





'''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 			UpperCAmelCase					:




      def __init__(      self      :			List[Any]      ,      __snake_case      :			List[Any]      ,      __snake_case      :			int=13      ,      __snake_case      :			List[str]=[30, 30]      ,      __snake_case      :			List[Any]=2      ,      __snake_case      :			Any=3      ,      __snake_case      :			str=True      ,      __snake_case      :			Union[str, Any]=True      ,      __snake_case      :			int=32      ,      __snake_case      :			List[str]=5      ,      __snake_case      :			Union[str, Any]=4      ,      __snake_case      :			List[str]=37      ,      __snake_case      :			Union[str, Any]="gelu"      ,      __snake_case      :			Optional[Any]=0.1      ,      __snake_case      :			List[str]=0.1      ,      __snake_case      :			Dict=10      ,      __snake_case      :			List[str]=0.02      ,      __snake_case      :			Dict=3      ,      __snake_case      :			Tuple=None      ,      __snake_case      :			Tuple=8      ,      __snake_case      :			Dict=10      ,      )    ->				Optional[Any]:
            _lowerCAmelCase												=							parent
            _lowerCAmelCase												=							batch_size
            _lowerCAmelCase												=							image_size
            _lowerCAmelCase												=							patch_size
            _lowerCAmelCase												=							num_channels
            _lowerCAmelCase												=							is_training
            _lowerCAmelCase												=							use_labels
            _lowerCAmelCase												=							hidden_size
            _lowerCAmelCase												=							num_hidden_layers
            _lowerCAmelCase												=							num_attention_heads
            _lowerCAmelCase												=							intermediate_size
            _lowerCAmelCase												=							hidden_act
            _lowerCAmelCase												=							hidden_dropout_prob
            _lowerCAmelCase												=							attention_probs_dropout_prob
            _lowerCAmelCase												=							type_sequence_label_size
            _lowerCAmelCase												=							initializer_range
            _lowerCAmelCase												=							num_labels
            _lowerCAmelCase												=							scope
            _lowerCAmelCase												=							n_targets
            _lowerCAmelCase												=							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
            _lowerCAmelCase												=							(image_size[1] // patch_size) * (image_size[0] // patch_size)
            _lowerCAmelCase												=							num_patches + 1 + self.num_detection_tokens




      def     lowercase__   (      self      :			int  )    ->				Optional[Any]:
            _lowerCAmelCase												=							floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]  )

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

            _lowerCAmelCase												=							self.get_config()

            return config, pixel_values, labels




      def     lowercase__   (      self      :			str  )    ->				List[Any]:
            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=__snake_case      ,      initializer_range=self.initializer_range      ,      num_detection_tokens=self.num_detection_tokens      ,      num_labels=self.num_labels      ,      )




      def     lowercase__   (      self      :			int      ,      __snake_case      :			Optional[Any]      ,      __snake_case      :			Any      ,      __snake_case      :			Optional[Any]  )    ->				int:
            _lowerCAmelCase												=							YolosModel(config=__snake_case  )
            model.to(__snake_case  )
            model.eval()
            _lowerCAmelCase												=							model(__snake_case  )
            self.parent.assertEqual(
                result.last_hidden_state.shape      ,      (self.batch_size, self.expected_seq_len, self.hidden_size)  )




      def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			Union[str, Any]      ,      __snake_case      :			List[Any]      ,      __snake_case      :			int  )    ->				int:
            _lowerCAmelCase												=							YolosForObjectDetection(__snake_case  )
            model.to(__snake_case  )
            model.eval()

            _lowerCAmelCase												=							model(pixel_values=__snake_case  )
            _lowerCAmelCase												=							model(__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)  )

            _lowerCAmelCase												=							model(pixel_values=__snake_case      ,      labels=__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     lowercase__   (      self      :			Optional[int]  )    ->				List[Any]:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            _lowerCAmelCase					,							_lowerCAmelCase					,							_lowerCAmelCase												=							config_and_inputs
            _lowerCAmelCase												=							{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_torch
class 			UpperCAmelCase					(      snake_case_							,		snake_case_							,		unittest.TestCase       ):
      _lowercase:      Any											=       (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      _lowercase:      List[Any]											=       (
          {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
      )

      _lowercase:      Dict											=       False
      _lowercase:      Union[str, Any]											=       False
      _lowercase:      int											=       False
      _lowercase:      Tuple											=       False




      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			int      ,      __snake_case      :			Any      ,      __snake_case      :			List[Any]=False  )    ->				Optional[int]:
            _lowerCAmelCase												=							super()._prepare_for_class(__snake_case      ,      __snake_case      ,      return_labels=__snake_case  )

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

            return inputs_dict




      def     lowercase__   (      self      :			Optional[Any]  )    ->				Any:
            _lowerCAmelCase												=							YolosModelTester(self  )
            _lowerCAmelCase												=							ConfigTester(self      ,      config_class=__snake_case      ,      has_text_modality=__snake_case      ,      hidden_size=37  )




      def     lowercase__   (      self      :			str  )    ->				int:
            self.config_tester.run_common_tests()




      def     lowercase__   (      self      :			int  )    ->				Any:
            # YOLOS does not use inputs_embeds
            pass




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				List[str]:
            _lowerCAmelCase					,							_lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs_for_common()

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




      def     lowercase__   (      self      :			Optional[int]  )    ->				Union[str, Any]:
            _lowerCAmelCase					,							_lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs_for_common()

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

                  _lowerCAmelCase												=							["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]      ,      __snake_case  )




      def     lowercase__   (      self      :			str  )    ->				Optional[Any]:
            _lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__snake_case  )




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				List[Any]:
            _lowerCAmelCase					,							_lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs_for_common()
            _lowerCAmelCase												=							True

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

                  # check that output_attentions also work using config
                  del inputs_dict["output_attentions"]
                  _lowerCAmelCase												=							True
                  _lowerCAmelCase												=							model_class(__snake_case  )
                  model.to(__snake_case  )
                  model.eval()
                  with torch.no_grad():
                        _lowerCAmelCase												=							model(**self._prepare_for_class(__snake_case      ,      __snake_case  )  )
                  _lowerCAmelCase												=							outputs.attentions
                  self.assertEqual(len(__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]      ,      )
                  _lowerCAmelCase												=							len(__snake_case  )

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

                  _lowerCAmelCase												=							1
                  self.assertEqual(out_len + added_hidden_states      ,      len(__snake_case  )  )

                  _lowerCAmelCase												=							outputs.attentions

                  self.assertEqual(len(__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     lowercase__   (      self      :			List[str]  )    ->				Any:
            def check_hidden_states_output(__snake_case      :			Tuple      ,      __snake_case      :			Tuple      ,      __snake_case      :			Optional[int]  ):
                  _lowerCAmelCase												=							model_class(__snake_case  )
                  model.to(__snake_case  )
                  model.eval()

                  with torch.no_grad():
                        _lowerCAmelCase												=							model(**self._prepare_for_class(__snake_case      ,      __snake_case  )  )

                  _lowerCAmelCase												=							outputs.hidden_states

                  _lowerCAmelCase												=							getattr(
                      self.model_tester      ,      """expected_num_hidden_layers"""      ,      self.model_tester.num_hidden_layers + 1  )
                  self.assertEqual(len(__snake_case  )      ,      __snake_case  )

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

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

            _lowerCAmelCase					,							_lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  _lowerCAmelCase												=							True
                  check_hidden_states_output(__snake_case      ,      __snake_case      ,      __snake_case  )

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

                  check_hidden_states_output(__snake_case      ,      __snake_case      ,      __snake_case  )




      def     lowercase__   (      self      :			str  )    ->				int:
            _lowerCAmelCase												=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_object_detection(*__snake_case  )




      @slow
      def     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[int]:
            for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _lowerCAmelCase												=							YolosModel.from_pretrained(__snake_case  )
                  self.assertIsNotNone(__snake_case  )




def        UpperCamelCase__				(		) ->    Dict:





      """simple docstring"""


      _lowerCAmelCase												=							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
      return image





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




      @cached_property
      def     lowercase__   (      self      :			str  )    ->				Dict:
            return AutoImageProcessor.from_pretrained("""hustvl/yolos-small"""  ) if is_vision_available() else None




      @slow
      def     lowercase__   (      self      :			str  )    ->				Optional[Any]:
            _lowerCAmelCase												=							YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""  ).to(__snake_case  )

            _lowerCAmelCase												=							self.default_image_processor
            _lowerCAmelCase												=							prepare_img()
            _lowerCAmelCase												=							image_processor(images=__snake_case      ,      return_tensors="""pt"""  ).to(__snake_case  )

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

            # verify outputs
            _lowerCAmelCase												=							torch.Size((1, 1_00, 92)  )
            self.assertEqual(outputs.logits.shape      ,      __snake_case  )

            _lowerCAmelCase												=							torch.tensor(
                [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]      ,      device=__snake_case      ,      )
            _lowerCAmelCase												=							torch.tensor(
                [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]      ,      device=__snake_case  )
            self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]      ,      __snake_case      ,      atol=1E-4  )  )
            self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]      ,      __snake_case      ,      atol=1E-4  )  )

            # verify postprocessing
            _lowerCAmelCase												=							image_processor.post_process_object_detection(
                __snake_case      ,      threshold=0.3      ,      target_sizes=[image.size[::-1]]  )[0]
            _lowerCAmelCase												=							torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]  ).to(__snake_case  )
            _lowerCAmelCase												=							[75, 75, 17, 63, 17]
            _lowerCAmelCase												=							torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]  ).to(__snake_case  )

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













'''simple docstring'''






def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase  ):





      """simple docstring"""


      if not (isinstance(lowerCAmelCase							,     lowerCAmelCase  ) and isinstance(lowerCAmelCase							,     lowerCAmelCase  )):
            raise ValueError("""longest_common_substring() takes two strings for inputs"""  )

      _lowerCAmelCase												=							len(lowerCAmelCase  )
      _lowerCAmelCase												=							len(lowerCAmelCase  )

      _lowerCAmelCase												=							[[0] * (texta_length + 1) for _ in range(texta_length + 1  )]
      _lowerCAmelCase												=							0
      _lowerCAmelCase												=							0

      for i in range(1							,     texta_length + 1  ):
            for j in range(1							,     texta_length + 1  ):
                  if texta[i - 1] == texta[j - 1]:
                        _lowerCAmelCase												=							1 + dp[i - 1][j - 1]
                        if dp[i][j] > ans_length:
                              _lowerCAmelCase												=							i
                              _lowerCAmelCase												=							dp[i][j]

      return texta[ans_index - ans_length : ans_index]


if __name__ == "__main__":
      import doctest

      doctest.testmod()






