

import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor







class   __lowercase      :
 def __init__(							self      ,							A_      ,							A_=13      ,							A_=32      ,							A_=3      ,							A_=4      ,							A_=[10, 20, 30, 40]      ,							A_=[2, 2, 3, 2]      ,							A_=True      ,							A_=True      ,							A_=37      ,							A_="gelu"      ,							A_=10      ,							A_=0.02      ,							A_=["stage2", "stage3", "stage4"]      ,							A_=[2, 3, 4]      ,							A_=None      ,							)					->Tuple:



       '''simple docstring'''





       __lowerCAmelCase					:						List[Any]					=					parent
       __lowerCAmelCase					:						Union[str, Any]					=					batch_size
       __lowerCAmelCase					:						Optional[int]					=					image_size
       __lowerCAmelCase					:						Optional[Any]					=					num_channels
       __lowerCAmelCase					:						Dict					=					num_stages
       __lowerCAmelCase					:						Dict					=					hidden_sizes
       __lowerCAmelCase					:						List[Any]					=					depths
       __lowerCAmelCase					:						Optional[Any]					=					is_training
       __lowerCAmelCase					:						Dict					=					use_labels
       __lowerCAmelCase					:						Dict					=					intermediate_size
       __lowerCAmelCase					:						List[Any]					=					hidden_act
       __lowerCAmelCase					:						List[Any]					=					num_labels
       __lowerCAmelCase					:						Optional[Any]					=					initializer_range
       __lowerCAmelCase					:						str					=					out_features
       __lowerCAmelCase					:						Optional[int]					=					out_indices
       __lowerCAmelCase					:						List[str]					=					scope
 def 	UpperCamelCase__  (							self					)					->Optional[int]:



       '''simple docstring'''





       __lowerCAmelCase					:						Tuple					=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

       __lowerCAmelCase					:						Tuple					=					None
       if self.use_labels:
             __lowerCAmelCase					:						List[Any]					=					ids_tensor([self.batch_size]      ,							self.num_labels					)

       __lowerCAmelCase					:						Dict					=					self.get_config()
       return config, pixel_values, labels
 def 	UpperCamelCase__  (							self					)					->Tuple:



       '''simple docstring'''





       return ConvNextConfig(
           num_channels=self.num_channels      ,							hidden_sizes=self.hidden_sizes      ,							depths=self.depths      ,							num_stages=self.num_stages      ,							hidden_act=self.hidden_act      ,							is_decoder=lowercase_      ,							initializer_range=self.initializer_range      ,							out_features=self.out_features      ,							out_indices=self.out_indices      ,							num_labels=self.num_labels      ,							)
 def 	UpperCamelCase__  (							self      ,							A_      ,							A_      ,							A_					)					->int:



       '''simple docstring'''





       __lowerCAmelCase					:						List[str]					=					ConvNextModel(config=lowercase_					)
       model.to(lowercase_					)
       model.eval()
       __lowerCAmelCase					:						Any					=					model(lowercase_					)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape      ,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)      ,							)
 def 	UpperCamelCase__  (							self      ,							A_      ,							A_      ,							A_					)					->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase					:						Dict					=					ConvNextForImageClassification(lowercase_					)
       model.to(lowercase_					)
       model.eval()
       __lowerCAmelCase					:						Optional[Any]					=					model(lowercase_      ,							labels=lowercase_					)
       self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)					)
 def 	UpperCamelCase__  (							self      ,							A_      ,							A_      ,							A_					)					->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase					:						Union[str, Any]					=					ConvNextBackbone(config=lowercase_					)
       model.to(lowercase_					)
       model.eval()
       __lowerCAmelCase					:						Union[str, Any]					=					model(lowercase_					)

       # verify hidden states
       self.parent.assertEqual(len(result.feature_maps					)      ,							len(config.out_features					)					)
       self.parent.assertListEqual(list(result.feature_maps[0].shape					)      ,							[self.batch_size, self.hidden_sizes[1], 4, 4]					)

       # verify channels
       self.parent.assertEqual(len(model.channels					)      ,							len(config.out_features					)					)
       self.parent.assertListEqual(model.channels      ,							config.hidden_sizes[1:]					)

       # verify backbone works with out_features=None
       __lowerCAmelCase					:						int					=					None
       __lowerCAmelCase					:						Dict					=					ConvNextBackbone(config=lowercase_					)
       model.to(lowercase_					)
       model.eval()
       __lowerCAmelCase					:						Any					=					model(lowercase_					)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps					)      ,							1					)
       self.parent.assertListEqual(list(result.feature_maps[0].shape					)      ,							[self.batch_size, self.hidden_sizes[-1], 1, 1]					)

       # verify channels
       self.parent.assertEqual(len(model.channels					)      ,							1					)
       self.parent.assertListEqual(model.channels      ,							[config.hidden_sizes[-1]]					)





 def 	UpperCamelCase__  (							self					)					->int:



       '''simple docstring'''





       __lowerCAmelCase					:						List[str]					=					self.prepare_config_and_inputs()
       __lowerCAmelCase					:						Tuple					=					config_and_inputs
       __lowerCAmelCase					:						List[str]					=					{"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_torch
class   __lowercase      (_UpperCAmelCase		,   _UpperCAmelCase		,   unittest.TestCase ):
 _UpperCamelCase			  =  (
     (
         ConvNextModel,
         ConvNextForImageClassification,
         ConvNextBackbone,
     )
     if is_torch_available()
     else ()
 )
 _UpperCamelCase			  =  (
     {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
     if is_torch_available()
     else {}
 )

 _UpperCamelCase			  =  True
 _UpperCamelCase			  =  False
 _UpperCamelCase			  =  False
 _UpperCamelCase			  =  False
 _UpperCamelCase			  =  False
 def 	UpperCamelCase__  (							self					)					->Tuple:



       '''simple docstring'''





       __lowerCAmelCase					:						Optional[Any]					=					ConvNextModelTester(self					)
       __lowerCAmelCase					:						int					=					ConfigTester(self      ,							config_class=lowercase_      ,							has_text_modality=lowercase_      ,							hidden_size=37					)
 def 	UpperCamelCase__  (							self					)					->List[Any]:



       '''simple docstring'''





       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()
 def 	UpperCamelCase__  (							self					)					->int:



       '''simple docstring'''





       return
 @unittest.skip(reason='''ConvNext does not use inputs_embeds'''					)
 def 	UpperCamelCase__  (							self					)					->Any:



       '''simple docstring'''





       pass
 @unittest.skip(reason='''ConvNext does not support input and output embeddings'''					)
 def 	UpperCamelCase__  (							self					)					->List[str]:



       '''simple docstring'''





       pass
 @unittest.skip(reason='''ConvNext does not use feedforward chunking'''					)
 def 	UpperCamelCase__  (							self					)					->Union[str, Any]:



       '''simple docstring'''





       pass
 def 	UpperCamelCase__  (							self					)					->Dict:



       '''simple docstring'''





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

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

             __lowerCAmelCase					:						Tuple					=					["""pixel_values"""]
             self.assertListEqual(arg_names[:1]      ,							lowercase_					)
 def 	UpperCamelCase__  (							self					)					->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase					:						Union[str, Any]					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowercase_					)
 def 	UpperCamelCase__  (							self					)					->List[str]:



       '''simple docstring'''





       __lowerCAmelCase					:						Dict					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*lowercase_					)
 def 	UpperCamelCase__  (							self					)					->Optional[Any]:



       '''simple docstring'''





       def check_hidden_states_output(A_      ,							A_      ,							A_					):
             __lowerCAmelCase					:						Any					=					model_class(lowercase_					)
             model.to(lowercase_					)
             model.eval()

             with torch.no_grad():
                   __lowerCAmelCase					:						Dict					=					model(**self._prepare_for_class(lowercase_      ,							lowercase_					)					)

             __lowerCAmelCase					:						Union[str, Any]					=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             __lowerCAmelCase					:						Union[str, Any]					=					self.model_tester.num_stages
             self.assertEqual(len(lowercase_					)      ,							expected_num_stages + 1					)

             # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]					)      ,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]      ,							)

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

       for model_class in self.all_model_classes:
             __lowerCAmelCase					:						Optional[Any]					=					True
             check_hidden_states_output(lowercase_      ,							lowercase_      ,							lowercase_					)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             __lowerCAmelCase					:						int					=					True

             check_hidden_states_output(lowercase_      ,							lowercase_      ,							lowercase_					)
 def 	UpperCamelCase__  (							self					)					->Dict:



       '''simple docstring'''





       __lowerCAmelCase					:						Any					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowercase_					)





 @slow
 def 	UpperCamelCase__  (							self					)					->str:



       '''simple docstring'''





       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __lowerCAmelCase					:						Optional[int]					=					ConvNextModel.from_pretrained(lowercase_					)
             self.assertIsNotNone(lowercase_					)







def 		_lowercase (     ):
      __lowerCAmelCase					:						List[str]					=					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
      return image







@require_torch
@require_vision
class   __lowercase      (unittest.TestCase ):
 @cached_property
 def 	UpperCamelCase__  (							self					)					->Any:



       '''simple docstring'''





       return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''					) if is_vision_available() else None





 @slow
 def 	UpperCamelCase__  (							self					)					->Any:



       '''simple docstring'''





       __lowerCAmelCase					:						Dict					=					ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''					).to(lowercase_					)

       __lowerCAmelCase					:						Dict					=					self.default_image_processor
       __lowerCAmelCase					:						int					=					prepare_img()
       __lowerCAmelCase					:						Union[str, Any]					=					image_processor(images=lowercase_      ,							return_tensors='''pt'''					).to(lowercase_					)

       # forward pass
       with torch.no_grad():
             __lowerCAmelCase					:						str					=					model(**lowercase_					)

       # verify the logits
       __lowerCAmelCase					:						Union[str, Any]					=					torch.Size((1, 1000)					)
       self.assertEqual(outputs.logits.shape      ,							lowercase_					)

       __lowerCAmelCase					:						Optional[Any]					=					torch.tensor([-0.0_260, -0.4_739, 0.1_911]					).to(lowercase_					)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,							lowercase_      ,							atol=1e-4					)					)







@require_torch
class   __lowercase      (unittest.TestCase		,   _UpperCAmelCase ):
 _UpperCamelCase			  =  (ConvNextBackbone,) if is_torch_available() else ()
 _UpperCamelCase			  =  ConvNextConfig

 _UpperCamelCase			  =  False
 def 	UpperCamelCase__  (							self					)					->Tuple:



       '''simple docstring'''





       __lowerCAmelCase					:						List[str]					=					ConvNextModelTester(self					)



'''simple docstring'''




import math
import unittest




def 							lowerCamelCase	(      UpperCAmelCase__       :					int )			->      bool:
							assert isinstance(UpperCAmelCase__      ,      UpperCAmelCase__ ) and (
							    number >= 0
							), "'number' must been an int and positive"

							if 1 < number < 4:
														# 2 and 3 are primes
														return True
							elif number < 2 or number % 2 == 0 or number % 3 == 0:
														# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
														return False

							# All primes number are in format of 6k +/- 1
							for i in range(5      ,      int(math.sqrt(UpperCAmelCase__ ) + 1 )      ,      6 ):
														if number % i == 0 or number % (i + 2) == 0:
																					return False
							return True





class     __magic_name__						(    unittest.TestCase):







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Dict    ):
										self.assertTrue(is_prime(2    )    )
										self.assertTrue(is_prime(3    )    )
										self.assertTrue(is_prime(5    )    )
										self.assertTrue(is_prime(7    )    )
										self.assertTrue(is_prime(11    )    )
										self.assertTrue(is_prime(13    )    )
										self.assertTrue(is_prime(17    )    )
										self.assertTrue(is_prime(19    )    )
										self.assertTrue(is_prime(23    )    )
										self.assertTrue(is_prime(29    )    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										with self.assertRaises(lowercase_    ):
																	is_prime(-19    )
										self.assertFalse(
										    is_prime(0    )				,			"""Zero doesn't have any positive factors, primes must have exactly two."""				,			)
										self.assertFalse(
										    is_prime(1    )				,			"""One only has 1 positive factor, primes must have exactly two."""				,			)
										self.assertFalse(is_prime(2 * 2    )    )
										self.assertFalse(is_prime(2 * 3    )    )
										self.assertFalse(is_prime(3 * 3    )    )
										self.assertFalse(is_prime(3 * 5    )    )
										self.assertFalse(is_prime(3 * 5 * 7    )    )


if __name__ == "__main__":
						unittest.main()





