


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







      """simple docstring"""







      UpperCamelCase         =					parent
      UpperCamelCase         =					batch_size
      UpperCamelCase         =					image_size
      UpperCamelCase         =					patch_size
      UpperCamelCase         =					num_channels
      UpperCamelCase         =					is_training
      UpperCamelCase         =					use_labels
      UpperCamelCase         =					hidden_size
      UpperCamelCase         =					num_hidden_layers
      UpperCamelCase         =					num_attention_heads
      UpperCamelCase         =					intermediate_size
      UpperCamelCase         =					hidden_act
      UpperCamelCase         =					hidden_dropout_prob
      UpperCamelCase         =					attention_probs_dropout_prob
      UpperCamelCase         =					type_sequence_label_size
      UpperCamelCase         =					initializer_range
      UpperCamelCase         =					num_labels
      UpperCamelCase         =					scope
      UpperCamelCase         =					n_targets
      UpperCamelCase         =					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         =					(image_size[1] // patch_size) * (image_size[0] // patch_size)
      UpperCamelCase         =					num_patches + 1 + self.num_detection_tokens




   def   lowerCamelCase_					(						self							:		Tuple						):







      """simple docstring"""







      UpperCamelCase         =					floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)

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

      UpperCamelCase         =					self.get_config()

      return config, pixel_values, labels




   def   lowerCamelCase_					(						self							:		Union[str, Any]						):







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




   def   lowerCamelCase_					(						self							:		List[Any]       ,       __magic_name__							:		Optional[int]       ,       __magic_name__							:		Optional[int]       ,       __magic_name__							:		Optional[Any]						):







      """simple docstring"""







      UpperCamelCase         =					YolosModel(config=lowerCAmelCase_						)
      model.to(lowerCAmelCase_						)
      model.eval()
      UpperCamelCase         =					model(lowerCAmelCase_						)
      self.parent.assertEqual(
          result.last_hidden_state.shape       ,       (self.batch_size, self.expected_seq_len, self.hidden_size)						)




   def   lowerCamelCase_					(						self							:		Union[str, Any]       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		str       ,       __magic_name__							:		str						):







      """simple docstring"""







      UpperCamelCase         =					YolosForObjectDetection(lowerCAmelCase_						)
      model.to(lowerCAmelCase_						)
      model.eval()

      UpperCamelCase         =					model(pixel_values=lowerCAmelCase_						)
      UpperCamelCase         =					model(lowerCAmelCase_						)

      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         =					model(pixel_values=lowerCAmelCase_       ,       labels=lowerCAmelCase_						)

      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   lowerCamelCase_					(						self							:		Union[str, Any]						):







      """simple docstring"""







      UpperCamelCase         =					self.prepare_config_and_inputs()
      UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase         =					config_and_inputs
      UpperCamelCase         =					{"""pixel_values""": pixel_values}
      return config, inputs_dict




@require_torch
class    UpperCAmelCase					(       __UpperCAmelCase      , __UpperCAmelCase      , 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   lowerCamelCase_					(						self							:		List[str]       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		Dict       ,       __magic_name__							:		List[str]=False						):







      """simple docstring"""







      UpperCamelCase         =					super()._prepare_for_class(lowerCAmelCase_       ,       lowerCAmelCase_       ,       return_labels=lowerCAmelCase_						)

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

      return inputs_dict




   def   lowerCamelCase_					(						self							:		Optional[Any]						):







      """simple docstring"""







      UpperCamelCase         =					YolosModelTester(self						)
      UpperCamelCase         =					ConfigTester(self       ,       config_class=lowerCAmelCase_       ,       has_text_modality=lowerCAmelCase_       ,       hidden_size=3_7						)




   def   lowerCamelCase_					(						self							:		int						):







      """simple docstring"""







      self.config_tester.run_common_tests()




   def   lowerCamelCase_					(						self							:		str						):







      """simple docstring"""







      pass




   def   lowerCamelCase_					(						self							:		Optional[Any]						):







      """simple docstring"""







      UpperCamelCase  ,  UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_common()

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




   def   lowerCamelCase_					(						self							:		List[Any]						):







      """simple docstring"""







      UpperCamelCase  ,  UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_common()

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

         UpperCamelCase         =					["""pixel_values"""]
         self.assertListEqual(arg_names[:1]       ,       lowerCAmelCase_						)




   def   lowerCamelCase_					(						self							:		int						):







      """simple docstring"""







      UpperCamelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase_						)




   def   lowerCamelCase_					(						self							:		List[str]						):







      """simple docstring"""







      UpperCamelCase  ,  UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_common()
      UpperCamelCase         =					True

      # in YOLOS, the seq_len is different
      UpperCamelCase         =					self.model_tester.expected_seq_len
      for model_class in self.all_model_classes:
         UpperCamelCase         =					True
         UpperCamelCase         =					False
         UpperCamelCase         =					True
         UpperCamelCase         =					model_class(lowerCAmelCase_						)
         model.to(lowerCAmelCase_						)
         model.eval()
         with torch.no_grad():
            UpperCamelCase         =					model(**self._prepare_for_class(lowerCAmelCase_       ,       lowerCAmelCase_						)						)
         UpperCamelCase         =					outputs.attentions
         self.assertEqual(len(lowerCAmelCase_						)       ,       self.model_tester.num_hidden_layers						)

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

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

         # Check attention is always last and order is fine
         UpperCamelCase         =					True
         UpperCamelCase         =					True
         UpperCamelCase         =					model_class(lowerCAmelCase_						)
         model.to(lowerCAmelCase_						)
         model.eval()
         with torch.no_grad():
            UpperCamelCase         =					model(**self._prepare_for_class(lowerCAmelCase_       ,       lowerCAmelCase_						)						)

         UpperCamelCase         =					1
         self.assertEqual(out_len + added_hidden_states       ,       len(lowerCAmelCase_						)						)

         UpperCamelCase         =					outputs.attentions

         self.assertEqual(len(lowerCAmelCase_						)       ,       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   lowerCamelCase_					(						self							:		int						):







      """simple docstring"""







      def check_hidden_states_output(__magic_name__							:		Union[str, Any]       ,       __magic_name__							:		Optional[int]       ,       __magic_name__							:		Optional[Any]						):
         UpperCamelCase         =					model_class(lowerCAmelCase_						)
         model.to(lowerCAmelCase_						)
         model.eval()

         with torch.no_grad():
            UpperCamelCase         =					model(**self._prepare_for_class(lowerCAmelCase_       ,       lowerCAmelCase_						)						)

         UpperCamelCase         =					outputs.hidden_states

         UpperCamelCase         =					getattr(
             self.model_tester       ,       """expected_num_hidden_layers"""       ,       self.model_tester.num_hidden_layers + 1						)
         self.assertEqual(len(lowerCAmelCase_						)       ,       lowerCAmelCase_						)

         # YOLOS has a different seq_length
         UpperCamelCase         =					self.model_tester.expected_seq_len

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

      UpperCamelCase  ,  UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         UpperCamelCase         =					True
         check_hidden_states_output(lowerCAmelCase_       ,       lowerCAmelCase_       ,       lowerCAmelCase_						)

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         UpperCamelCase         =					True

         check_hidden_states_output(lowerCAmelCase_       ,       lowerCAmelCase_       ,       lowerCAmelCase_						)




   def   lowerCamelCase_					(						self							:		Tuple						):







      """simple docstring"""







      UpperCamelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_object_detection(*lowerCAmelCase_						)





   @slow
   def   lowerCamelCase_					(						self							:		Optional[Any]						):







      """simple docstring"""







      for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         UpperCamelCase         =					YolosModel.from_pretrained(lowerCAmelCase_						)
         self.assertIsNotNone(lowerCAmelCase_						)






def 							_lowercase    (		):





   """simple docstring"""




   UpperCamelCase         =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
   return image




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




   @cached_property
   def   lowerCamelCase_					(						self							:		int						):







      """simple docstring"""







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





   @slow
   def   lowerCamelCase_					(						self							:		Union[str, Any]						):







      """simple docstring"""







      UpperCamelCase         =					YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""						).to(lowerCAmelCase_						)

      UpperCamelCase         =					self.default_image_processor
      UpperCamelCase         =					prepare_img()
      UpperCamelCase         =					image_processor(images=lowerCAmelCase_       ,       return_tensors="""pt"""						).to(lowerCAmelCase_						)

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

      # verify outputs
      UpperCamelCase         =					torch.Size((1, 1_0_0, 9_2)						)
      self.assertEqual(outputs.logits.shape       ,       lowerCAmelCase_						)

      UpperCamelCase         =					torch.tensor(
          [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]]       ,       device=lowerCAmelCase_       ,       )
      UpperCamelCase         =					torch.tensor(
          [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]]       ,       device=lowerCAmelCase_						)
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]       ,       lowerCAmelCase_       ,       atol=1e-4						)						)
      self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]       ,       lowerCAmelCase_       ,       atol=1e-4						)						)

      # verify postprocessing
      UpperCamelCase         =					image_processor.post_process_object_detection(
          lowerCAmelCase_       ,       threshold=0.3       ,       target_sizes=[image.size[::-1]]						)[0]
      UpperCamelCase         =					torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]						).to(lowerCAmelCase_						)
      UpperCamelCase         =					[7_5, 7_5, 1_7, 6_3, 1_7]
      UpperCamelCase         =					torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]						).to(lowerCAmelCase_						)

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








import math






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		int	):





			"""simple docstring"""




			UpperCamelCase         =					[True] * n
			UpperCamelCase         =					False
			UpperCamelCase         =					False
			UpperCamelCase         =					True

			for i in range(3       ,  int(n**0.5 + 1	)       ,  2	):
						UpperCamelCase         =					i * 2
						while index < n:
									UpperCamelCase         =					False
									UpperCamelCase         =					index + i

			UpperCamelCase         =					[2]

			for i in range(3       ,  SCREAMING_SNAKE_CASE_       ,  2	):
						if is_prime[i]:
									primes.append(SCREAMING_SNAKE_CASE_	)

			return primes






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		int = 999_966_663_333	):





			"""simple docstring"""




			UpperCamelCase         =					math.floor(math.sqrt(SCREAMING_SNAKE_CASE_	)	) + 100
			UpperCamelCase         =					prime_sieve(SCREAMING_SNAKE_CASE_	)

			UpperCamelCase         =					0
			UpperCamelCase         =					0
			UpperCamelCase         =					primes[prime_index]

			while (last_prime**2) <= limit:
						UpperCamelCase         =					primes[prime_index + 1]

						UpperCamelCase         =					last_prime**2
						UpperCamelCase         =					next_prime**2

						# Get numbers divisible by lps(current)
						UpperCamelCase         =					lower_bound + last_prime
						while upper_bound > current <= limit:
									matches_sum += current
									current += last_prime

						# Reset the upper_bound
						while (upper_bound - next_prime) > limit:
									upper_bound -= next_prime

						# Add the numbers divisible by ups(current)
						UpperCamelCase         =					upper_bound - next_prime
						while current > lower_bound:
									matches_sum += current
									current -= next_prime

						# Remove the numbers divisible by both ups and lps
						UpperCamelCase         =					0
						while upper_bound > current <= limit:
									if current <= lower_bound:
												# Increment the current number
												current += last_prime * next_prime
												continue

									if current > limit:
												break

									# Remove twice since it was added by both ups and lps
									matches_sum -= current * 2

									# Increment the current number
									current += last_prime * next_prime

						# Setup for next pair
						UpperCamelCase         =					next_prime
						prime_index += 1

			return matches_sum


if __name__ == "__main__":
			print(solution())




