



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



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



	def 		UpperCamelCase				(    self				:     Optional[Any])->				Union[str, Any]:
						__lowerCAmelCase						 =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]])

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

						__lowerCAmelCase						 =self.get_config()

						return config, pixel_values, labels



	def 		UpperCamelCase				(    self				:     Optional[int])->				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=snake_case_					,						initializer_range=self.initializer_range					,						num_detection_tokens=self.num_detection_tokens					,						num_labels=self.num_labels					,						)



	def 		UpperCamelCase				(    self				:     int					,						snake_case_				:     List[Any]					,						snake_case_				:     int					,						snake_case_				:     List[str])->				Tuple:
						__lowerCAmelCase						 =YolosModel(config=snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase						 =model(snake_case_)
						self.parent.assertEqual(
						    result.last_hidden_state.shape					,						(self.batch_size, self.expected_seq_len, self.hidden_size))



	def 		UpperCamelCase				(    self				:     Any					,						snake_case_				:     List[Any]					,						snake_case_				:     Any					,						snake_case_				:     Tuple)->				Tuple:
						__lowerCAmelCase						 =YolosForObjectDetection(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase						 =model(pixel_values=snake_case_)
						__lowerCAmelCase						 =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))

						__lowerCAmelCase						 =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 		UpperCamelCase				(    self				:     Optional[int])->				List[Any]:
						__lowerCAmelCase						 =self.prepare_config_and_inputs()
						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =config_and_inputs
						__lowerCAmelCase						 ={"""pixel_values""": pixel_values}
						return config, inputs_dict






@require_torch
class     __a			(  SCREAMING_SNAKE_CASE						,     SCREAMING_SNAKE_CASE						,     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 		UpperCamelCase				(    self				:     List[str]					,						snake_case_				:     List[Any]					,						snake_case_				:     Optional[Any]					,						snake_case_				:     Union[str, Any]=False)->				Optional[Any]:
						__lowerCAmelCase						 =super()._prepare_for_class(snake_case_					,						snake_case_					,						return_labels=snake_case_)

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

						return inputs_dict



	def 		UpperCamelCase				(    self				:     Any)->				Dict:
						__lowerCAmelCase						 =YolosModelTester(self)
						__lowerCAmelCase						 =ConfigTester(self					,						config_class=snake_case_					,						has_text_modality=snake_case_					,						hidden_size=37)



	def 		UpperCamelCase				(    self				:     List[str])->				List[Any]:
						self.config_tester.run_common_tests()



	def 		UpperCamelCase				(    self				:     List[Any])->				Dict:
						# YOLOS does not use inputs_embeds
						pass



	def 		UpperCamelCase				(    self				:     List[Any])->				List[Any]:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

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



	def 		UpperCamelCase				(    self				:     Any)->				Any:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

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

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



	def 		UpperCamelCase				(    self				:     Dict)->				List[Any]:
						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*snake_case_)



	def 		UpperCamelCase				(    self				:     Optional[Any])->				Any:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()
						__lowerCAmelCase						 =True

						# in YOLOS, the seq_len is different
						__lowerCAmelCase						 =self.model_tester.expected_seq_len
						for model_class in self.all_model_classes:
											__lowerCAmelCase						 =True
											__lowerCAmelCase						 =False
											__lowerCAmelCase						 =True
											__lowerCAmelCase						 =model_class(snake_case_)
											model.to(snake_case_)
											model.eval()
											with torch.no_grad():
																__lowerCAmelCase						 =model(**self._prepare_for_class(snake_case_					,						snake_case_))
											__lowerCAmelCase						 =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"]
											__lowerCAmelCase						 =True
											__lowerCAmelCase						 =model_class(snake_case_)
											model.to(snake_case_)
											model.eval()
											with torch.no_grad():
																__lowerCAmelCase						 =model(**self._prepare_for_class(snake_case_					,						snake_case_))
											__lowerCAmelCase						 =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]					,						)
											__lowerCAmelCase						 =len(snake_case_)

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

											__lowerCAmelCase						 =1
											self.assertEqual(out_len + added_hidden_states					,						len(snake_case_))

											__lowerCAmelCase						 =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 		UpperCamelCase				(    self				:     int)->				Any:
						def check_hidden_states_output(snake_case_				:     Optional[int]					,						snake_case_				:     str					,						snake_case_				:     List[str]):
											__lowerCAmelCase						 =model_class(snake_case_)
											model.to(snake_case_)
											model.eval()

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

											__lowerCAmelCase						 =outputs.hidden_states

											__lowerCAmelCase						 =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
											__lowerCAmelCase						 =self.model_tester.expected_seq_len

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

						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__lowerCAmelCase						 =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"]
											__lowerCAmelCase						 =True

											check_hidden_states_output(snake_case_					,						snake_case_					,						snake_case_)



	def 		UpperCamelCase				(    self				:     List[Any])->				Any:
						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_object_detection(*snake_case_)



	@slow
	def 		UpperCamelCase				(    self				:     List[str])->				List[Any]:
						for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase						 =YolosModel.from_pretrained(snake_case_)
											self.assertIsNotNone(snake_case_)






def        __lowerCAmelCase		(	)	->    Optional[Any]:
					__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
					return image






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



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



	@slow
	def 		UpperCamelCase				(    self				:     str)->				str:
						__lowerCAmelCase						 =YolosForObjectDetection.from_pretrained("""hustvl/yolos-small""").to(snake_case_)

						__lowerCAmelCase						 =self.default_image_processor
						__lowerCAmelCase						 =prepare_img()
						__lowerCAmelCase						 =image_processor(images=snake_case_					,						return_tensors="""pt""").to(snake_case_)

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

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

						__lowerCAmelCase						 =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=snake_case_					,						)
						__lowerCAmelCase						 =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=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
						__lowerCAmelCase						 =image_processor.post_process_object_detection(
						    snake_case_					,						threshold=0.3					,						target_sizes=[image.size[::-1]])[0]
						__lowerCAmelCase						 =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(snake_case_)
						__lowerCAmelCase						 =[75, 75, 17, 63, 17]
						__lowerCAmelCase						 =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(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_))









from manim import *






class     __a			(  SCREAMING_SNAKE_CASE					):



	def 		UpperCamelCase				(    self				:     Tuple)->				Dict:
						__lowerCAmelCase						 =Rectangle(height=0.5					,						width=0.5)
						__lowerCAmelCase						 =Rectangle(height=0.4_6					,						width=0.4_6).set_stroke(width=0)

						__lowerCAmelCase						 =[mem.copy() for i in range(6)]
						__lowerCAmelCase						 =[mem.copy() for i in range(6)]
						__lowerCAmelCase						 =VGroup(*snake_case_).arrange(snake_case_					,						buff=0)
						__lowerCAmelCase						 =VGroup(*snake_case_).arrange(snake_case_					,						buff=0)
						__lowerCAmelCase						 =VGroup(snake_case_					,						snake_case_).arrange(snake_case_					,						buff=0)
						__lowerCAmelCase						 =Text("""CPU"""					,						font_size=24)
						__lowerCAmelCase						 =Group(snake_case_					,						snake_case_).arrange(snake_case_					,						buff=0.5					,						aligned_edge=snake_case_)
						cpu.move_to([-2.5, -0.5, 0])
						self.add(snake_case_)

						__lowerCAmelCase						 =[mem.copy() for i in range(1)]
						__lowerCAmelCase						 =VGroup(*snake_case_).arrange(snake_case_					,						buff=0)
						__lowerCAmelCase						 =Text("""GPU"""					,						font_size=24)
						__lowerCAmelCase						 =Group(snake_case_					,						snake_case_).arrange(snake_case_					,						buff=0.5					,						aligned_edge=snake_case_)
						gpu.align_to(snake_case_					,						snake_case_)
						gpu.set_x(gpu.get_x() - 1)

						self.add(snake_case_)

						__lowerCAmelCase						 =[mem.copy() for i in range(6)]
						__lowerCAmelCase						 =VGroup(*snake_case_).arrange(snake_case_					,						buff=0)

						__lowerCAmelCase						 =Text("""Model"""					,						font_size=24)
						__lowerCAmelCase						 =Group(snake_case_					,						snake_case_).arrange(snake_case_					,						buff=0.5					,						aligned_edge=snake_case_)
						model.move_to([3, -1.0, 0])

						self.play(
						    Create(snake_case_					,						run_time=1)					,						Create(snake_case_					,						run_time=1)					,						Create(snake_case_					,						run_time=1)					,						)

						__lowerCAmelCase						 =MarkupText(
						    F"""First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM."""					,						font_size=24					,						)

						__lowerCAmelCase						 =Square(side_length=2.2)
						key.move_to([-5, 2, 0])

						__lowerCAmelCase						 =MarkupText(
						    F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""					,						font_size=18					,						)

						key_text.move_to([-5, 2.4, 0])

						step_a.move_to([2, 2, 0])
						self.play(Write(snake_case_					,						run_time=2.5)					,						Write(snake_case_)					,						Write(snake_case_))

						self.add(snake_case_)

						__lowerCAmelCase						 =[]
						__lowerCAmelCase						 =[]
						__lowerCAmelCase						 =[]
						for i, rect in enumerate(snake_case_):
											__lowerCAmelCase						 =Rectangle(height=0.4_6					,						width=0.4_6).set_stroke(width=0.0).set_fill(snake_case_					,						opacity=0.7)
											cpu_target.move_to(snake_case_)
											cpu_target.generate_target()
											__lowerCAmelCase						 =0.4_6 / 4
											__lowerCAmelCase						 =0.4_6 / 3

											if i == 0:
																cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT)					,						buff=0.0_2					,						direction=snake_case_)
																cpu_target.target.set_x(cpu_target.target.get_x() + 0.1)
											elif i == 3:
																cpu_target.target.next_to(cpu_targs[0].target					,						direction=snake_case_					,						buff=0.0)
											else:
																cpu_target.target.next_to(cpu_targs[i - 1].target					,						direction=snake_case_					,						buff=0.0)
											cpu_targs.append(snake_case_)

											first_animations.append(rect.animate(run_time=0.5).set_stroke(snake_case_))
											second_animations.append(MoveToTarget(snake_case_					,						run_time=1.5))

						self.play(*snake_case_)
						self.play(*snake_case_)

						self.wait()




