
'''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__      :

						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       ,							)					->      int:


								'''simple docstring'''

								_UpperCamelCase						    =	parent
								_UpperCamelCase						    =	batch_size
								_UpperCamelCase						    =	image_size
								_UpperCamelCase						    =	num_channels
								_UpperCamelCase						    =	num_stages
								_UpperCamelCase						    =	hidden_sizes
								_UpperCamelCase						    =	depths
								_UpperCamelCase						    =	is_training
								_UpperCamelCase						    =	use_labels
								_UpperCamelCase						    =	intermediate_size
								_UpperCamelCase						    =	hidden_act
								_UpperCamelCase						    =	num_labels
								_UpperCamelCase						    =	initializer_range
								_UpperCamelCase						    =	out_features
								_UpperCamelCase						    =	out_indices
								_UpperCamelCase						    =	scope

						def  A_				(			self				)					->      Any:


								'''simple docstring'''

								_UpperCamelCase						    =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

								_UpperCamelCase						    =	None
								if self.use_labels:
										_UpperCamelCase						    =	ids_tensor([self.batch_size]       ,							self.num_labels				)

								_UpperCamelCase						    =	self.get_config()
								return config, pixel_values, labels

						def  A_				(			self				)					->      Any:


								'''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=_A       ,							initializer_range=self.initializer_range       ,							out_features=self.out_features       ,							out_indices=self.out_indices       ,							num_labels=self.num_labels       ,							)

						def  A_				(			self       ,							a       ,							a       ,							a				)					->      Tuple:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextModel(config=_A				)
								model.to(_A				)
								model.eval()
								_UpperCamelCase						    =	model(_A				)
								# 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  A_				(			self       ,							a       ,							a       ,							a				)					->      List[str]:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextForImageClassification(_A				)
								model.to(_A				)
								model.eval()
								_UpperCamelCase						    =	model(_A       ,							labels=_A				)
								self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_labels)				)

						def  A_				(			self       ,							a       ,							a       ,							a				)					->      Dict:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextBackbone(config=_A				)
								model.to(_A				)
								model.eval()
								_UpperCamelCase						    =	model(_A				)

								# 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						    =	None
								_UpperCamelCase						    =	ConvNextBackbone(config=_A				)
								model.to(_A				)
								model.eval()
								_UpperCamelCase						    =	model(_A				)

								# 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  A_				(			self				)					->      Tuple:


								'''simple docstring'''

								_UpperCamelCase						    =	self.prepare_config_and_inputs()
								_UpperCamelCase						    =	config_and_inputs
								_UpperCamelCase						    =	{'pixel_values': pixel_values}
								return config, inputs_dict







@require_torch
class        lowerCAmelCase__      (   a__		,	a__		,	unittest.TestCase	):
						UpperCamelCase_							: int	=		(
						    (
						        ConvNextModel,
						        ConvNextForImageClassification,
						        ConvNextBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase_							: List[Any]	=		(
						    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase_							: Optional[int]	=		True
						UpperCamelCase_							: Tuple	=		False
						UpperCamelCase_							: str	=		False
						UpperCamelCase_							: Any	=		False
						UpperCamelCase_							: List[str]	=		False

						def  A_				(			self				)					->      List[Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextModelTester(self				)
								_UpperCamelCase						    =	ConfigTester(self       ,							config_class=_A       ,							has_text_modality=_A       ,							hidden_size=37				)

						def  A_				(			self				)					->      Tuple:


								'''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  A_				(			self				)					->      Optional[Any]:


								'''simple docstring'''

								return

						@unittest.skip(reason="""ConvNext does not use inputs_embeds"""				)
						def  A_				(			self				)					->      Optional[Any]:


								'''simple docstring'''

								pass

						@unittest.skip(reason="""ConvNext does not support input and output embeddings"""				)
						def  A_				(			self				)					->      str:


								'''simple docstring'''

								pass

						@unittest.skip(reason="""ConvNext does not use feedforward chunking"""				)
						def  A_				(			self				)					->      int:


								'''simple docstring'''

								pass

						def  A_				(			self				)					->      Tuple:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										_UpperCamelCase						    =	model_class(_A				)
										_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]       ,							_A				)

						def  A_				(			self				)					->      Optional[Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_A				)

						def  A_				(			self				)					->      Union[str, Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*_A				)

						def  A_				(			self				)					->      str:


								'''simple docstring'''

								def check_hidden_states_output(a       ,							a       ,							a				):
										_UpperCamelCase						    =	model_class(_A				)
										model.to(_A				)
										model.eval()

										with torch.no_grad():
												_UpperCamelCase						    =	model(**self._prepare_for_class(_A       ,							_A				)				)

										_UpperCamelCase						    =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										_UpperCamelCase						    =	self.model_tester.num_stages
										self.assertEqual(len(_A				)       ,							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						    =	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										_UpperCamelCase						    =	True
										check_hidden_states_output(_A       ,							_A       ,							_A				)

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

										check_hidden_states_output(_A       ,							_A       ,							_A				)

						def  A_				(			self				)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*_A				)







						@slow
						def  A_				(			self				)					->      List[str]:


								'''simple docstring'''

								for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_UpperCamelCase						    =	ConvNextModel.from_pretrained(_A				)
										self.assertIsNotNone(_A				)




def 							__A()		->				Optional[Any]:

		"""simple docstring"""






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







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

						@cached_property
						def  A_				(			self				)					->      Union[str, Any]:


								'''simple docstring'''

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







						@slow
						def  A_				(			self				)					->      int:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""				).to(_A				)

								_UpperCamelCase						    =	self.default_image_processor
								_UpperCamelCase						    =	prepare_img()
								_UpperCamelCase						    =	image_processor(images=_A       ,							return_tensors="""pt"""				).to(_A				)

								# forward pass
								with torch.no_grad():
										_UpperCamelCase						    =	model(**_A				)

								# verify the logits
								_UpperCamelCase						    =	torch.Size((1, 10_00)				)
								self.assertEqual(outputs.logits.shape       ,							_A				)

								_UpperCamelCase						    =	torch.tensor([-0.0260, -0.4739, 0.1911]				).to(_A				)

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







@require_torch
class        lowerCAmelCase__      (   unittest.TestCase		,	a__	):
						UpperCamelCase_							: Union[str, Any]	=		(ConvNextBackbone,) if is_torch_available() else ()
						UpperCamelCase_							: List[str]	=		ConvNextConfig

						UpperCamelCase_							: Tuple	=		False

						def  A_				(			self				)					->      Dict:


								'''simple docstring'''

								_UpperCamelCase						    =	ConvNextModelTester(self				)





def 							__A(lowerCAmelCase						,  lowerCAmelCase )		->				tuple[float, float]:

		"""simple docstring"""






		if not len(lowerCAmelCase ) == len(lowerCAmelCase ) == 3:
				raise ValueError("""Please enter a valid equation.""" )
		if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
				raise ValueError("""Both a & b of two equations can't be zero.""" )

		# Extract the coefficients
		_UpperCamelCase    ,	_UpperCamelCase    ,	_UpperCamelCase						    =	equationa
		_UpperCamelCase    ,	_UpperCamelCase    ,	_UpperCamelCase						    =	equationa

		# Calculate the determinants of the matrices
		_UpperCamelCase						    =	aa * ba - aa * ba
		_UpperCamelCase						    =	ca * ba - ca * ba
		_UpperCamelCase						    =	aa * ca - aa * ca

		# Check if the system of linear equations has a solution (using Cramer's rule)
		if determinant == 0:
				if determinant_x == determinant_y == 0:
						raise ValueError("""Infinite solutions. (Consistent system)""" )
				else:
						raise ValueError("""No solution. (Inconsistent system)""" )
		else:
				if determinant_x == determinant_y == 0:
						# Trivial solution (Inconsistent system)
						return (0.0, 0.0)
				else:
						_UpperCamelCase						    =	determinant_x / determinant
						_UpperCamelCase						    =	determinant_y / determinant
						# Non-Trivial Solution (Consistent system)
						return (x, y)



