






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


							def __init__(			self      :						Dict			,    snake_case      :						Optional[Any]			,    snake_case      :						List[Any]=13			,    snake_case      :						Any=[30, 30]			,    snake_case      :						int=2			,    snake_case      :						List[Any]=3			,    snake_case      :						Dict=True			,    snake_case      :						Union[str, Any]=True			,    snake_case      :						List[Any]=32			,    snake_case      :						str=5			,    snake_case      :						str=4			,    snake_case      :						str=37			,    snake_case      :						str="gelu"			,    snake_case      :						Optional[Any]=0.1			,    snake_case      :						Optional[int]=0.1			,    snake_case      :						Optional[Any]=10			,    snake_case      :						Optional[int]=0.02			,    snake_case      :						List[Any]=3			,    snake_case      :						Optional[Any]=None			,    snake_case      :						str=8			,    snake_case      :						Union[str, Any]=10			,    ):
													'''simple docstring'''





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


							def 						_UpperCamelCase       (			self      :						Tuple							):
													'''simple docstring'''





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

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

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

													return config, pixel_values, labels


							def 						_UpperCamelCase       (			self      :						Tuple							):
													'''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=snake_case			,    initializer_range=self.initializer_range			,    num_detection_tokens=self.num_detection_tokens			,    num_labels=self.num_labels			,    )


							def 						_UpperCamelCase       (			self      :						List[Any]			,    snake_case      :						str			,    snake_case      :						Union[str, Any]			,    snake_case      :						int							):
													'''simple docstring'''





													A__						:  int		  =  YolosModel(config=snake_case							)
													model.to(snake_case							)
													model.eval()
													A__						:  str		  =  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[str]			,    snake_case      :						Union[str, Any]			,    snake_case      :						List[Any]							):
													'''simple docstring'''





													A__						:  str		  =  YolosForObjectDetection(snake_case							)
													model.to(snake_case							)
													model.eval()

													A__						:  Tuple		  =  model(pixel_values=snake_case							)
													A__						:  Dict		  =  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)							)

													A__						:  Tuple		  =  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[Any]							):
													'''simple docstring'''





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






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

							snake_case_     =							False
							snake_case_     =							False
							snake_case_     =							False
							snake_case_     =							False


							def 						_UpperCamelCase       (			self      :						Optional[Any]			,    snake_case      :						Optional[Any]			,    snake_case      :						Dict			,    snake_case      :						int=False							):
													'''simple docstring'''





													A__						:  Union[str, Any]		  =  super()._prepare_for_class(snake_case			,    snake_case			,    return_labels=snake_case							)

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

													return inputs_dict


							def 						_UpperCamelCase       (			self      :						str							):
													'''simple docstring'''





													A__						:  List[str]		  =  YolosModelTester(self							)
													A__						:  Union[str, Any]		  =  ConfigTester(self			,    config_class=snake_case			,    has_text_modality=snake_case			,    hidden_size=37							)


							def 						_UpperCamelCase       (			self      :						Optional[Any]							):
													'''simple docstring'''





													self.config_tester.run_common_tests()


							def 						_UpperCamelCase       (			self      :						List[str]							):
													'''simple docstring'''





													pass


							def 						_UpperCamelCase       (			self      :						Any							):
													'''simple docstring'''





													A__  ,  A__						:  Optional[Any]		  =  self.model_tester.prepare_config_and_inputs_for_common()

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


							def 						_UpperCamelCase       (			self      :						Optional[Any]							):
													'''simple docstring'''





													A__  ,  A__						:  Union[str, Any]		  =  self.model_tester.prepare_config_and_inputs_for_common()

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

																			A__						:  str		  =  ["""pixel_values"""]
																			self.assertListEqual(arg_names[:1]			,    snake_case							)


							def 						_UpperCamelCase       (			self      :						List[str]							):
													'''simple docstring'''





													A__						:  Optional[Any]		  =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*snake_case							)


							def 						_UpperCamelCase       (			self      :						int							):
													'''simple docstring'''





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

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

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

																			A__						:  str		  =  1
																			self.assertEqual(out_len + added_hidden_states			,    len(snake_case							)							)

																			A__						:  int		  =  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      :						Optional[Any]							):
													'''simple docstring'''





													def check_hidden_states_output(snake_case      :						Tuple			,    snake_case      :						Tuple			,    snake_case      :						List[str]							):
																			A__						:  Optional[int]		  =  model_class(snake_case							)
																			model.to(snake_case							)
																			model.eval()

																			with torch.no_grad():
																									A__						:  Union[str, Any]		  =  model(**self._prepare_for_class(snake_case			,    snake_case							)							)

																			A__						:  Optional[int]		  =  outputs.hidden_states

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

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

													A__  ,  A__						:  List[str]		  =  self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			A__						:  Optional[Any]		  =  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"]
																			A__						:  str		  =  True

																			check_hidden_states_output(snake_case			,    snake_case			,    snake_case							)


							def 						_UpperCamelCase       (			self      :						int							):
													'''simple docstring'''





													A__						:  str		  =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_object_detection(*snake_case							)


							@slow
							def 						_UpperCamelCase       (			self      :						Optional[Any]							):
													'''simple docstring'''





													for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			A__						:  List[str]		  =  YolosModel.from_pretrained(snake_case							)
																			self.assertIsNotNone(snake_case							)




def      _lowerCAmelCase		(							)		->List[str]:
						A__						:  int		  =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
						return image






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


							@cached_property
							def 						_UpperCamelCase       (			self      :						List[Any]							):
													'''simple docstring'''





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


							@slow
							def 						_UpperCamelCase       (			self      :						int							):
													'''simple docstring'''





													A__						:  Any		  =  YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(snake_case							)

													A__						:  Dict		  =  self.default_image_processor
													A__						:  int		  =  prepare_img()
													A__						:  Union[str, Any]		  =  image_processor(images=snake_case			,    return_tensors="""pt"""							).to(snake_case							)

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

													# verify outputs
													A__						:  List[Any]		  =  torch.Size((1, 100, 92)							)
													self.assertEqual(outputs.logits.shape			,    snake_case							)

													A__						:  Tuple		  =  torch.tensor(
													    [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]			,    device=snake_case			,    )
													A__						:  Tuple		  =  torch.tensor(
													    [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]			,    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
													A__						:  List[Any]		  =  image_processor.post_process_object_detection(
													    snake_case			,    threshold=0.3			,    target_sizes=[image.size[::-1]]							)[0]
													A__						:  Tuple		  =  torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]							).to(snake_case							)
													A__						:  int		  =  [75, 75, 17, 63, 17]
													A__						:  Any		  =  torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]							).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							)							)














"""simple docstring"""



def      _lowerCAmelCase		(							UpperCAmelCase__       :					int,						UpperCAmelCase__       :					int      )		->str:
						if a < 0 or b < 0:
												raise ValueError("""the value of both inputs must be positive"""      )

						A__						:  str		  =  str(bin(UpperCAmelCase__      )      )[2:]  # remove the leading "0b"
						A__						:  List[Any]		  =  str(bin(UpperCAmelCase__      )      )[2:]  # remove the leading "0b"

						A__						:  List[str]		  =  max(len(UpperCAmelCase__      ),						len(UpperCAmelCase__      )      )

						return "0b" + "".join(
						    str(int(char_a == """1""" and char_b == """1"""      )      )
						    for char_a, char_b in zip(a_binary.zfill(UpperCAmelCase__      ),						b_binary.zfill(UpperCAmelCase__      )      )      )


if __name__ == "__main__":
						import doctest

						doctest.testmod()






