





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




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

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

								_a								= self.get_config()

								return config, pixel_values, labels




				def   UpperCamelCase__   (  self     :					List[str]					):
								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=__a					,				initializer_range=self.initializer_range					,				num_detection_tokens=self.num_detection_tokens					,				num_labels=self.num_labels					,				)




				def   UpperCamelCase__   (  self     :					int					,				__a     :					Any					,				__a     :					str					,				__a     :					Dict					):
								_a								= YolosModel(config=__a					)
								model.to(__a					)
								model.eval()
								_a								= model(__a					)
								self.parent.assertEqual(
								    result.last_hidden_state.shape					,				(self.batch_size, self.expected_seq_len, self.hidden_size)					)




				def   UpperCamelCase__   (  self     :					List[Any]					,				__a     :					List[str]					,				__a     :					Tuple					,				__a     :					List[str]					):
								_a								= YolosForObjectDetection(__a					)
								model.to(__a					)
								model.eval()

								_a								= model(pixel_values=__a					)
								_a								= model(__a					)

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

								_a								= model(pixel_values=__a					,				labels=__a					)

								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   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= self.prepare_config_and_inputs()
								_a	,					_a	,					_a								= config_and_inputs
								_a								= {"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   UpperCamelCase__   (  self     :					List[str]					,				__a     :					Any					,				__a     :					Tuple					,				__a     :					str=False					):
								_a								= super()._prepare_for_class(__a					,				__a					,				return_labels=__a					)

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

								return inputs_dict




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= YolosModelTester(self					)
								_a								= ConfigTester(self					,				config_class=__a					,				has_text_modality=__a					,				hidden_size=37					)




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




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




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												_a								= model_class(__a					)
												self.assertIsInstance(model.get_input_embeddings()					,				(nn.Module)					)
												_a								= model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(__a					,				nn.Linear					)					)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

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

												_a								= ["pixel_values"]
												self.assertListEqual(arg_names[:1]					,				__a					)




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__a					)




				def   UpperCamelCase__   (  self     :					int					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()
								_a								= True

								# in YOLOS, the seq_len is different
								_a								= self.model_tester.expected_seq_len
								for model_class in self.all_model_classes:
												_a								= True
												_a								= False
												_a								= True
												_a								= model_class(__a					)
												model.to(__a					)
												model.eval()
												with torch.no_grad():
																_a								= model(**self._prepare_for_class(__a					,				__a					)					)
												_a								= outputs.attentions
												self.assertEqual(len(__a					)					,				self.model_tester.num_hidden_layers					)

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

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

												# Check attention is always last and order is fine
												_a								= True
												_a								= True
												_a								= model_class(__a					)
												model.to(__a					)
												model.eval()
												with torch.no_grad():
																_a								= model(**self._prepare_for_class(__a					,				__a					)					)

												_a								= 1
												self.assertEqual(out_len + added_hidden_states					,				len(__a					)					)

												_a								= outputs.attentions

												self.assertEqual(len(__a					)					,				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   UpperCamelCase__   (  self     :					Any					):
								def check_hidden_states_output(__a     :					Tuple					,				__a     :					Any					,				__a     :					List[str]					):
												_a								= model_class(__a					)
												model.to(__a					)
												model.eval()

												with torch.no_grad():
																_a								= model(**self._prepare_for_class(__a					,				__a					)					)

												_a								= outputs.hidden_states

												_a								= getattr(
												    self.model_tester					,				"expected_num_hidden_layers"					,				self.model_tester.num_hidden_layers + 1					)
												self.assertEqual(len(__a					)					,				__a					)

												# YOLOS has a different seq_length
												_a								= self.model_tester.expected_seq_len

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

								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												_a								= True
												check_hidden_states_output(__a					,				__a					,				__a					)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												_a								= True

												check_hidden_states_output(__a					,				__a					,				__a					)




				def   UpperCamelCase__   (  self     :					str					):
								_a								= self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*__a					)




				@slow
				def   UpperCamelCase__   (  self     :					List[Any]					):
								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_a								= YolosModel.from_pretrained(__a					)
												self.assertIsNotNone(__a					)






def  _lowerCamelCase				( )	->	str:
				_a								= 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   UpperCamelCase__   (  self     :					Tuple					):
								return AutoImageProcessor.from_pretrained("hustvl/yolos-small"					) if is_vision_available() else None




				@slow
				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= YolosForObjectDetection.from_pretrained("hustvl/yolos-small"					).to(__a					)

								_a								= self.default_image_processor
								_a								= prepare_img()
								_a								= image_processor(images=__a					,				return_tensors="pt"					).to(__a					)

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

								# verify outputs
								_a								= torch.Size((1, 1_00, 92)					)
								self.assertEqual(outputs.logits.shape					,				__a					)

								_a								= torch.tensor(
								    [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]					,				device=__a					,				)
								_a								= torch.tensor(
								    [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]					,				device=__a					)
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]					,				__a					,				atol=1e-4					)					)
								self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]					,				__a					,				atol=1e-4					)					)

								# verify postprocessing
								_a								= image_processor.post_process_object_detection(
								    __a					,				threshold=0.3					,				target_sizes=[image.size[::-1]]					)[0]
								_a								= torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]					).to(__a					)
								_a								= [75, 75, 17, 63, 17]
								_a								= torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]					).to(__a					)

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







'''simple docstring'''







def  _lowerCamelCase				( lowercase						:      int						)	->	bool:
				_a								= n ** (1 / 3)
				return (val * val * val) == n


if __name__ == "__main__":
					print(perfect_cube(27))
					print(perfect_cube(4))
