

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







			def __init__(			self			: Dict			,  lowercase			: Optional[int]			,  lowercase			: Union[str, Any]=13			,  lowercase			: Optional[int]=[30, 30]			,  lowercase			: List[Any]=2			,  lowercase			: Tuple=3			,  lowercase			: Optional[Any]=True			,  lowercase			: Any=True			,  lowercase			: List[str]=32			,  lowercase			: str=5			,  lowercase			: List[str]=4			,  lowercase			: Dict=37			,  lowercase			: List[str]="gelu"			,  lowercase			: Optional[int]=0.1			,  lowercase			: Any=0.1			,  lowercase			: Union[str, Any]=10			,  lowercase			: int=0.0_2			,  lowercase			: List[str]=3			,  lowercase			: Optional[int]=None			,  lowercase			: int=8			,  lowercase			: Union[str, Any]=10			,  ):





								'''simple docstring'''



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







			def 			__lowerCAmelCase				(			self			: List[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   str      =				floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]  )

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

								UpperCAmelCase			:   str      =				self.get_config()

								return config, pixel_values, labels







			def 			__lowerCAmelCase				(			self			: List[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=lowercase			,  initializer_range=self.initializer_range			,  num_detection_tokens=self.num_detection_tokens			,  num_labels=self.num_labels			,  )







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: str			,  lowercase			: List[str]			,  lowercase			: Any  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				YolosModel(config=lowercase  )
								model.to(lowercase  )
								model.eval()
								UpperCAmelCase			:   str      =				model(lowercase  )
								self.parent.assertEqual(
								    result.last_hidden_state.shape			,  (self.batch_size, self.expected_seq_len, self.hidden_size)  )







			def 			__lowerCAmelCase				(			self			: int			,  lowercase			: Optional[int]			,  lowercase			: Tuple			,  lowercase			: List[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[str]      =				YolosForObjectDetection(lowercase  )
								model.to(lowercase  )
								model.eval()

								UpperCAmelCase			:   int      =				model(pixel_values=lowercase  )
								UpperCAmelCase			:   Any      =				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)  )

								UpperCAmelCase			:   List[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 			__lowerCAmelCase				(			self			: List[str]  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[str]      =				self.prepare_config_and_inputs()
								UpperCAmelCase      ,							UpperCAmelCase      ,							UpperCAmelCase			:   Optional[int]      =				config_and_inputs
								UpperCAmelCase			:   Union[str, Any]      =				{"pixel_values": pixel_values}
								return config, inputs_dict







@require_torch
class       snake_case__  ( lowerCAmelCase_					,  lowerCAmelCase_					,  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 			__lowerCAmelCase				(			self			: str			,  lowercase			: Tuple			,  lowercase			: Any			,  lowercase			: Tuple=False  ):





								'''simple docstring'''



								UpperCAmelCase			:   int      =				super()._prepare_for_class(lowercase			,  lowercase			,  return_labels=lowercase  )

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

								return inputs_dict







			def 			__lowerCAmelCase				(			self			: int  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				YolosModelTester(self  )
								UpperCAmelCase			:   int      =				ConfigTester(self			,  config_class=lowercase			,  has_text_modality=lowercase			,  hidden_size=37  )







			def 			__lowerCAmelCase				(			self			: Tuple  ):





								'''simple docstring'''



								self.config_tester.run_common_tests()







			def 			__lowerCAmelCase				(			self			: Any  ):





								'''simple docstring'''



								pass







			def 			__lowerCAmelCase				(			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			:   List[str]      =				model_class(lowercase  )
													self.assertIsInstance(model.get_input_embeddings()			,  (nn.Module)  )
													UpperCAmelCase			:   Any      =				model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowercase			,  nn.Linear  )  )







			def 			__lowerCAmelCase				(			self			: Tuple  ):





								'''simple docstring'''



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

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

													UpperCAmelCase			:   Any      =				["pixel_values"]
													self.assertListEqual(arg_names[:1]			,  lowercase  )







			def 			__lowerCAmelCase				(			self			: str  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowercase  )







			def 			__lowerCAmelCase				(			self			: List[Any]  ):





								'''simple docstring'''



								UpperCAmelCase      ,							UpperCAmelCase			:   List[Any]      =				self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase			:   List[str]      =				True

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

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

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

													UpperCAmelCase			:   int      =				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 			__lowerCAmelCase				(			self			: Optional[int]  ):





								'''simple docstring'''



								def check_hidden_states_output(lowercase			: Union[str, Any]			,  lowercase			: Any			,  lowercase			: Tuple  ):
													UpperCAmelCase			:   List[str]      =				model_class(lowercase  )
													model.to(lowercase  )
													model.eval()

													with torch.no_grad():
																		UpperCAmelCase			:   List[Any]      =				model(**self._prepare_for_class(lowercase			,  lowercase  )  )

													UpperCAmelCase			:   Union[str, Any]      =				outputs.hidden_states

													UpperCAmelCase			:   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
													UpperCAmelCase			:   List[Any]      =				self.model_tester.expected_seq_len

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

								UpperCAmelCase      ,							UpperCAmelCase			:   Union[str, Any]      =				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													UpperCAmelCase			:   List[Any]      =				True
													check_hidden_states_output(lowercase			,  lowercase			,  lowercase  )

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

													check_hidden_states_output(lowercase			,  lowercase			,  lowercase  )







			def 			__lowerCAmelCase				(			self			: Dict  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[Any]      =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*lowercase  )







			@slow
			def 			__lowerCAmelCase				(			self			: List[str]  ):





								'''simple docstring'''



								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase			:   Any      =				YolosModel.from_pretrained(lowercase  )
													self.assertIsNotNone(lowercase  )



def   lowercase_	(    ):




					'''simple docstring'''






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







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







			@cached_property
			def 			__lowerCAmelCase				(			self			: Optional[Any]  ):





								'''simple docstring'''



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







			@slow
			def 			__lowerCAmelCase				(			self			: List[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   int      =				YolosForObjectDetection.from_pretrained("hustvl/yolos-small"  ).to(lowercase  )

								UpperCAmelCase			:   str      =				self.default_image_processor
								UpperCAmelCase			:   Any      =				prepare_img()
								UpperCAmelCase			:   Tuple      =				image_processor(images=lowercase			,  return_tensors="pt"  ).to(lowercase  )

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

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

								UpperCAmelCase			:   int      =				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=lowercase			,  )
								UpperCAmelCase			:   Dict      =				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=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
								UpperCAmelCase			:   Tuple      =				image_processor.post_process_object_detection(
								    lowercase			,  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(lowercase  )
								UpperCAmelCase			:   int      =				[75, 75, 17, 63, 17]
								UpperCAmelCase			:   List[Any]      =				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(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"""






# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import doctest
import sys
import warnings
from os.path import abspath, dirname, join

import _pytest

from transformers.testing_utils import HfDoctestModule, HfDocTestParser


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
snake_case_   :   Union[str, Any]        =       abspath(join(dirname(__file__), """src"""))
sys.path.insert(1, git_repo_path)

# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)



def   lowercase_	(    _lowercase       :		List[str]	):




					'''simple docstring'''






					config.addinivalue_line(
					    "markers"							,      "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested"	)
					config.addinivalue_line(
					    "markers"							,      "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested"	)
					config.addinivalue_line("markers"							,      "is_pipeline_test: mark test to run only when pipelines are tested"	)
					config.addinivalue_line("markers"							,      "is_staging_test: mark test to run only in the staging environment"	)
					config.addinivalue_line("markers"							,      "accelerate_tests: mark test that require accelerate"	)
					config.addinivalue_line("markers"							,      "tool_tests: mark the tool tests that are run on their specific schedule"	)



def   lowercase_	(    _lowercase       :		List[str]	):




					'''simple docstring'''






					from transformers.testing_utils import pytest_addoption_shared

					pytest_addoption_shared(_lowercase	)



def   lowercase_	(    _lowercase       :		Tuple	):




					'''simple docstring'''






					from transformers.testing_utils import pytest_terminal_summary_main

					UpperCAmelCase			:   Optional[int]      =				terminalreporter.config.getoption("--make-reports"	)
					if make_reports:
										pytest_terminal_summary_main(_lowercase							,      id=_lowercase	)



def   lowercase_	(    _lowercase       :		str							,      _lowercase       :		Dict	):




					'''simple docstring'''






					if exitstatus == 5:
										UpperCAmelCase			:   List[str]      =				0


# Doctest custom flag to ignore output.
snake_case_   :   Union[str, Any]        =       doctest.register_optionflag("""IGNORE_RESULT""")

snake_case_   :   Optional[int]        =       doctest.OutputChecker







class       snake_case__  ( lowerCAmelCase_     ):







			def 			__lowerCAmelCase				(			self			: List[Any]			,  lowercase			: Tuple			,  lowercase			: Optional[Any]			,  lowercase			: int  ):





								'''simple docstring'''



								if IGNORE_RESULT & optionflags:
													return True
								return OutputChecker.check_output(self			,  lowercase			,  lowercase			,  lowercase  )

snake_case_   :   List[str]        =       CustomOutputChecker
snake_case_   :   Optional[Any]        =       HfDoctestModule




snake_case_   :   List[str]        =       HfDocTestParser


