



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


					'''simple docstring'''





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



					def 	snake_case ( self							:						List[str]  )->      List[Any]:
								lowerCamelCase__	:	Any				=floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]  )

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

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

								return config, pixel_values, labels



					def 	snake_case ( self							:						Dict  )->      int:
								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 	snake_case ( self							:						int,						lowerCamelCase							:						List[str],						lowerCamelCase							:						Optional[int],						lowerCamelCase							:						List[str]  )->      Dict:
								lowerCamelCase__	:	List[Any]				=YolosModel(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowerCamelCase__	:	str				=model(lowerCamelCase  )
								self.parent.assertEqual(
								    result.last_hidden_state.shape,						(self.batch_size, self.expected_seq_len, self.hidden_size)  )



					def 	snake_case ( self							:						Optional[int],						lowerCamelCase							:						List[Any],						lowerCamelCase							:						List[str],						lowerCamelCase							:						Optional[Any]  )->      List[Any]:
								lowerCamelCase__	:	List[Any]				=YolosForObjectDetection(lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()

								lowerCamelCase__	:	str				=model(pixel_values=lowerCamelCase  )
								lowerCamelCase__	:	Optional[int]				=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)  )

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





@require_torch
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_	,     lowerCAmelCase_	,     unittest.TestCase     ):


					'''simple docstring'''





					_a         =							(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
					_a         =							(
					    {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
					)

					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False



					def 	snake_case ( self							:						Tuple,						lowerCamelCase							:						List[Any],						lowerCamelCase							:						Dict,						lowerCamelCase							:						List[str]=False  )->      Optional[Any]:
								lowerCamelCase__	:	Any				=super()._prepare_for_class(lowerCamelCase,						lowerCamelCase,						return_labels=lowerCamelCase  )

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

								return inputs_dict



					def 	snake_case ( self							:						Any  )->      List[Any]:
								lowerCamelCase__	:	str				=YolosModelTester(self  )
								lowerCamelCase__	:	Optional[int]				=ConfigTester(self,						config_class=lowerCamelCase,						has_text_modality=lowerCamelCase,						hidden_size=37  )



					def 	snake_case ( self							:						Optional[int]  )->      Optional[Any]:
								self.config_tester.run_common_tests()



					def 	snake_case ( self							:						List[str]  )->      Optional[Any]:
								# YOLOS does not use inputs_embeds
								pass



					def 	snake_case ( self							:						List[str]  )->      Optional[Any]:
								lowerCamelCase__	:	Tuple				=self.model_tester.prepare_config_and_inputs_for_common()

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



					def 	snake_case ( self							:						str  )->      List[Any]:
								lowerCamelCase__	:	Optional[Any]				=self.model_tester.prepare_config_and_inputs_for_common()

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

											lowerCamelCase__	:	Any				=['''pixel_values''']
											self.assertListEqual(arg_names[:1],						lowerCamelCase  )



					def 	snake_case ( self							:						List[str]  )->      int:
								lowerCamelCase__	:	Optional[Any]				=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase  )



					def 	snake_case ( self							:						Dict  )->      int:
								lowerCamelCase__	:	Dict				=self.model_tester.prepare_config_and_inputs_for_common()
								lowerCamelCase__	:	Optional[int]				=True

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

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

											lowerCamelCase__	:	int				=1
											self.assertEqual(out_len + added_hidden_states,						len(lowerCamelCase  )  )

											lowerCamelCase__	:	Optional[Any]				=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 	snake_case ( self							:						List[Any]  )->      Union[str, Any]:
								def check_hidden_states_output(lowerCamelCase							:						str,						lowerCamelCase							:						Dict,						lowerCamelCase							:						str  ):
											lowerCamelCase__	:	Optional[Any]				=model_class(lowerCamelCase  )
											model.to(lowerCamelCase  )
											model.eval()

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

											lowerCamelCase__	:	int				=outputs.hidden_states

											lowerCamelCase__	:	Tuple				=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
											lowerCamelCase__	:	Optional[Any]				=self.model_tester.expected_seq_len

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

								lowerCamelCase__	:	Tuple				=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__	:	Tuple				=True
											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )

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

											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )



					def 	snake_case ( self							:						Union[str, Any]  )->      str:
								lowerCamelCase__	:	Dict				=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*lowerCamelCase  )




					@slow
					def 	snake_case ( self							:						Optional[Any]  )->      Dict:
								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__	:	Any				=YolosModel.from_pretrained(lowerCamelCase  )
											self.assertIsNotNone(lowerCamelCase  )






def   snake_case__     (	):
			"""simple docstring"""
			lowerCamelCase__	:	Optional[int]				=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
			return image

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


					'''simple docstring'''





					@cached_property
					def 	snake_case ( self							:						Tuple  )->      Union[str, Any]:
								return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''  ) if is_vision_available() else None




					@slow
					def 	snake_case ( self							:						Union[str, Any]  )->      str:
								lowerCamelCase__	:	str				=YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''  ).to(lowerCamelCase  )

								lowerCamelCase__	:	Tuple				=self.default_image_processor
								lowerCamelCase__	:	List[str]				=prepare_img()
								lowerCamelCase__	:	Optional[Any]				=image_processor(images=lowerCamelCase,						return_tensors='''pt'''  ).to(lowerCamelCase  )

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

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

								lowerCamelCase__	:	Optional[int]				=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,						)
								lowerCamelCase__	:	int				=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
								lowerCamelCase__	:	Union[str, Any]				=image_processor.post_process_object_detection(
								    lowerCamelCase,						threshold=0.3,						target_sizes=[image.size[::-1]]  )[0]
								lowerCamelCase__	:	Optional[Any]				=torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]  ).to(lowerCamelCase  )
								lowerCamelCase__	:	Tuple				=[75, 75, 17, 63, 17]
								lowerCamelCase__	:	Tuple				=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"""






_lowercase				:				Optional[Any]   		=		{
    "Pillow": "Pillow<10.0.0",
    "accelerate": "accelerate>=0.20.3",
    "av": "av==9.2.0",
    "beautifulsoup4": "beautifulsoup4",
    "black": "black~=23.1",
    "codecarbon": "codecarbon==1.2.0",
    "cookiecutter": "cookiecutter==1.7.3",
    "dataclasses": "dataclasses",
    "datasets": "datasets!=2.5.0",
    "decord": "decord==0.6.0",
    "deepspeed": "deepspeed>=0.9.3",
    "diffusers": "diffusers",
    "dill": "dill<0.3.5",
    "evaluate": "evaluate>=0.2.0",
    "fairscale": "fairscale>0.3",
    "faiss-cpu": "faiss-cpu",
    "fastapi": "fastapi",
    "filelock": "filelock",
    "flax": "flax>=0.4.1,<=0.7.0",
    "ftfy": "ftfy",
    "fugashi": "fugashi>=1.0",
    "GitPython": "GitPython<3.1.19",
    "hf-doc-builder": "hf-doc-builder>=0.3.0",
    "huggingface-hub": "huggingface-hub>=0.14.1,<1.0",
    "importlib_metadata": "importlib_metadata",
    "ipadic": "ipadic>=1.0.0,<2.0",
    "isort": "isort>=5.5.4",
    "jax": "jax>=0.2.8,!=0.3.2,<=0.4.13",
    "jaxlib": "jaxlib>=0.1.65,<=0.4.13",
    "jieba": "jieba",
    "kenlm": "kenlm",
    "keras-nlp": "keras-nlp>=0.3.1",
    "librosa": "librosa",
    "nltk": "nltk",
    "natten": "natten>=0.14.6",
    "numpy": "numpy>=1.17",
    "onnxconverter-common": "onnxconverter-common",
    "onnxruntime-tools": "onnxruntime-tools>=1.4.2",
    "onnxruntime": "onnxruntime>=1.4.0",
    "opencv-python": "opencv-python",
    "optuna": "optuna",
    "optax": "optax>=0.0.8,<=0.1.4",
    "packaging": "packaging>=20.0",
    "parameterized": "parameterized",
    "phonemizer": "phonemizer",
    "protobuf": "protobuf",
    "psutil": "psutil",
    "pyyaml": "pyyaml>=5.1",
    "pydantic": "pydantic<2",
    "pytest": "pytest>=7.2.0",
    "pytest-timeout": "pytest-timeout",
    "pytest-xdist": "pytest-xdist",
    "python": "python>=3.8.0",
    "ray[tune]": "ray[tune]",
    "regex": "regex!=2019.12.17",
    "requests": "requests",
    "rhoknp": "rhoknp>=1.1.0,<1.3.1",
    "rjieba": "rjieba",
    "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
    "ruff": "ruff>=0.0.241,<=0.0.259",
    "sacrebleu": "sacrebleu>=1.4.12,<2.0.0",
    "sacremoses": "sacremoses",
    "safetensors": "safetensors>=0.3.1",
    "sagemaker": "sagemaker>=2.31.0",
    "scikit-learn": "scikit-learn",
    "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
    "sigopt": "sigopt",
    "starlette": "starlette",
    "sudachipy": "sudachipy>=0.6.6",
    "sudachidict_core": "sudachidict_core>=20220729",
    "tensorflow-cpu": "tensorflow-cpu>=2.6,<2.14",
    "tensorflow": "tensorflow>=2.6,<2.14",
    "tensorflow-text": "tensorflow-text<2.14",
    "tf2onnx": "tf2onnx",
    "timeout-decorator": "timeout-decorator",
    "timm": "timm",
    "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14",
    "torch": "torch>=1.9,!=1.12.0",
    "torchaudio": "torchaudio",
    "torchvision": "torchvision",
    "pyctcdecode": "pyctcdecode>=0.4.0",
    "tqdm": "tqdm>=4.27",
    "unidic": "unidic>=1.0.2",
    "unidic_lite": "unidic_lite>=1.0.7",
    "urllib3": "urllib3<2.0.0",
    "uvicorn": "uvicorn",
}




