



"""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    SCREAMING_SNAKE_CASE__ :

    def __init__(				self			:				List[str] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Any=1_3 ,  lowerCAmelCase_			:				Any=[3_0, 3_0] ,  lowerCAmelCase_			:				Dict=2 ,  lowerCAmelCase_			:				Optional[int]=3 ,  lowerCAmelCase_			:				str=True ,  lowerCAmelCase_			:				List[str]=True ,  lowerCAmelCase_			:				Union[str, Any]=3_2 ,  lowerCAmelCase_			:				Optional[int]=5 ,  lowerCAmelCase_			:				Optional[Any]=4 ,  lowerCAmelCase_			:				Optional[Any]=3_7 ,  lowerCAmelCase_			:				int="gelu" ,  lowerCAmelCase_			:				int=0.1 ,  lowerCAmelCase_			:				str=0.1 ,  lowerCAmelCase_			:				Tuple=1_0 ,  lowerCAmelCase_			:				Tuple=0.02 ,  lowerCAmelCase_			:				List[str]=3 ,  lowerCAmelCase_			:				Union[str, Any]=None ,  lowerCAmelCase_			:				Optional[Any]=8 ,  lowerCAmelCase_			:				Dict=1_0 ,  ):







      """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 					_UpperCAmelCase	(				self			:				Tuple):







      """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 					_UpperCAmelCase	(				self			:				Union[str, 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 					_UpperCAmelCase	(				self			:				List[Any] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Optional[Any]):







      """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 					_UpperCAmelCase	(				self			:				Union[str, Any] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				str):







      """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 					_UpperCAmelCase	(				self			:				Union[str, Any]):







      """simple docstring"""







      lowercase_								= self.prepare_config_and_inputs()
      lowercase_					,    lowercase_					,    lowercase_								= config_and_inputs
      lowercase_								= {"""pixel_values""": pixel_values}
      return config, inputs_dict







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

    lowercase__      =   False
    lowercase__      =   False
    lowercase__      =   False
    lowercase__      =   False

    def 					_UpperCAmelCase	(				self			:				List[str] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				Dict ,  lowerCAmelCase_			:				List[str]=False):







      """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 					_UpperCAmelCase	(				self			:				Optional[Any]):







      """simple docstring"""







      lowercase_								= YolosModelTester(self)
      lowercase_								= ConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_ ,  hidden_size=3_7)

    def 					_UpperCAmelCase	(				self			:				int):







      """simple docstring"""







      self.config_tester.run_common_tests()

    def 					_UpperCAmelCase	(				self			:				str):







      """simple docstring"""







      pass

    def 					_UpperCAmelCase	(				self			:				Optional[Any]):







      """simple docstring"""







      lowercase_					,    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 					_UpperCAmelCase	(				self			:				List[Any]):







      """simple docstring"""







      lowercase_					,    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 					_UpperCAmelCase	(				self			:				int):







      """simple docstring"""







      lowercase_								= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase_)

    def 					_UpperCAmelCase	(				self			:				List[str]):







      """simple docstring"""







      lowercase_					,    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 					_UpperCAmelCase	(				self			:				int):







      """simple docstring"""







      def check_hidden_states_output(lowerCAmelCase_			:				Union[str, Any] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Optional[Any]):
        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_					,    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 					_UpperCAmelCase	(				self			:				Tuple):







      """simple docstring"""







      lowercase_								= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_object_detection(*lowerCAmelCase_)




    @slow
    def 					_UpperCAmelCase	(				self			:				Optional[Any]):







      """simple docstring"""







      for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase_								= YolosModel.from_pretrained(lowerCAmelCase_)
        self.assertIsNotNone(lowerCAmelCase_)







def 			_SCREAMING_SNAKE_CASE						() ->						Dict:







  '''simple docstring'''


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


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

    @cached_property
    def 					_UpperCAmelCase	(				self			:				int):







      """simple docstring"""







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




    @slow
    def 					_UpperCAmelCase	(				self			:				Union[str, Any]):







      """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, 1_0_0, 9_2))
      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.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] ,  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.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]).to(lowerCAmelCase_)
      lowercase_								= [7_5, 7_5, 1_7, 6_3, 1_7]
      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_))






"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase						:		List[Any]			= logging.get_logger(__name__)

UpperCAmelCase						:		Optional[Any]			= {
    "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json",
}


class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase   ):
    lowercase__      =   "mgp-str"

    def __init__(				self			:				Optional[Any] ,  lowerCAmelCase_			:				Optional[Any]=[3_2, 1_2_8] ,  lowerCAmelCase_			:				Union[str, Any]=4 ,  lowerCAmelCase_			:				Dict=3 ,  lowerCAmelCase_			:				List[str]=2_7 ,  lowerCAmelCase_			:				str=3_8 ,  lowerCAmelCase_			:				Optional[int]=5_0_2_5_7 ,  lowerCAmelCase_			:				Any=3_0_5_2_2 ,  lowerCAmelCase_			:				str=7_6_8 ,  lowerCAmelCase_			:				Any=1_2 ,  lowerCAmelCase_			:				Optional[Any]=1_2 ,  lowerCAmelCase_			:				Tuple=4.0 ,  lowerCAmelCase_			:				str=True ,  lowerCAmelCase_			:				List[str]=False ,  lowerCAmelCase_			:				List[Any]=1E-5 ,  lowerCAmelCase_			:				Any=0.0 ,  lowerCAmelCase_			:				int=0.0 ,  lowerCAmelCase_			:				str=0.0 ,  lowerCAmelCase_			:				Dict=False ,  lowerCAmelCase_			:				List[str]=0.02 ,  **lowerCAmelCase_			:				str ,  ):







      """simple docstring"""







      super().__init__(**lowerCAmelCase_)

      lowercase_								= image_size
      lowercase_								= patch_size
      lowercase_								= num_channels
      lowercase_								= max_token_length
      lowercase_								= num_character_labels
      lowercase_								= num_bpe_labels
      lowercase_								= num_wordpiece_labels
      lowercase_								= hidden_size
      lowercase_								= num_hidden_layers
      lowercase_								= num_attention_heads
      lowercase_								= mlp_ratio
      lowercase_								= distilled
      lowercase_								= layer_norm_eps
      lowercase_								= drop_rate
      lowercase_								= qkv_bias
      lowercase_								= attn_drop_rate
      lowercase_								= drop_path_rate
      lowercase_								= output_aa_attentions
      lowercase_								= initializer_range

