






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


						'''simple docstring'''




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






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

								snake_case_				:							List[Any]						 =       self.get_config()

								return config, pixel_values, labels






						def       _lowerCAmelCase       (	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=_SCREAMING_SNAKE_CASE		,				initializer_range=self.initializer_range		,				num_detection_tokens=self.num_detection_tokens		,				num_labels=self.num_labels		,				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Union[str, Any]:
								snake_case_				:							List[Any]						 =       YolosModel(config=_SCREAMING_SNAKE_CASE				)
								model.to(_SCREAMING_SNAKE_CASE				)
								model.eval()
								snake_case_				:							Dict						 =       model(_SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(
								    result.last_hidden_state.shape		,				(self.batch_size, self.expected_seq_len, self.hidden_size)				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								snake_case_				:							str						 =       YolosForObjectDetection(_SCREAMING_SNAKE_CASE				)
								model.to(_SCREAMING_SNAKE_CASE				)
								model.eval()

								snake_case_				:							List[str]						 =       model(pixel_values=_SCREAMING_SNAKE_CASE				)
								snake_case_				:							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)				)

								snake_case_				:							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       _lowerCAmelCase       (	self				) ->				Any:
								snake_case_				:							Any						 =       self.prepare_config_and_inputs()
								snake_case_ ,       snake_case_ ,       snake_case_				:							Dict						 =       config_and_inputs
								snake_case_				:							int						 =       {"pixel_values": pixel_values}
								return config, inputs_dict




@require_torch
class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					,  SCREAMING_SNAKE_CASE__					,  unittest.TestCase					):


						'''simple docstring'''




						A     :   int						=					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
						A     :   Union[str, Any]						=					(
						    {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
						)

						A     :   int						=					False
						A     :   Any						=					False
						A     :   List[Any]						=					False
						A     :   str						=					False






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=False				) ->				Dict:
								snake_case_				:							Tuple						 =       super()._prepare_for_class(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				return_labels=_SCREAMING_SNAKE_CASE				)

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

								return inputs_dict






						def       _lowerCAmelCase       (	self				) ->				Optional[Any]:
								snake_case_				:							Dict						 =       YolosModelTester(self				)
								snake_case_				:							Optional[Any]						 =       ConfigTester(self		,				config_class=_SCREAMING_SNAKE_CASE		,				has_text_modality=_SCREAMING_SNAKE_CASE		,				hidden_size=37				)






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






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






						def       _lowerCAmelCase       (	self				) ->				List[Any]:
								snake_case_ ,       snake_case_				:							Optional[Any]						 =       self.model_tester.prepare_config_and_inputs_for_common()

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






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								snake_case_ ,       snake_case_				:							int						 =       self.model_tester.prepare_config_and_inputs_for_common()

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

										snake_case_				:							Any						 =       ["pixel_values"]
										self.assertListEqual(arg_names[:1]		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				str:
								snake_case_				:							Dict						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Optional[Any]:
								snake_case_ ,       snake_case_				:							int						 =       self.model_tester.prepare_config_and_inputs_for_common()
								snake_case_				:							Optional[Any]						 =       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_				:							Union[str, Any]						 =       True
										snake_case_				:							int						 =       False
										snake_case_				:							Tuple						 =       True
										snake_case_				:							Any						 =       model_class(_SCREAMING_SNAKE_CASE				)
										model.to(_SCREAMING_SNAKE_CASE				)
										model.eval()
										with torch.no_grad():
												snake_case_				:							int						 =       model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)				)
										snake_case_				:							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"]
										snake_case_				:							Tuple						 =       True
										snake_case_				:							Tuple						 =       model_class(_SCREAMING_SNAKE_CASE				)
										model.to(_SCREAMING_SNAKE_CASE				)
										model.eval()
										with torch.no_grad():
												snake_case_				:							Tuple						 =       model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)				)
										snake_case_				:							List[Any]						 =       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]		,				)
										snake_case_				:							Optional[Any]						 =       len(_SCREAMING_SNAKE_CASE				)

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

										snake_case_				:							int						 =       1
										self.assertEqual(out_len + added_hidden_states		,				len(_SCREAMING_SNAKE_CASE				)				)

										snake_case_				:							str						 =       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       _lowerCAmelCase       (	self				) ->				Tuple:
								def check_hidden_states_output(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				):
										snake_case_				:							Tuple						 =       model_class(_SCREAMING_SNAKE_CASE				)
										model.to(_SCREAMING_SNAKE_CASE				)
										model.eval()

										with torch.no_grad():
												snake_case_				:							int						 =       model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)				)

										snake_case_				:							Union[str, 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(_SCREAMING_SNAKE_CASE				)		,				_SCREAMING_SNAKE_CASE				)

										# YOLOS has a different seq_length
										snake_case_				:							List[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_				:							Tuple						 =       self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										snake_case_				:							List[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"]
										snake_case_				:							Tuple						 =       True

										check_hidden_states_output(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								snake_case_				:							List[Any]						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*_SCREAMING_SNAKE_CASE				)






						@slow
						def       _lowerCAmelCase       (	self				) ->				Any:
								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										snake_case_				:							Dict						 =       YolosModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
										self.assertIsNotNone(_SCREAMING_SNAKE_CASE				)




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




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


						'''simple docstring'''




						@cached_property
						def       _lowerCAmelCase       (	self				) ->				Tuple:
								return AutoImageProcessor.from_pretrained("hustvl/yolos-small"				) if is_vision_available() else None






						@slow
						def       _lowerCAmelCase       (	self				) ->				List[str]:
								snake_case_				:							str						 =       YolosForObjectDetection.from_pretrained("hustvl/yolos-small"				).to(_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[int]						 =       self.default_image_processor
								snake_case_				:							str						 =       prepare_img()
								snake_case_				:							List[Any]						 =       image_processor(images=_SCREAMING_SNAKE_CASE		,				return_tensors="pt"				).to(_SCREAMING_SNAKE_CASE				)

								# forward pass
								with torch.no_grad():
										snake_case_				:							int						 =       model(inputs.pixel_values				)

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

								snake_case_				:							List[Any]						 =       torch.tensor(
								    [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]		,				device=_SCREAMING_SNAKE_CASE		,				)
								snake_case_				:							int						 =       torch.tensor(
								    [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]		,				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
								snake_case_				:							List[Any]						 =       image_processor.post_process_object_detection(
								    _SCREAMING_SNAKE_CASE		,				threshold=0.3		,				target_sizes=[image.size[::-1]]				)[0]
								snake_case_				:							List[Any]						 =       torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]				).to(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Union[str, Any]						 =       [75, 75, 17, 63, 17]
								snake_case_				:							str						 =       torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]				).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				)				)








import math

def      lowerCAmelCase__	(    _a       :			int    ):

		if 1 < number < 4:
				# 2 and 3 are primes
				return True
		elif number < 2 or number % 2 == 0 or number % 3 == 0:
				# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
				return False

		# All primes number are in format of 6k +/- 1
		for i in range(5  ,      int(math.sqrt(_a    ) + 1    )  ,      6    ):
				if number % i == 0 or number % (i + 2) == 0:
						return False
		return True

def      lowerCAmelCase__	(    _a       :			float = 0.1    ):
		snake_case_				:							int						 =       3
		snake_case_				:							Optional[Any]						 =       3

		while primes / (2 * j - 1) >= ratio:
				for i in range(j * j + j + 1  ,      (j + 2) * (j + 2)  ,      j + 1    ):
						primes += is_prime(_a    )
				j += 2
		return j


if __name__ == "__main__":
							import doctest

							doctest.testmod()
