




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






			'''simple docstring'''



			def __init__(						self						,   lowercase						,   lowercase=13						,   lowercase=[30, 30]						,   lowercase=2						,   lowercase=3						,   lowercase=True						,   lowercase=True						,   lowercase=32						,   lowercase=5						,   lowercase=4						,   lowercase=37						,   lowercase="gelu"						,   lowercase=0.1						,   lowercase=0.1						,   lowercase=10						,   lowercase=0.02						,   lowercase=3						,   lowercase=None						,   lowercase=8						,   lowercase=10						,   ):
							_lowerCamelCase  :    str					=					parent
							_lowerCamelCase  :    Union[str, Any]					=					batch_size
							_lowerCamelCase  :    List[Any]					=					image_size
							_lowerCamelCase  :    Any					=					patch_size
							_lowerCamelCase  :    int					=					num_channels
							_lowerCamelCase  :    Optional[Any]					=					is_training
							_lowerCamelCase  :    List[str]					=					use_labels
							_lowerCamelCase  :    int					=					hidden_size
							_lowerCamelCase  :    Optional[Any]					=					num_hidden_layers
							_lowerCamelCase  :    List[str]					=					num_attention_heads
							_lowerCamelCase  :    Any					=					intermediate_size
							_lowerCamelCase  :    Optional[Any]					=					hidden_act
							_lowerCamelCase  :    List[Any]					=					hidden_dropout_prob
							_lowerCamelCase  :    Optional[int]					=					attention_probs_dropout_prob
							_lowerCamelCase  :    Tuple					=					type_sequence_label_size
							_lowerCamelCase  :    str					=					initializer_range
							_lowerCamelCase  :    Dict					=					num_labels
							_lowerCamelCase  :    Union[str, Any]					=					scope
							_lowerCamelCase  :    Union[str, Any]					=					n_targets
							_lowerCamelCase  :    Tuple					=					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  :    Any					=					(image_size[1] // patch_size) * (image_size[0] // patch_size)
							_lowerCamelCase  :    Dict					=					num_patches + 1 + self.num_detection_tokens
			def       A_					(						self						):
							_lowerCamelCase  :    Optional[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  :    str					=					[]
											for i in range(self.batch_size						):
															_lowerCamelCase  :    List[str]					=					{}
															_lowerCamelCase  :    str					=					torch.randint(
															    high=self.num_labels						,   size=(self.n_targets,)						,   device=lowercase						)
															_lowerCamelCase  :    int					=					torch.rand(self.n_targets						,   4						,   device=lowercase						)
															labels.append(lowercase						)

							_lowerCamelCase  :    Optional[int]					=					self.get_config()

							return config, pixel_values, labels
			def       A_					(						self						):
							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=lowercase						,   initializer_range=self.initializer_range						,   num_detection_tokens=self.num_detection_tokens						,   num_labels=self.num_labels						,   )
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    List[Any]					=					YolosModel(config=lowercase						)
							model.to(lowercase						)
							model.eval()
							_lowerCamelCase  :    str					=					model(lowercase						)
							self.parent.assertEqual(
							    result.last_hidden_state.shape						,   (self.batch_size, self.expected_seq_len, self.hidden_size)						)
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    Any					=					YolosForObjectDetection(lowercase						)
							model.to(lowercase						)
							model.eval()

							_lowerCamelCase  :    Optional[Any]					=					model(pixel_values=lowercase						)
							_lowerCamelCase  :    Dict					=					model(lowercase						)

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

							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       A_					(						self						):
							_lowerCamelCase  :    List[str]					=					self.prepare_config_and_inputs()
							_lowerCamelCase,				_lowerCamelCase,				_lowerCamelCase  :    Optional[int]					=					config_and_inputs
							_lowerCamelCase  :    str					=					{'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class lowerCAmelCase__			(  lowercase,			lowercase,			unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__   =    (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
			lowerCamelCase__   =    (
			    {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
			)

			lowerCamelCase__   =    False
			lowerCamelCase__   =    False
			lowerCamelCase__   =    False
			lowerCamelCase__   =    False
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase=False						):
							_lowerCamelCase  :    List[str]					=					super()._prepare_for_class(lowercase						,   lowercase						,   return_labels=lowercase						)

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

							return inputs_dict
			def       A_					(						self						):
							_lowerCamelCase  :    int					=					YolosModelTester(self						)
							_lowerCamelCase  :    Dict					=					ConfigTester(self						,   config_class=lowercase						,   has_text_modality=lowercase						,   hidden_size=37						)
			def       A_					(						self						):
							self.config_tester.run_common_tests()
			def       A_					(						self						):
							# YOLOS does not use inputs_embeds
							pass
			def       A_					(						self						):
							_lowerCamelCase,				_lowerCamelCase  :    Any					=					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											_lowerCamelCase  :    Dict					=					model_class(lowercase						)
											self.assertIsInstance(model.get_input_embeddings()						,   (nn.Module)						)
											_lowerCamelCase  :    List[str]					=					model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowercase						,   nn.Linear						)						)
			def       A_					(						self						):
							_lowerCamelCase,				_lowerCamelCase  :    Dict					=					self.model_tester.prepare_config_and_inputs_for_common()

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

											_lowerCamelCase  :    List[str]					=					['pixel_values']
											self.assertListEqual(arg_names[:1]						,   lowercase						)
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase						)
			def       A_					(						self						):
							_lowerCamelCase,				_lowerCamelCase  :    int					=					self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase  :    Tuple					=					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  :    str					=					True
											_lowerCamelCase  :    str					=					False
											_lowerCamelCase  :    Optional[int]					=					True
											_lowerCamelCase  :    Optional[Any]					=					model_class(lowercase						)
											model.to(lowercase						)
											model.eval()
											with torch.no_grad():
															_lowerCamelCase  :    Optional[int]					=					model(**self._prepare_for_class(lowercase						,   lowercase						)						)
											_lowerCamelCase  :    Any					=					outputs.attentions
											self.assertEqual(len(lowercase						)						,   self.model_tester.num_hidden_layers						)

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

											self.assertListEqual(
											    list(attentions[0].shape[-3:]						)						,   [self.model_tester.num_attention_heads, seq_len, seq_len]						,   )
											_lowerCamelCase  :    Union[str, Any]					=					len(lowercase						)

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

											_lowerCamelCase  :    Dict					=					1
											self.assertEqual(out_len + added_hidden_states						,   len(lowercase						)						)

											_lowerCamelCase  :    Dict					=					outputs.attentions

											self.assertEqual(len(lowercase						)						,   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       A_					(						self						):
							def check_hidden_states_output(lowercase						,   lowercase						,   lowercase						):
											_lowerCamelCase  :    List[Any]					=					model_class(lowercase						)
											model.to(lowercase						)
											model.eval()

											with torch.no_grad():
															_lowerCamelCase  :    int					=					model(**self._prepare_for_class(lowercase						,   lowercase						)						)

											_lowerCamelCase  :    Optional[Any]					=					outputs.hidden_states

											_lowerCamelCase  :    List[str]					=					getattr(
											    self.model_tester						,   'expected_num_hidden_layers'						,   self.model_tester.num_hidden_layers + 1						)
											self.assertEqual(len(lowercase						)						,   lowercase						)

											# YOLOS has a different seq_length
											_lowerCamelCase  :    Dict					=					self.model_tester.expected_seq_len

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

							_lowerCamelCase,				_lowerCamelCase  :    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(lowercase						,   lowercase						,   lowercase						)

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

											check_hidden_states_output(lowercase						,   lowercase						,   lowercase						)
			def       A_					(						self						):
							_lowerCamelCase  :    List[Any]					=					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_object_detection(*lowercase						)






			@slow
			def       A_					(						self						):
							for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_lowerCamelCase  :    Dict					=					YolosModel.from_pretrained(lowercase						)
											self.assertIsNotNone(lowercase						)







def   _snake_case    (       ):
				_lowerCamelCase  :    Optional[int]					=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
				return image






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






			'''simple docstring'''



			@cached_property
			def       A_					(						self						):
							return AutoImageProcessor.from_pretrained('hustvl/yolos-small'						) if is_vision_available() else None






			@slow
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					YolosForObjectDetection.from_pretrained('hustvl/yolos-small'						).to(lowercase						)

							_lowerCamelCase  :    Dict					=					self.default_image_processor
							_lowerCamelCase  :    List[str]					=					prepare_img()
							_lowerCamelCase  :    Union[str, Any]					=					image_processor(images=lowercase						,   return_tensors='pt'						).to(lowercase						)

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

							# verify outputs
							_lowerCamelCase  :    Optional[int]					=					torch.Size((1, 100, 92)						)
							self.assertEqual(outputs.logits.shape						,   lowercase						)

							_lowerCamelCase  :    List[Any]					=					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=lowercase						,   )
							_lowerCamelCase  :    List[Any]					=					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=lowercase						)
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]						,   lowercase						,   atol=1E-4						)						)
							self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]						,   lowercase						,   atol=1E-4						)						)

							# verify postprocessing
							_lowerCamelCase  :    List[str]					=					image_processor.post_process_object_detection(
							    lowercase						,   threshold=0.3						,   target_sizes=[image.size[::-1]]						)[0]
							_lowerCamelCase  :    str					=					torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]						).to(lowercase						)
							_lowerCamelCase  :    str					=					[75, 75, 17, 63, 17]
							_lowerCamelCase  :    Union[str, Any]					=					torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]						).to(lowercase						)

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





"""simple docstring"""






def   _snake_case    (       lowercase__	):
				_lowerCamelCase  :    List[str]					=					abs(lowercase__	)
				_lowerCamelCase  :    Optional[int]					=					0
				while n > 0:
								res += n % 10
								n //= 10
				return res







def   _snake_case    (       lowercase__	):
				_lowerCamelCase  :    List[str]					=					abs(lowercase__	)
				return n if n < 10 else n % 10 + sum_of_digits(n // 10	)







def   _snake_case    (       lowercase__	):
				return sum(int(lowercase__	) for c in str(abs(lowercase__	)	)	)







def   _snake_case    (       ):
				from collections.abc import Callable
				from timeit import timeit

				def benchmark_a_function(lowercase__							,					lowercase__	) -> None:
								_lowerCamelCase  :    int					=					f'''{func.__name__}({value})'''
								_lowerCamelCase  :    Optional[Any]					=					timeit(f'''__main__.{call}'''							,					setup='import __main__'	)
								print(f'''{call:56} = {func(lowercase__	)} -- {timing:.4f} seconds'''	)

				for value in (262144, 1125899906842624, 1267650600228229401496703205376):
								for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
												benchmark_a_function(lowercase__							,					lowercase__	)
								print()


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			benchmark()