

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    ,       A_    ,       A_=13    ,       A_=[30, 30]    ,       A_=2    ,       A_=3    ,       A_=True    ,       A_=True    ,       A_=32    ,       A_=5    ,       A_=4    ,       A_=37    ,       A_="gelu"    ,       A_=0.1    ,       A_=0.1    ,       A_=10    ,       A_=0.02    ,       A_=3    ,       A_=None    ,       A_=8    ,       A_=10    ,       ):







										'''simple docstring'''


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


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		List[Any]					=     floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)

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

										_UpperCAmelCase							:		Dict					=     self.get_config()

										return config, pixel_values, labels


						def 							_UpperCAmelCase					(							self						):







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


						def 							_UpperCAmelCase					(							self    ,       A_    ,       A_    ,       A_						):







										'''simple docstring'''


										_UpperCAmelCase							:		Optional[Any]					=     YolosModel(config=a__						)
										model.to(a__						)
										model.eval()
										_UpperCAmelCase							:		str					=     model(a__						)
										self.parent.assertEqual(
										    result.last_hidden_state.shape    ,       (self.batch_size, self.expected_seq_len, self.hidden_size)						)


						def 							_UpperCAmelCase					(							self    ,       A_    ,       A_    ,       A_						):







										'''simple docstring'''


										_UpperCAmelCase							:		List[str]					=     YolosForObjectDetection(a__						)
										model.to(a__						)
										model.eval()

										_UpperCAmelCase							:		Union[str, Any]					=     model(pixel_values=a__						)
										_UpperCAmelCase							:		Tuple					=     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)						)

										_UpperCAmelCase							:		Tuple					=     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						):







										'''simple docstring'''


										_UpperCAmelCase							:		Tuple					=     self.prepare_config_and_inputs()
										_UpperCAmelCase							:		List[Any]					=     config_and_inputs
										_UpperCAmelCase							:		Dict					=     {'''pixel_values''': pixel_values}
										return config, inputs_dict







@require_torch
class 					a	(						lowerCamelCase__				,			lowerCamelCase__				,			unittest.TestCase					):
						_lowercase         =      (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
						_lowercase         =      (
						    {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
						)

						_lowercase         =      False
						_lowercase         =      False
						_lowercase         =      False
						_lowercase         =      False


						def 							_UpperCAmelCase					(							self    ,       A_    ,       A_    ,       A_=False						):







										'''simple docstring'''


										_UpperCAmelCase							:		Optional[int]					=     super()._prepare_for_class(a__    ,       a__    ,       return_labels=a__						)

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

										return inputs_dict


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		Optional[Any]					=     YolosModelTester(self						)
										_UpperCAmelCase							:		str					=     ConfigTester(self    ,       config_class=a__    ,       has_text_modality=a__    ,       hidden_size=37						)


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										self.config_tester.run_common_tests()


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										pass


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


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

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


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		str					=     self.model_tester.prepare_config_and_inputs_for_common()

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

														_UpperCAmelCase							:		Optional[Any]					=     ['''pixel_values''']
														self.assertListEqual(arg_names[:1]    ,       a__						)


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		Union[str, Any]					=     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*a__						)


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		Dict					=     self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCAmelCase							:		Optional[int]					=     True

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

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

														_UpperCAmelCase							:		int					=     1
														self.assertEqual(out_len + added_hidden_states    ,       len(a__						)						)

														_UpperCAmelCase							:		List[str]					=     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						):







										'''simple docstring'''


										def check_hidden_states_output(A_    ,       A_    ,       A_						):
														_UpperCAmelCase							:		str					=     model_class(a__						)
														model.to(a__						)
														model.eval()

														with torch.no_grad():
																		_UpperCAmelCase							:		Any					=     model(**self._prepare_for_class(a__    ,       a__						)						)

														_UpperCAmelCase							:		List[str]					=     outputs.hidden_states

														_UpperCAmelCase							:		Optional[int]					=     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
														_UpperCAmelCase							:		Optional[Any]					=     self.model_tester.expected_seq_len

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

										_UpperCAmelCase							:		str					=     self.model_tester.prepare_config_and_inputs_for_common()

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

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														_UpperCAmelCase							:		List[str]					=     True

														check_hidden_states_output(a__    ,       a__    ,       a__						)


						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		Any					=     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_object_detection(*a__						)





						@slow
						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_UpperCAmelCase							:		Optional[Any]					=     YolosModel.from_pretrained(a__						)
														self.assertIsNotNone(a__						)







def 				__SCREAMING_SNAKE_CASE				(					) ->							Tuple:
				_UpperCAmelCase							:		int					=     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
				return image





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


						@cached_property
						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


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





						@slow
						def 							_UpperCAmelCase					(							self						):







										'''simple docstring'''


										_UpperCAmelCase							:		List[str]					=     YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(a__						)

										_UpperCAmelCase							:		int					=     self.default_image_processor
										_UpperCAmelCase							:		Dict					=     prepare_img()
										_UpperCAmelCase							:		str					=     image_processor(images=a__    ,       return_tensors="pt"						).to(a__						)

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

										# verify outputs
										_UpperCAmelCase							:		int					=     torch.Size((1, 100, 92)						)
										self.assertEqual(outputs.logits.shape    ,       a__						)

										_UpperCAmelCase							:		Dict					=     torch.tensor(
										    [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]    ,       device=a__    ,       )
										_UpperCAmelCase							:		str					=     torch.tensor(
										    [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]    ,       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
										_UpperCAmelCase							:		Optional[Any]					=     image_processor.post_process_object_detection(
										    a__    ,       threshold=0.3    ,       target_sizes=[image.size[::-1]]						)[0]
										_UpperCAmelCase							:		Any					=     torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]						).to(a__						)
										_UpperCAmelCase							:		str					=     [75, 75, 17, 63, 17]
										_UpperCAmelCase							:		Union[str, Any]					=     torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]						).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__						)						)









import copy
import random

from transformers import CLIPTokenizer







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      def __init__(		self   ,				*a__   ,				**a__):



             """simple docstring"""





             super().__init__(*a__   ,				**a__)
             _lowerCamelCase				:  Optional[Any]						=		{}


      def 					__snake_case      (		self   ,				a__   ,				*a__   ,				**a__):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		super().add_tokens(a__   ,				*a__   ,				**a__)
             if num_added_tokens == 0:
                    raise ValueError(
                        F"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
                        ''' `placeholder_token` that is not already in the tokenizer.''')


      def 					__snake_case      (		self   ,				a__   ,				*a__   ,				a__=1   ,				**a__):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		[]
             if num_vec_per_token == 1:
                    self.try_adding_tokens(a__   ,				*a__   ,				**a__)
                    output.append(a__)
             else:
                    _lowerCamelCase				:  Dict						=		[]
                    for i in range(a__):
                           _lowerCamelCase				:  Optional[Any]						=		placeholder_token + F"""_{i}"""
                           self.try_adding_tokens(a__   ,				*a__   ,				**a__)
                           output.append(a__)
        # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
             for token in self.token_map:
                    if token in placeholder_token:
                           raise ValueError(
                               F"""The tokenizer already has placeholder token {token} that can get confused with"""
                               F""" {placeholder_token}keep placeholder tokens independent""")
             _lowerCamelCase				:  int						=		output


      def 					__snake_case      (		self   ,				a__   ,				a__=False   ,				a__=1.0):



             """simple docstring"""





             if isinstance(a__   ,				a__):
                    _lowerCamelCase				:  Tuple						=		[]
                    for i in range(len(a__)):
                           output.append(self.replace_placeholder_tokens_in_text(text[i]   ,				vector_shuffle=a__))
                    return output
             for placeholder_token in self.token_map:
                    if placeholder_token in text:
                           _lowerCamelCase				:  Union[str, Any]						=		self.token_map[placeholder_token]
                           _lowerCamelCase				:  Optional[Any]						=		tokens[: 1 + int(len(a__) * prop_tokens_to_load)]
                           if vector_shuffle:
                                  _lowerCamelCase				:  int						=		copy.copy(a__)
                                  random.shuffle(a__)
                           _lowerCamelCase				:  List[str]						=		text.replace(a__   ,				''' '''.join(a__))
             return text


      def __call__(		self   ,				a__   ,				*a__   ,				a__=False   ,				a__=1.0   ,				**a__):



             """simple docstring"""





             return super().__call__(
                 self.replace_placeholder_tokens_in_text(
                     a__   ,				vector_shuffle=a__   ,				prop_tokens_to_load=a__)   ,				*a__   ,				**a__   ,				)



      def 					__snake_case      (		self   ,				a__   ,				*a__   ,				a__=False   ,				a__=1.0   ,				**a__):



             """simple docstring"""





             return super().encode(
                 self.replace_placeholder_tokens_in_text(
                     a__   ,				vector_shuffle=a__   ,				prop_tokens_to_load=a__)   ,				*a__   ,				**a__   ,				)

