


"""simple docstring"""






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







					"""simple docstring"""


					def __init__(       self    : Any ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : Dict=13 ,       UpperCamelCase    : int=32 ,       UpperCamelCase    : Tuple=3 ,       UpperCamelCase    : Dict=4 ,       UpperCamelCase    : int=[10, 20, 30, 40] ,       UpperCamelCase    : Dict=[2, 2, 3, 2] ,       UpperCamelCase    : str=True ,       UpperCamelCase    : Optional[int]=True ,       UpperCamelCase    : List[Any]=37 ,       UpperCamelCase    : str="gelu" ,       UpperCamelCase    : List[str]=10 ,       UpperCamelCase    : List[str]=0.02 ,       UpperCamelCase    : Dict=["stage2", "stage3", "stage4"] ,       UpperCamelCase    : Tuple=[2, 3, 4] ,       UpperCamelCase    : Dict=None ,       ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					parent
												__UpperCAmelCase   :						str      							=					batch_size
												__UpperCAmelCase   :						str      							=					image_size
												__UpperCAmelCase   :						int      							=					num_channels
												__UpperCAmelCase   :						List[Any]      							=					num_stages
												__UpperCAmelCase   :						List[str]      							=					hidden_sizes
												__UpperCAmelCase   :						Any      							=					depths
												__UpperCAmelCase   :						int      							=					is_training
												__UpperCAmelCase   :						Optional[int]      							=					use_labels
												__UpperCAmelCase   :						Tuple      							=					intermediate_size
												__UpperCAmelCase   :						int      							=					hidden_act
												__UpperCAmelCase   :						Tuple      							=					num_labels
												__UpperCAmelCase   :						List[str]      							=					initializer_range
												__UpperCAmelCase   :						Tuple      							=					out_features
												__UpperCAmelCase   :						List[str]      							=					out_indices
												__UpperCAmelCase   :						Any      							=					scope






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






												__UpperCAmelCase   :						List[str]      							=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

												__UpperCAmelCase   :						int      							=					None
												if self.use_labels:
																			__UpperCAmelCase   :						Optional[Any]      							=					ids_tensor([self.batch_size] ,       self.num_labels  )

												__UpperCAmelCase   :						Optional[int]      							=					self.get_config()
												return config, pixel_values, labels






					def lowerCamelCase__							(       self    : str  ):
												'''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=UpperCamelCase ,       initializer_range=self.initializer_range ,       out_features=self.out_features ,       out_indices=self.out_indices ,       num_labels=self.num_labels ,       )






					def lowerCamelCase__							(       self    : Dict ,       UpperCamelCase    : List[Any] ,       UpperCamelCase    : Any ,       UpperCamelCase    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[Any]      							=					ConvNextModel(config=UpperCamelCase  )
												model.to(UpperCamelCase  )
												model.eval()
												__UpperCAmelCase   :						List[str]      							=					model(UpperCamelCase  )
												# 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 lowerCamelCase__							(       self    : List[Any] ,       UpperCamelCase    : Optional[Any] ,       UpperCamelCase    : Any ,       UpperCamelCase    : int  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[Any]      							=					ConvNextForImageClassification(UpperCamelCase  )
												model.to(UpperCamelCase  )
												model.eval()
												__UpperCAmelCase   :						List[Any]      							=					model(UpperCamelCase ,       labels=UpperCamelCase  )
												self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)  )






					def lowerCamelCase__							(       self    : Optional[int] ,       UpperCamelCase    : List[Any] ,       UpperCamelCase    : Union[str, Any] ,       UpperCamelCase    : int  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					ConvNextBackbone(config=UpperCamelCase  )
												model.to(UpperCamelCase  )
												model.eval()
												__UpperCAmelCase   :						Optional[Any]      							=					model(UpperCamelCase  )

												# 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
												__UpperCAmelCase   :						str      							=					None
												__UpperCAmelCase   :						Any      							=					ConvNextBackbone(config=UpperCamelCase  )
												model.to(UpperCamelCase  )
												model.eval()
												__UpperCAmelCase   :						List[str]      							=					model(UpperCamelCase  )

												# 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 lowerCamelCase__							(       self    : List[Any]  ):
												'''simple docstring'''






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






@require_torch
class      lowerCamelCase__   (     A     ,    A     ,    unittest.TestCase				):







					"""simple docstring"""


					__a	       =							(
					    (
					        ConvNextModel,
					        ConvNextForImageClassification,
					        ConvNextBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					__a	       =							(
					    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
					    if is_torch_available()
					    else {}
					)

					__a	       =							True
					__a	       =							False
					__a	       =							False
					__a	       =							False
					__a	       =							False






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






												__UpperCAmelCase   :						Any      							=					ConvNextModelTester(self  )
												__UpperCAmelCase   :						List[Any]      							=					ConfigTester(self ,       config_class=UpperCamelCase ,       has_text_modality=UpperCamelCase ,       hidden_size=37  )






					def lowerCamelCase__							(       self    : 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 lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												return






					@unittest.skip(reason="""ConvNext does not use inputs_embeds"""  )
					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												pass






					@unittest.skip(reason="""ConvNext does not support input and output embeddings"""  )
					def lowerCamelCase__							(       self    : List[Any]  ):
												'''simple docstring'''






												pass






					@unittest.skip(reason="""ConvNext does not use feedforward chunking"""  )
					def lowerCamelCase__							(       self    : Optional[Any]  ):
												'''simple docstring'''






												pass






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






												__UpperCAmelCase							,__UpperCAmelCase   :						str      							=					self.model_tester.prepare_config_and_inputs_for_common()

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

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






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






												__UpperCAmelCase   :						Optional[Any]      							=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*UpperCamelCase  )






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






												__UpperCAmelCase   :						int      							=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*UpperCamelCase  )






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






												def check_hidden_states_output(UpperCamelCase    : Tuple ,       UpperCamelCase    : Union[str, Any] ,       UpperCamelCase    : Optional[Any]  ):
																			__UpperCAmelCase   :						List[Any]      							=					model_class(UpperCamelCase  )
																			model.to(UpperCamelCase  )
																			model.eval()

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

																			__UpperCAmelCase   :						Optional[int]      							=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																			__UpperCAmelCase   :						Any      							=					self.model_tester.num_stages
																			self.assertEqual(len(UpperCamelCase  ) ,       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] ,       )

												__UpperCAmelCase							,__UpperCAmelCase   :						List[Any]      							=					self.model_tester.prepare_config_and_inputs_for_common()

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

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

																			check_hidden_states_output(UpperCamelCase ,       UpperCamelCase ,       UpperCamelCase  )






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






												__UpperCAmelCase   :						str      							=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*UpperCamelCase  )






					@slow
					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__UpperCAmelCase   :						Tuple      							=					ConvNextModel.from_pretrained(UpperCamelCase  )
																			self.assertIsNotNone(UpperCamelCase  )






def      lowerCamelCase       (     )		->       Dict:

							'''simple docstring'''



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





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







					"""simple docstring"""


					@cached_property
					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






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






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






												__UpperCAmelCase   :						Tuple      							=					ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""  ).to(UpperCamelCase  )

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

												# forward pass
												with torch.no_grad():
																			__UpperCAmelCase   :						List[str]      							=					model(**UpperCamelCase  )

												# verify the logits
												__UpperCAmelCase   :						List[Any]      							=					torch.Size((1, 1_000)  )
												self.assertEqual(outputs.logits.shape ,       UpperCamelCase  )

												__UpperCAmelCase   :						Optional[Any]      							=					torch.tensor([-0.0260, -0.4739, 0.1911]  ).to(UpperCamelCase  )

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






@require_torch
class      lowerCamelCase__   (     unittest.TestCase     ,    A				):







					"""simple docstring"""


					__a	       =							(ConvNextBackbone,) if is_torch_available() else ()
					__a	       =							ConvNextConfig

					__a	       =							False






					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Any      							=					ConvNextModelTester(self  )




"""simple docstring"""






def      lowerCamelCase       (     _UpperCamelCase		:      float       ,			_UpperCamelCase		:      float       ,			_UpperCamelCase		:      int							)		->       float:

							'''simple docstring'''



							if principal <= 0:
														raise Exception("""Principal borrowed must be > 0"""							)
							if rate_per_annum < 0:
														raise Exception("""Rate of interest must be >= 0"""							)
							if years_to_repay <= 0 or not isinstance(_UpperCamelCase       ,			_UpperCamelCase							):
														raise Exception("""Years to repay must be an integer > 0"""							)

							# Yearly rate is divided by 12 to get monthly rate
							__UpperCAmelCase   :						List[Any]      							=					rate_per_annum / 1_2

							# Years to repay is multiplied by 12 to get number of payments as payment is monthly
							__UpperCAmelCase   :						Optional[int]      							=					years_to_repay * 1_2

							return (
							    principal
							    * rate_per_month
							    * (1 + rate_per_month) ** number_of_payments
							    / ((1 + rate_per_month) ** number_of_payments - 1)
							)


if __name__ == "__main__":
							import doctest

							doctest.testmod()
