






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					:   Tuple							,   SCREAMING_SNAKE_CASE					:   str							,   SCREAMING_SNAKE_CASE					:   Dict=13							,   SCREAMING_SNAKE_CASE					:   int=[30, 30]							,   SCREAMING_SNAKE_CASE					:   Tuple=2							,   SCREAMING_SNAKE_CASE					:   Tuple=3							,   SCREAMING_SNAKE_CASE					:   List[str]=True							,   SCREAMING_SNAKE_CASE					:   str=True							,   SCREAMING_SNAKE_CASE					:   int=32							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=5							,   SCREAMING_SNAKE_CASE					:   Tuple=4							,   SCREAMING_SNAKE_CASE					:   Tuple=37							,   SCREAMING_SNAKE_CASE					:   int="gelu"							,   SCREAMING_SNAKE_CASE					:   Any=0.1							,   SCREAMING_SNAKE_CASE					:   List[str]=0.1							,   SCREAMING_SNAKE_CASE					:   Optional[int]=10							,   SCREAMING_SNAKE_CASE					:   List[str]=0.0_2							,   SCREAMING_SNAKE_CASE					:   int=3							,   SCREAMING_SNAKE_CASE					:   int=None							,   SCREAMING_SNAKE_CASE					:   Tuple=8							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=10							,   ):


      '''simple docstring'''






      UpperCamelCase__			:   Any       				=  parent
      UpperCamelCase__			:   int       				=  batch_size
      UpperCamelCase__			:   Optional[int]       				=  image_size
      UpperCamelCase__			:   Any       				=  patch_size
      UpperCamelCase__			:   Union[str, Any]       				=  num_channels
      UpperCamelCase__			:   str       				=  is_training
      UpperCamelCase__			:   List[Any]       				=  use_labels
      UpperCamelCase__			:   Tuple       				=  hidden_size
      UpperCamelCase__			:   str       				=  num_hidden_layers
      UpperCamelCase__			:   Dict       				=  num_attention_heads
      UpperCamelCase__			:   Any       				=  intermediate_size
      UpperCamelCase__			:   List[str]       				=  hidden_act
      UpperCamelCase__			:   Optional[Any]       				=  hidden_dropout_prob
      UpperCamelCase__			:   List[str]       				=  attention_probs_dropout_prob
      UpperCamelCase__			:   str       				=  type_sequence_label_size
      UpperCamelCase__			:   List[str]       				=  initializer_range
      UpperCamelCase__			:   Any       				=  num_labels
      UpperCamelCase__			:   List[str]       				=  scope
      UpperCamelCase__			:   List[str]       				=  n_targets
      UpperCamelCase__			:   List[str]       				=  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
      UpperCamelCase__			:   Union[str, Any]       				=  (image_size[1] // patch_size) * (image_size[0] // patch_size)
      UpperCamelCase__			:   str       				=  num_patches + 1 + self.num_detection_tokens







 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






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

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

      UpperCamelCase__			:   Union[str, Any]       				=  self.get_config()

      return config, pixel_values, labels







 def 					__lowercase					(		self					:   Dict						):


      '''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 					__lowercase					(		self					:   Union[str, Any]							,   SCREAMING_SNAKE_CASE					:   Optional[Any]							,   SCREAMING_SNAKE_CASE					:   List[Any]							,   SCREAMING_SNAKE_CASE					:   Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Union[str, Any]       				=  YolosModel(config=SCREAMING_SNAKE_CASE						)
      model.to(SCREAMING_SNAKE_CASE						)
      model.eval()
      UpperCamelCase__			:   Optional[int]       				=  model(SCREAMING_SNAKE_CASE						)
      self.parent.assertEqual(
          result.last_hidden_state.shape							,   (self.batch_size, self.expected_seq_len, self.hidden_size)						)







 def 					__lowercase					(		self					:   Any							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]							,   SCREAMING_SNAKE_CASE					:   str							,   SCREAMING_SNAKE_CASE					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   str       				=  YolosForObjectDetection(SCREAMING_SNAKE_CASE						)
      model.to(SCREAMING_SNAKE_CASE						)
      model.eval()

      UpperCamelCase__			:   Union[str, Any]       				=  model(pixel_values=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Any       				=  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)						)

      UpperCamelCase__			:   Dict       				=  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 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  self.prepare_config_and_inputs()
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   Dict       				=  config_and_inputs
      UpperCamelCase__			:   int       				=  {"pixel_values": pixel_values}
      return config, inputs_dict







@require_torch
class 			__a  (    A__       ,   A__       ,   unittest.TestCase       ):
 _lowerCAmelCase       :       int        = (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
 _lowerCAmelCase       :       Union[str, Any]        = (
     {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
 )

 _lowerCAmelCase       :       List[Any]        = False
 _lowerCAmelCase       :       Optional[Any]        = False
 _lowerCAmelCase       :       Union[str, Any]        = False
 _lowerCAmelCase       :       Optional[Any]        = False







 def 					__lowercase					(		self					:   str							,   SCREAMING_SNAKE_CASE					:   Any							,   SCREAMING_SNAKE_CASE					:   Any							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=False						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  super()._prepare_for_class(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   return_labels=SCREAMING_SNAKE_CASE						)

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

      return inputs_dict







 def 					__lowercase					(		self					:   Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Union[str, Any]       				=  YolosModelTester(self						)
      UpperCamelCase__			:   Union[str, Any]       				=  ConfigTester(self							,   config_class=SCREAMING_SNAKE_CASE							,   has_text_modality=SCREAMING_SNAKE_CASE							,   hidden_size=37						)







 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      self.config_tester.run_common_tests()







 def 					__lowercase					(		self					:   Dict						):


      '''simple docstring'''






      pass







 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__				,     UpperCamelCase__			:   int       				=  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           UpperCamelCase__			:   Dict       				=  model_class(SCREAMING_SNAKE_CASE						)
           self.assertIsInstance(model.get_input_embeddings()							,   (nn.Module)						)
           UpperCamelCase__			:   Union[str, Any]       				=  model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE							,   nn.Linear						)						)







 def 					__lowercase					(		self					:   Dict						):


      '''simple docstring'''






      UpperCamelCase__				,     UpperCamelCase__			:   List[str]       				=  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           UpperCamelCase__			:   str       				=  model_class(SCREAMING_SNAKE_CASE						)
           UpperCamelCase__			:   List[Any]       				=  inspect.signature(model.forward						)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           UpperCamelCase__			:   Optional[int]       				=  [*signature.parameters.keys()]

           UpperCamelCase__			:   Tuple       				=  ["pixel_values"]
           self.assertListEqual(arg_names[:1]							,   SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Any       				=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__				,     UpperCamelCase__			:   str       				=  self.model_tester.prepare_config_and_inputs_for_common()
      UpperCamelCase__			:   Dict       				=  True

      # in YOLOS, the seq_len is different
      UpperCamelCase__			:   int       				=  self.model_tester.expected_seq_len
      for model_class in self.all_model_classes:
           UpperCamelCase__			:   Optional[Any]       				=  True
           UpperCamelCase__			:   Dict       				=  False
           UpperCamelCase__			:   int       				=  True
           UpperCamelCase__			:   Any       				=  model_class(SCREAMING_SNAKE_CASE						)
           model.to(SCREAMING_SNAKE_CASE						)
           model.eval()
           with torch.no_grad():
                UpperCamelCase__			:   int       				=  model(**self._prepare_for_class(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)						)
           UpperCamelCase__			:   Dict       				=  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"]
           UpperCamelCase__			:   Any       				=  True
           UpperCamelCase__			:   List[str]       				=  model_class(SCREAMING_SNAKE_CASE						)
           model.to(SCREAMING_SNAKE_CASE						)
           model.eval()
           with torch.no_grad():
                UpperCamelCase__			:   Tuple       				=  model(**self._prepare_for_class(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)						)
           UpperCamelCase__			:   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]							,   )
           UpperCamelCase__			:   Tuple       				=  len(SCREAMING_SNAKE_CASE						)

           # Check attention is always last and order is fine
           UpperCamelCase__			:   Any       				=  True
           UpperCamelCase__			:   Optional[int]       				=  True
           UpperCamelCase__			:   str       				=  model_class(SCREAMING_SNAKE_CASE						)
           model.to(SCREAMING_SNAKE_CASE						)
           model.eval()
           with torch.no_grad():
                UpperCamelCase__			:   Optional[Any]       				=  model(**self._prepare_for_class(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)						)

           UpperCamelCase__			:   Tuple       				=  1
           self.assertEqual(out_len + added_hidden_states							,   len(SCREAMING_SNAKE_CASE						)						)

           UpperCamelCase__			:   int       				=  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 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      def check_hidden_states_output(SCREAMING_SNAKE_CASE					:   Any							,   SCREAMING_SNAKE_CASE					:   Dict							,   SCREAMING_SNAKE_CASE					:   Optional[int]						):
           UpperCamelCase__			:   Dict       				=  model_class(SCREAMING_SNAKE_CASE						)
           model.to(SCREAMING_SNAKE_CASE						)
           model.eval()

           with torch.no_grad():
                UpperCamelCase__			:   Optional[int]       				=  model(**self._prepare_for_class(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)						)

           UpperCamelCase__			:   List[Any]       				=  outputs.hidden_states

           UpperCamelCase__			:   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
           UpperCamelCase__			:   Dict       				=  self.model_tester.expected_seq_len

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

      UpperCamelCase__				,     UpperCamelCase__			:   int       				=  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           UpperCamelCase__			:   str       				=  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"]
           UpperCamelCase__			:   Union[str, Any]       				=  True

           check_hidden_states_output(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__			:   str       				=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_object_detection(*SCREAMING_SNAKE_CASE						)







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


      '''simple docstring'''






      for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__			:   str       				=  YolosModel.from_pretrained(SCREAMING_SNAKE_CASE						)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE						)







def 		SCREAMING_SNAKE_CASE							(					) ->	Dict:
     UpperCamelCase__			:   Dict       				=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
     return image





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







 @cached_property
 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






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







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


      '''simple docstring'''






      UpperCamelCase__			:   List[str]       				=  YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(SCREAMING_SNAKE_CASE						)

      UpperCamelCase__			:   List[str]       				=  self.default_image_processor
      UpperCamelCase__			:   List[Any]       				=  prepare_img()
      UpperCamelCase__			:   List[str]       				=  image_processor(images=SCREAMING_SNAKE_CASE							,   return_tensors="pt"						).to(SCREAMING_SNAKE_CASE						)

      # forward pass
      with torch.no_grad():
           UpperCamelCase__			:   List[Any]       				=  model(inputs.pixel_values						)

      # verify outputs
      UpperCamelCase__			:   List[Any]       				=  torch.Size((1, 1_00, 92)						)
      self.assertEqual(outputs.logits.shape							,   SCREAMING_SNAKE_CASE						)

      UpperCamelCase__			:   Dict       				=  torch.tensor(
          [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]							,   device=SCREAMING_SNAKE_CASE							,   )
      UpperCamelCase__			:   List[str]       				=  torch.tensor(
          [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]							,   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
      UpperCamelCase__			:   List[str]       				=  image_processor.post_process_object_detection(
          SCREAMING_SNAKE_CASE							,   threshold=0.3							,   target_sizes=[image.size[::-1]]						)[0]
      UpperCamelCase__			:   Optional[Any]       				=  torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]						).to(SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Dict       				=  [75, 75, 17, 63, 17]
      UpperCamelCase__			:   Tuple       				=  torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]						).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						)						)







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available


lowerCamelCase	:							int				={
    '''configuration_audio_spectrogram_transformer''': [
        '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''ASTConfig''',
    ]
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCamelCase	:							Union[str, Any]				=[
     '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''ASTForAudioClassification''',
     '''ASTModel''',
     '''ASTPreTrainedModel''',
 ]

try:
 if not is_speech_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCamelCase	:							Optional[int]				=['''ASTFeatureExtractor''']

if TYPE_CHECKING:
 from .configuration_audio_spectrogram_transformer import (
     AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
     ASTConfig,
 )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_audio_spectrogram_transformer import (
      AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      ASTForAudioClassification,
      ASTModel,
      ASTPreTrainedModel,
  )

 try:
  if not is_speech_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor


else:
 import sys

 lowerCamelCase	:							Optional[int]				=_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)