





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





											'''simple docstring'''





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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





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

											_snake_case:   Any  					=		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:   Union[str, Any]  					=		[]
																	for i in range(self.batch_size       ):
																							_snake_case:   List[str]  					=		{}
																							_snake_case:   str  					=		torch.randint(
																							    high=self.num_labels       ,     size=(self.n_targets,)       ,     device=__snake_case       )
																							_snake_case:   Union[str, Any]  					=		torch.rand(self.n_targets       ,     4       ,     device=__snake_case       )
																							labels.append(__snake_case       )

											_snake_case:   List[str]  					=		self.get_config()

											return config, pixel_values, labels


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''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=__snake_case       ,     initializer_range=self.initializer_range       ,     num_detection_tokens=self.num_detection_tokens       ,     num_labels=self.num_labels       ,     )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  List[str]       ,     __snake_case	:  str       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		YolosModel(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Tuple  					=		model(__snake_case       )
											self.parent.assertEqual(
											    result.last_hidden_state.shape       ,     (self.batch_size, self.expected_seq_len, self.hidden_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  Dict       ,     __snake_case	:  List[str]       ,     __snake_case	:  int       ):





											'''simple docstring'''





											_snake_case:   str  					=		YolosForObjectDetection(__snake_case       )
											model.to(__snake_case       )
											model.eval()

											_snake_case:   int  					=		model(pixel_values=__snake_case       )
											_snake_case:   List[Any]  					=		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)       )

											_snake_case:   Optional[Any]  					=		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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.prepare_config_and_inputs()
											_snake_case					,						_snake_case					,						_snake_case:   Optional[int]  					=		config_and_inputs
											_snake_case:   int  					=		{'pixel_values': pixel_values}
											return config, inputs_dict







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

					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  List[str]=False       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		super()._prepare_for_class(__snake_case       ,     __snake_case       ,     return_labels=__snake_case       )

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

											return inputs_dict


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		YolosModelTester(self       )
											_snake_case:   Tuple  					=		ConfigTester(self       ,     config_class=__snake_case       ,     has_text_modality=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





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

											for model_class in self.all_model_classes:
																	_snake_case:   List[str]  					=		model_class(__snake_case       )
																	self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module)       )
																	_snake_case:   Tuple  					=		model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(__snake_case       ,     nn.Linear       )       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_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:   str  					=		model_class(__snake_case       )
																	_snake_case:   List[str]  					=		inspect.signature(model.forward       )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	_snake_case:   List[str]  					=		[*signature.parameters.keys()]

																	_snake_case:   Dict  					=		['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,     __snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()
											_snake_case:   int  					=		True

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

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

																	_snake_case:   List[str]  					=		1
																	self.assertEqual(out_len + added_hidden_states       ,     len(__snake_case       )       )

																	_snake_case:   Dict  					=		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    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											def check_hidden_states_output(__snake_case	:  Dict       ,     __snake_case	:  str       ,     __snake_case	:  List[Any]       ):
																	_snake_case:   List[str]  					=		model_class(__snake_case       )
																	model.to(__snake_case       )
																	model.eval()

																	with torch.no_grad():
																							_snake_case:   List[str]  					=		model(**self._prepare_for_class(__snake_case       ,     __snake_case       )       )

																	_snake_case:   Dict  					=		outputs.hidden_states

																	_snake_case:   List[str]  					=		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
																	_snake_case:   Union[str, Any]  					=		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:   int  					=		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	_snake_case:   Optional[Any]  					=		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"]
																	_snake_case:   Dict  					=		True

																	check_hidden_states_output(__snake_case       ,     __snake_case       ,     __snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_object_detection(*__snake_case       )




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_snake_case:   List[str]  					=		YolosModel.from_pretrained(__snake_case       )
																	self.assertIsNotNone(__snake_case       )





def       lowercase_      (		)   ->Tuple:
						_snake_case:   Union[str, Any]  					=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image







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


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





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




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		YolosForObjectDetection.from_pretrained('hustvl/yolos-small'       ).to(__snake_case       )

											_snake_case:   List[Any]  					=		self.default_image_processor
											_snake_case:   List[str]  					=		prepare_img()
											_snake_case:   List[Any]  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       ).to(__snake_case       )

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

											# verify outputs
											_snake_case:   Optional[int]  					=		torch.Size((1, 1_00, 92)       )
											self.assertEqual(outputs.logits.shape       ,     __snake_case       )

											_snake_case:   List[Any]  					=		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=__snake_case       ,     )
											_snake_case:   Dict  					=		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=__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
											_snake_case:   Optional[Any]  					=		image_processor.post_process_object_detection(
											    __snake_case       ,     threshold=0.3       ,     target_sizes=[image.size[::-1]]       )[0]
											_snake_case:   Tuple  					=		torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]       ).to(__snake_case       )
											_snake_case:   Union[str, Any]  					=		[75, 75, 17, 63, 17]
											_snake_case:   List[Any]  					=		torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]       ).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'''






from ..utils import DummyObject, requires_backends







class 			lowerCamelCase					(						metaclass=__UpperCAmelCase  ):
					_SCREAMING_SNAKE_CASE							   =    ["torch", "scipy"]


					def __init__(					self	:  Tuple       ,     *__snake_case	:  List[Any]       ,     **__snake_case	:  List[Any]       ):





											'''simple docstring'''





											requires_backends(self       ,     ['torch', 'scipy']       )


					@classmethod
					def    SCREAMING_SNAKE_CASE_		(					cls	:  Optional[int]       ,     *__snake_case	:  Optional[Any]       ,     **__snake_case	:  Tuple       ):





											'''simple docstring'''





											requires_backends(cls       ,     ['torch', 'scipy']       )




					@classmethod
					def    SCREAMING_SNAKE_CASE_		(					cls	:  List[Any]       ,     *__snake_case	:  Optional[Any]       ,     **__snake_case	:  str       ):





											'''simple docstring'''





											requires_backends(cls       ,     ['torch', 'scipy']       )





