



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

 def 		_snake_case      (  self	: Optional[int]       ):
     snake_case_				:  List[Any]       =			floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]       )

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

     snake_case_				:  int       =			self.get_config()

     return config, pixel_values, labels

 def 		_snake_case      (  self	: 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=lowercase_						,  initializer_range=self.initializer_range						,  num_detection_tokens=self.num_detection_tokens						,  num_labels=self.num_labels						,  )

 def 		_snake_case      (  self	: List[Any]						,  lowercase_	: List[Any]						,  lowercase_	: Optional[Any]						,  lowercase_	: Any       ):
     snake_case_				:  Any       =			YolosModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Tuple       =			model(lowercase_       )
     self.parent.assertEqual(
         result.last_hidden_state.shape						,  (self.batch_size, self.expected_seq_len, self.hidden_size)       )

 def 		_snake_case      (  self	: List[Any]						,  lowercase_	: Dict						,  lowercase_	: str						,  lowercase_	: Optional[int]       ):
     snake_case_				:  Union[str, Any]       =			YolosForObjectDetection(lowercase_       )
     model.to(lowercase_       )
     model.eval()

     snake_case_				:  Any       =			model(pixel_values=lowercase_       )
     snake_case_				:  Optional[int]       =			model(lowercase_       )

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

     snake_case_				:  Optional[Any]       =			model(pixel_values=lowercase_						,  labels=lowercase_       )

     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 		_snake_case      (  self	: int       ):
     snake_case_				:  str       =			self.prepare_config_and_inputs()
     snake_case_,			snake_case_,			snake_case_				:  List[str]       =			config_and_inputs
     snake_case_				:  int       =			{'''pixel_values''': pixel_values}
     return config, inputs_dict





@require_torch
class  _UpperCAmelCase (    lowercase_					,  lowercase_					,  unittest.TestCase):
 _lowerCAmelCase     :    Any	      =	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
 _lowerCAmelCase     :    Dict	      =	(
     {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
 )

 _lowerCAmelCase     :    Optional[Any]	      =	False
 _lowerCAmelCase     :    Dict	      =	False
 _lowerCAmelCase     :    List[str]	      =	False
 _lowerCAmelCase     :    Optional[int]	      =	False

 def 		_snake_case      (  self	: Union[str, Any]						,  lowercase_	: Any						,  lowercase_	: List[str]						,  lowercase_	: Optional[Any]=False       ):
     snake_case_				:  str       =			super()._prepare_for_class(lowercase_						,  lowercase_						,  return_labels=lowercase_       )

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

     return inputs_dict

 def 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  Dict       =			YolosModelTester(self       )
     snake_case_				:  Any       =			ConfigTester(self						,  config_class=lowercase_						,  has_text_modality=lowercase_						,  hidden_size=37       )

 def 		_snake_case      (  self	: Tuple       ):
     self.config_tester.run_common_tests()

 def 		_snake_case      (  self	: Any       ):
     # YOLOS does not use inputs_embeds
     pass

 def 		_snake_case      (  self	: List[str]       ):
     snake_case_,			snake_case_				:  Tuple       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Optional[Any]       =			model_class(lowercase_       )
         self.assertIsInstance(model.get_input_embeddings()						,  (nn.Module)       )
         snake_case_				:  Any       =			model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(lowercase_						,  nn.Linear       )       )

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_,			snake_case_				:  Union[str, Any]       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Tuple       =			model_class(lowercase_       )
         snake_case_				:  Any       =			inspect.signature(model.forward       )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         snake_case_				:  Union[str, Any]       =			[*signature.parameters.keys()]

         snake_case_				:  Optional[Any]       =			['''pixel_values''']
         self.assertListEqual(arg_names[:1]						,  lowercase_       )

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  int       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )

 def 		_snake_case      (  self	: Tuple       ):
     snake_case_,			snake_case_				:  Optional[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()
     snake_case_				:  str       =			True

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

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

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

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

         snake_case_				:  Optional[Any]       =			1
         self.assertEqual(out_len + added_hidden_states						,  len(lowercase_       )       )

         snake_case_				:  Dict       =			outputs.attentions

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

         with torch.no_grad():
             snake_case_				:  Tuple       =			model(**self._prepare_for_class(lowercase_						,  lowercase_       )       )

         snake_case_				:  Optional[Any]       =			outputs.hidden_states

         snake_case_				:  int       =			getattr(
             self.model_tester						,  '''expected_num_hidden_layers'''						,  self.model_tester.num_hidden_layers + 1       )
         self.assertEqual(len(lowercase_       )						,  lowercase_       )

         # YOLOS has a different seq_length
         snake_case_				:  Optional[int]       =			self.model_tester.expected_seq_len

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

     snake_case_,			snake_case_				:  Tuple       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  str       =			True
         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         snake_case_				:  Any       =			True

         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

 def 		_snake_case      (  self	: Dict       ):
     snake_case_				:  int       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_object_detection(*lowercase_       )






 @slow
 def 		_snake_case      (  self	: List[str]       ):
     for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_				:  str       =			YolosModel.from_pretrained(lowercase_       )
         self.assertIsNotNone(lowercase_       )





def __lowercase    ( ):
    snake_case_				:  Union[str, Any]       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
    return image






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

 @cached_property
 def 		_snake_case      (  self	: List[str]       ):
     return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''       ) if is_vision_available() else None






 @slow
 def 		_snake_case      (  self	: Optional[Any]       ):
     snake_case_				:  List[str]       =			YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''       ).to(lowercase_       )

     snake_case_				:  str       =			self.default_image_processor
     snake_case_				:  str       =			prepare_img()
     snake_case_				:  Union[str, Any]       =			image_processor(images=lowercase_						,  return_tensors='''pt'''       ).to(lowercase_       )

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

     # verify outputs
     snake_case_				:  Tuple       =			torch.Size((1, 100, 92)       )
     self.assertEqual(outputs.logits.shape						,  lowercase_       )

     snake_case_				:  Union[str, Any]       =			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=lowercase_						,  )
     snake_case_				:  List[Any]       =			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=lowercase_       )
     self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]						,  lowercase_						,  atol=1E-4       )       )
     self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]						,  lowercase_						,  atol=1E-4       )       )

     # verify postprocessing
     snake_case_				:  List[Any]       =			image_processor.post_process_object_detection(
         lowercase_						,  threshold=0.3						,  target_sizes=[image.size[::-1]]       )[0]
     snake_case_				:  List[str]       =			torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]       ).to(lowercase_       )
     snake_case_				:  List[Any]       =			[75, 75, 17, 63, 17]
     snake_case_				:  Optional[Any]       =			torch.tensor([335.0609, 79.38_48, 375.4216, 187.2495]       ).to(lowercase_       )

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










"""simple docstring"""

lowercase__					:						Union[str, Any]												=			{
    '''Pillow''': '''Pillow''',
    '''accelerate''': '''accelerate>=0.11.0''',
    '''compel''': '''compel==0.1.8''',
    '''black''': '''black~=23.1''',
    '''datasets''': '''datasets''',
    '''filelock''': '''filelock''',
    '''flax''': '''flax>=0.4.1''',
    '''hf-doc-builder''': '''hf-doc-builder>=0.3.0''',
    '''huggingface-hub''': '''huggingface-hub>=0.13.2''',
    '''requests-mock''': '''requests-mock==1.10.0''',
    '''importlib_metadata''': '''importlib_metadata''',
    '''invisible-watermark''': '''invisible-watermark''',
    '''isort''': '''isort>=5.5.4''',
    '''jax''': '''jax>=0.2.8,!=0.3.2''',
    '''jaxlib''': '''jaxlib>=0.1.65''',
    '''Jinja2''': '''Jinja2''',
    '''k-diffusion''': '''k-diffusion>=0.0.12''',
    '''torchsde''': '''torchsde''',
    '''note_seq''': '''note_seq''',
    '''librosa''': '''librosa''',
    '''numpy''': '''numpy''',
    '''omegaconf''': '''omegaconf''',
    '''parameterized''': '''parameterized''',
    '''protobuf''': '''protobuf>=3.20.3,<4''',
    '''pytest''': '''pytest''',
    '''pytest-timeout''': '''pytest-timeout''',
    '''pytest-xdist''': '''pytest-xdist''',
    '''ruff''': '''ruff>=0.0.241''',
    '''safetensors''': '''safetensors''',
    '''sentencepiece''': '''sentencepiece>=0.1.91,!=0.1.92''',
    '''scipy''': '''scipy''',
    '''onnx''': '''onnx''',
    '''regex''': '''regex!=2019.12.17''',
    '''requests''': '''requests''',
    '''tensorboard''': '''tensorboard''',
    '''torch''': '''torch>=1.4''',
    '''torchvision''': '''torchvision''',
    '''transformers''': '''transformers>=4.25.1''',
    '''urllib3''': '''urllib3<=2.0.0''',
}





