

"""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							:    Optional[int]					,  UpperCamelCase__							:    int					,  UpperCamelCase__							:    Optional[Any]=1_3					,  UpperCamelCase__							:    List[Any]=[3_0, 3_0]					,  UpperCamelCase__							:    Optional[Any]=2					,  UpperCamelCase__							:    Union[str, Any]=3					,  UpperCamelCase__							:    Any=True					,  UpperCamelCase__							:    Dict=True					,  UpperCamelCase__							:    Dict=3_2					,  UpperCamelCase__							:    int=5					,  UpperCamelCase__							:    Dict=4					,  UpperCamelCase__							:    int=3_7					,  UpperCamelCase__							:    str="gelu"					,  UpperCamelCase__							:    Union[str, Any]=0.1					,  UpperCamelCase__							:    str=0.1					,  UpperCamelCase__							:    str=1_0					,  UpperCamelCase__							:    Any=0.02					,  UpperCamelCase__							:    Any=3					,  UpperCamelCase__							:    Any=None					,  UpperCamelCase__							:    int=8					,  UpperCamelCase__							:    int=1_0					,  )->       Optional[int]:



						'''simple docstring'''


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

				def 							lowercase_					(     self							:    int)->       str:



						'''simple docstring'''


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

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

						__lowerCAmelCase:	int   				=      self.get_config()

						return config, pixel_values, labels

				def 							lowercase_					(     self							:    int)->       List[str]:



						'''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=UpperCamelCase__					,  initializer_range=self.initializer_range					,  num_detection_tokens=self.num_detection_tokens					,  num_labels=self.num_labels					,  )

				def 							lowercase_					(     self							:    Any					,  UpperCamelCase__							:    Tuple					,  UpperCamelCase__							:    Union[str, Any]					,  UpperCamelCase__							:    int)->       Any:



						'''simple docstring'''


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

				def 							lowercase_					(     self							:    Dict					,  UpperCamelCase__							:    Tuple					,  UpperCamelCase__							:    Any					,  UpperCamelCase__							:    str)->       Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      YolosForObjectDetection(UpperCamelCase__)
						model.to(UpperCamelCase__)
						model.eval()

						__lowerCAmelCase:	str   				=      model(pixel_values=UpperCamelCase__)
						__lowerCAmelCase:	Tuple   				=      model(UpperCamelCase__)

						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:	Any   				=      model(pixel_values=UpperCamelCase__					,  labels=UpperCamelCase__)

						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 							lowercase_					(     self							:    Dict)->       Optional[Any]:



						'''simple docstring'''


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





@require_torch
class    snake_case     (    __snake_case,							__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_       :				Any       				=  (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE_       :				Optional[int]       				=  (
				    {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
				)

				SCREAMING_SNAKE_CASE_       :				Union[str, Any]       				=  False
				SCREAMING_SNAKE_CASE_       :				Dict       				=  False
				SCREAMING_SNAKE_CASE_       :				Optional[int]       				=  False
				SCREAMING_SNAKE_CASE_       :				Any       				=  False

				def 							lowercase_					(     self							:    Dict					,  UpperCamelCase__							:    List[str]					,  UpperCamelCase__							:    Union[str, Any]					,  UpperCamelCase__							:    Optional[int]=False)->       Any:



						'''simple docstring'''


						__lowerCAmelCase:	Any   				=      super()._prepare_for_class(UpperCamelCase__					,  UpperCamelCase__					,  return_labels=UpperCamelCase__)

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

						return inputs_dict

				def 							lowercase_					(     self							:    Dict)->       Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:	Any   				=      YolosModelTester(self)
						__lowerCAmelCase:	Tuple   				=      ConfigTester(self					,  config_class=UpperCamelCase__					,  has_text_modality=UpperCamelCase__					,  hidden_size=3_7)

				def 							lowercase_					(     self							:    Dict)->       int:



						'''simple docstring'''


						self.config_tester.run_common_tests()

				def 							lowercase_					(     self							:    List[Any])->       Union[str, Any]:



						'''simple docstring'''


						pass

				def 							lowercase_					(     self							:    Union[str, Any])->       int:



						'''simple docstring'''


						__lowerCAmelCase				,			__lowerCAmelCase:	Optional[int]   				=      self.model_tester.prepare_config_and_inputs_for_common()

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

				def 							lowercase_					(     self							:    Any)->       str:



						'''simple docstring'''


						__lowerCAmelCase				,			__lowerCAmelCase:	List[Any]   				=      self.model_tester.prepare_config_and_inputs_for_common()

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

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

				def 							lowercase_					(     self							:    Union[str, Any])->       List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:	Dict   				=      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase__)

				def 							lowercase_					(     self							:    Dict)->       int:



						'''simple docstring'''


						__lowerCAmelCase				,			__lowerCAmelCase:	List[str]   				=      self.model_tester.prepare_config_and_inputs_for_common()
						__lowerCAmelCase:	int   				=      True

						# in YOLOS, the seq_len is different
						__lowerCAmelCase:	Tuple   				=      self.model_tester.expected_seq_len
						for model_class in self.all_model_classes:
								__lowerCAmelCase:	Tuple   				=      True
								__lowerCAmelCase:	Tuple   				=      False
								__lowerCAmelCase:	List[Any]   				=      True
								__lowerCAmelCase:	List[Any]   				=      model_class(UpperCamelCase__)
								model.to(UpperCamelCase__)
								model.eval()
								with torch.no_grad():
										__lowerCAmelCase:	Optional[Any]   				=      model(**self._prepare_for_class(UpperCamelCase__					,  UpperCamelCase__))
								__lowerCAmelCase:	Any   				=      outputs.attentions
								self.assertEqual(len(UpperCamelCase__)					,  self.model_tester.num_hidden_layers)

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

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

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

								__lowerCAmelCase:	List[Any]   				=      1
								self.assertEqual(out_len + added_hidden_states					,  len(UpperCamelCase__))

								__lowerCAmelCase:	Tuple   				=      outputs.attentions

								self.assertEqual(len(UpperCamelCase__)					,  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 							lowercase_					(     self							:    Any)->       str:



						'''simple docstring'''


						def check_hidden_states_output(UpperCamelCase__							:    List[str]					,  UpperCamelCase__							:    Optional[Any]					,  UpperCamelCase__							:    Dict):
								__lowerCAmelCase:	Optional[Any]   				=      model_class(UpperCamelCase__)
								model.to(UpperCamelCase__)
								model.eval()

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

								__lowerCAmelCase:	Optional[int]   				=      outputs.hidden_states

								__lowerCAmelCase:	List[Any]   				=      getattr(
								    self.model_tester					,  "expected_num_hidden_layers"					,  self.model_tester.num_hidden_layers + 1)
								self.assertEqual(len(UpperCamelCase__)					,  UpperCamelCase__)

								# 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				,			__lowerCAmelCase:	Optional[int]   				=      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
								__lowerCAmelCase:	List[str]   				=      True
								check_hidden_states_output(UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__)

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

								check_hidden_states_output(UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__)

				def 							lowercase_					(     self							:    Optional[int])->       List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:	Union[str, Any]   				=      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_object_detection(*UpperCamelCase__)




				@slow
				def 							lowercase_					(     self							:    Optional[int])->       List[Any]:



						'''simple docstring'''


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






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





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

				@cached_property
				def 							lowercase_					(     self							:    List[str])->       List[Any]:



						'''simple docstring'''


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




				@slow
				def 							lowercase_					(     self							:    List[str])->       Any:



						'''simple docstring'''


						__lowerCAmelCase:	Union[str, Any]   				=      YolosForObjectDetection.from_pretrained("hustvl/yolos-small").to(UpperCamelCase__)

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

						# forward pass
						with torch.no_grad():
								__lowerCAmelCase:	Optional[Any]   				=      model(inputs.pixel_values)

						# verify outputs
						__lowerCAmelCase:	Union[str, Any]   				=      torch.Size((1, 1_0_0, 9_2))
						self.assertEqual(outputs.logits.shape					,  UpperCamelCase__)

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

						# verify postprocessing
						__lowerCAmelCase:	Optional[Any]   				=      image_processor.post_process_object_detection(
						    UpperCamelCase__					,  threshold=0.3					,  target_sizes=[image.size[::-1]])[0]
						__lowerCAmelCase:	Any   				=      torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]).to(UpperCamelCase__)
						__lowerCAmelCase:	Dict   				=      [7_5, 7_5, 1_7, 6_3, 1_7]
						__lowerCAmelCase:	List[Any]   				=      torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]).to(UpperCamelCase__)

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





"""simple docstring"""


from math import ceil






def    a__   (   __SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)     ->     str:
		__lowerCAmelCase:	Tuple   				=      list(range(0 ,			__SCREAMING_SNAKE_CASE			)			)

		__lowerCAmelCase:	Optional[Any]   				=      [item for sublist in list(device_map.values()			) for item in sublist]

		# Duplicate check
		__lowerCAmelCase:	List[Any]   				=      []
		for i in device_map_blocks:
				if device_map_blocks.count(__SCREAMING_SNAKE_CASE			) > 1 and i not in duplicate_blocks:
						duplicate_blocks.append(__SCREAMING_SNAKE_CASE			)
    # Missing blocks
		__lowerCAmelCase:	Optional[Any]   				=      [i for i in blocks if i not in device_map_blocks]
		__lowerCAmelCase:	List[Any]   				=      [i for i in device_map_blocks if i not in blocks]

		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
				    " These attention blocks were specified more than once: " + str(__SCREAMING_SNAKE_CASE			)			)
		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "There are attention blocks for this model that are not specified in the device_map. Add these attention "
				    "blocks to a device on the device_map: " + str(__SCREAMING_SNAKE_CASE			)			)
		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "The device_map contains more attention blocks than this model has. Remove these from the device_map:"
				    + str(__SCREAMING_SNAKE_CASE			)			)






def    a__   (   __SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)     ->     str:
		__lowerCAmelCase:	List[Any]   				=      list(range(__SCREAMING_SNAKE_CASE			)			)
		__lowerCAmelCase:	Dict   				=      int(ceil(n_layers / len(__SCREAMING_SNAKE_CASE			)			)			)
		__lowerCAmelCase:	Union[str, Any]   				=      [layers[i : i + n_blocks] for i in range(0 ,			__SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)]

		return dict(zip(__SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)			)


