






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


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


 def _lowercase	(     self		:						Tuple							)					->       str:
   _a  :       int             =	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

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

   _a  :       Optional[Any]             =	self.get_config()

   return config, pixel_values, labels


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


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


 def _lowercase	(     self		:						Union[str, Any]							,						UpperCAmelCase__		:						Tuple							,						UpperCAmelCase__		:						List[Any]							,						UpperCAmelCase__		:						Any							)					->       Optional[Any]:
   _a  :       int             =	YolosForObjectDetection(UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()

   _a  :       Dict             =	model(pixel_values=UpperCAmelCase__							)
   _a  :       Optional[int]             =	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)							)

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







@require_torch
class        UpperCamelCase			(	snake_case_		,     snake_case_		,     unittest.TestCase      ):
 UpperCamelCase					:       int			=					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
 UpperCamelCase					:       Optional[int]			=					(
     {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
 )

 UpperCamelCase					:       Dict			=					False
 UpperCamelCase					:       Dict			=					False
 UpperCamelCase					:       Any			=					False
 UpperCamelCase					:       int			=					False


 def _lowercase	(     self		:						Optional[Any]							,						UpperCAmelCase__		:						Union[str, Any]							,						UpperCAmelCase__		:						Optional[Any]							,						UpperCAmelCase__		:						Tuple=False							)					->       List[str]:
   _a  :       int             =	super()._prepare_for_class(UpperCAmelCase__							,						UpperCAmelCase__							,						return_labels=UpperCAmelCase__							)

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

   return inputs_dict


 def _lowercase	(     self		:						Dict							)					->       Union[str, Any]:
   _a  :       Optional[Any]             =	YolosModelTester(self							)
   _a  :       Any             =	ConfigTester(self							,						config_class=UpperCAmelCase__							,						has_text_modality=UpperCAmelCase__							,						hidden_size=37							)


 def _lowercase	(     self		:						Any							)					->       str:
   self.config_tester.run_common_tests()


 def _lowercase	(     self		:						List[str]							)					->       Tuple:
   # YOLOS does not use inputs_embeds
   pass


 def _lowercase	(     self		:						Tuple							)					->       List[Any]:
   _a      ,  _a  :       Dict             =	self.model_tester.prepare_config_and_inputs_for_common()

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


 def _lowercase	(     self		:						Dict							)					->       Optional[int]:
   _a      ,  _a  :       Union[str, Any]             =	self.model_tester.prepare_config_and_inputs_for_common()

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

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


 def _lowercase	(     self		:						str							)					->       str:
   _a  :       List[Any]             =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase__							)


 def _lowercase	(     self		:						int							)					->       List[str]:
   _a      ,  _a  :       List[Any]             =	self.model_tester.prepare_config_and_inputs_for_common()
   _a  :       int             =	True

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

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

     _a  :       Optional[Any]             =	1
     self.assertEqual(out_len + added_hidden_states							,						len(UpperCAmelCase__							)							)

     _a  :       Union[str, Any]             =	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		:						str							)					->       Optional[Any]:
   def check_hidden_states_output(UpperCAmelCase__		:						int							,						UpperCAmelCase__		:						Any							,						UpperCAmelCase__		:						int							):
     _a  :       Dict             =	model_class(UpperCAmelCase__							)
     model.to(UpperCAmelCase__							)
     model.eval()

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

     _a  :       Tuple             =	outputs.hidden_states

     _a  :       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
     _a  :       Dict             =	self.model_tester.expected_seq_len

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

   _a      ,  _a  :       str             =	self.model_tester.prepare_config_and_inputs_for_common()

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

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     _a  :       Union[str, Any]             =	True

     check_hidden_states_output(UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__							)


 def _lowercase	(     self		:						Optional[Any]							)					->       Tuple:
   _a  :       List[Any]             =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_object_detection(*UpperCAmelCase__							)







 @slow
 def _lowercase	(     self		:						Optional[Any]							)					->       Any:
   for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _a  :       str             =	YolosModel.from_pretrained(UpperCAmelCase__							)
     self.assertIsNotNone(UpperCAmelCase__							)







def 			lowerCAmelCase__     (     ):



  '''simple docstring'''
  _a  :       Dict             =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
  return image






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


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







 @slow
 def _lowercase	(     self		:						List[Any]							)					->       Optional[int]:
   _a  :       str             =	YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(UpperCAmelCase__							)

   _a  :       Any             =	self.default_image_processor
   _a  :       Dict             =	prepare_img()
   _a  :       Dict             =	image_processor(images=UpperCAmelCase__							,						return_tensors="""pt"""							).to(UpperCAmelCase__							)

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

   # verify outputs
   _a  :       Any             =	torch.Size((1, 100, 92)							)
   self.assertEqual(outputs.logits.shape							,						UpperCAmelCase__							)

   _a  :       Any             =	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=UpperCAmelCase__							,						)
   _a  :       int             =	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=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
   _a  :       List[str]             =	image_processor.post_process_object_detection(
       UpperCAmelCase__							,						threshold=0.3							,						target_sizes=[image.size[::-1]]							)[0]
   _a  :       Tuple             =	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(UpperCAmelCase__							)
   _a  :       int             =	[75, 75, 17, 63, 17]
   _a  :       Any             =	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(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"""




import warnings

from ...utils import logging
from .image_processing_clip import CLIPImageProcessor


_snake_case          =   logging.get_logger(__name__)






class        UpperCamelCase			(	snake_case_      ):


 def __init__(     self		:						Any							,						*UpperCAmelCase__		:						Optional[Any]							,						**UpperCAmelCase__		:						Tuple							)					->       None:
   warnings.warn(
       """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
       """ use CLIPImageProcessor instead."""							,						UpperCAmelCase__							,						)
   super().__init__(*UpperCAmelCase__							,						**UpperCAmelCase__							)

