



'''simple docstring'''






import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
						from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor

class 				SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	def __init__(						self			:     str		,			__snake_case			:     List[Any]		,			__snake_case			:     Optional[int]=13		,			__snake_case			:     List[Any]=32		,			__snake_case			:     List[str]=3		,			__snake_case			:     Union[str, Any]=4		,			__snake_case			:     int=[10, 20, 30, 40]		,			__snake_case			:     Any=[2, 2, 3, 2]		,			__snake_case			:     Any=True		,			__snake_case			:     Optional[Any]=True		,			__snake_case			:     int=37		,			__snake_case			:     List[Any]="gelu"		,			__snake_case			:     Dict=10		,			__snake_case			:     Optional[Any]=0.02		,			__snake_case			:     int=["stage2", "stage3", "stage4"]		,			__snake_case			:     Union[str, Any]=[2, 3, 4]		,			__snake_case			:     Optional[int]=None		,			)			->		Any:
								UpperCAmelCase :       Tuple 							=		parent
								UpperCAmelCase :       List[Any] 							=		batch_size
								UpperCAmelCase :       Dict 							=		image_size
								UpperCAmelCase :       Optional[int] 							=		num_channels
								UpperCAmelCase :       Union[str, Any] 							=		num_stages
								UpperCAmelCase :       Optional[int] 							=		hidden_sizes
								UpperCAmelCase :       Tuple 							=		depths
								UpperCAmelCase :       Union[str, Any] 							=		is_training
								UpperCAmelCase :       Optional[Any] 							=		use_labels
								UpperCAmelCase :       Tuple 							=		intermediate_size
								UpperCAmelCase :       Any 							=		hidden_act
								UpperCAmelCase :       Optional[int] 							=		num_labels
								UpperCAmelCase :       int 							=		initializer_range
								UpperCAmelCase :       Dict 							=		out_features
								UpperCAmelCase :       str 							=		out_indices
								UpperCAmelCase :       Any 							=		scope







	def      A	(						self			:     List[Any]		)			->		Dict:
								UpperCAmelCase :       int 							=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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

								return config, pixel_values, labels







	def      A	(						self			:     Dict		)			->		Optional[int]:
								return ConvNextVaConfig(
								    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=__snake_case		,			initializer_range=self.initializer_range		,			out_features=self.out_features		,			out_indices=self.out_indices		,			num_labels=self.num_labels		,			)







	def      A	(						self			:     str		,			__snake_case			:     Tuple		,			__snake_case			:     Any		,			__snake_case			:     str		)			->		Union[str, Any]:
								UpperCAmelCase :       Optional[int] 							=		ConvNextVaModel(config=__snake_case		)
								model.to(__snake_case		)
								model.eval()
								UpperCAmelCase :       Dict 							=		model(__snake_case		)
								# 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			:     Any		,			__snake_case			:     List[str]		,			__snake_case			:     Tuple		,			__snake_case			:     Optional[int]		)			->		List[Any]:
								UpperCAmelCase :       List[Any] 							=		ConvNextVaForImageClassification(__snake_case		)
								model.to(__snake_case		)
								model.eval()
								UpperCAmelCase :       int 							=		model(__snake_case		,			labels=__snake_case		)
								self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.num_labels)		)







	def      A	(						self			:     int		,			__snake_case			:     Any		,			__snake_case			:     List[Any]		,			__snake_case			:     Union[str, Any]		)			->		Union[str, Any]:
								UpperCAmelCase :       Any 							=		ConvNextVaBackbone(config=__snake_case		)
								model.to(__snake_case		)
								model.eval()
								UpperCAmelCase :       List[str] 							=		model(__snake_case		)

								# 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 :       List[Any] 							=		None
								UpperCAmelCase :       Dict 							=		ConvNextVaBackbone(config=__snake_case		)
								model.to(__snake_case		)
								model.eval()
								UpperCAmelCase :       Dict 							=		model(__snake_case		)

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







	def      A	(						self			:     Tuple		)			->		Tuple:
								UpperCAmelCase :       List[str] 							=		self.prepare_config_and_inputs()
								UpperCAmelCase							,		UpperCAmelCase							,		UpperCAmelCase :       int 							=		config_and_inputs
								UpperCAmelCase :       List[str] 							=		{'''pixel_values''': pixel_values, '''labels''': labels}
								return config, inputs_dict

@require_torch
class 				SCREAMING_SNAKE_CASE(							A__							,		A__							,		unittest.TestCase			):







	"""simple docstring"""






	lowerCamelCase__			 =       (
	    (
	        ConvNextVaModel,
	        ConvNextVaForImageClassification,
	        ConvNextVaBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	lowerCamelCase__			 =       (
	    {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
	    if is_torch_available()
	    else {}
	)

	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False







	def      A	(						self			:     Dict		)			->		Union[str, Any]:
								UpperCAmelCase :       List[Any] 							=		ConvNextVaModelTester(self		)
								UpperCAmelCase :       Any 							=		ConfigTester(self		,			config_class=__snake_case		,			has_text_modality=__snake_case		,			hidden_size=37		)







	def      A	(						self			:     Dict		)			->		List[Any]:
								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			:     Any		)			->		int:
								return







	@unittest.skip(reason='''ConvNextV2 does not use inputs_embeds'''		)
	def      A	(						self			:     Union[str, Any]		)			->		Optional[int]:
								pass







	@unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''		)
	def      A	(						self			:     Optional[int]		)			->		Tuple:
								pass







	@unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''		)
	def      A	(						self			:     Tuple		)			->		int:
								pass







	def      A	(						self			:     Union[str, Any]		)			->		Optional[int]:
								if not self.model_tester.is_training:
															return

								for model_class in self.all_model_classes:
															UpperCAmelCase							,		UpperCAmelCase :       Optional[int] 							=		self.model_tester.prepare_config_and_inputs_with_labels()
															UpperCAmelCase :       str 							=		True

															if model_class.__name__ in [
															    *get_values(__snake_case		),
															    *get_values(__snake_case		),
															]:
																						continue

															UpperCAmelCase :       Union[str, Any] 							=		model_class(__snake_case		)
															model.to(__snake_case		)
															model.train()
															UpperCAmelCase :       str 							=		self._prepare_for_class(__snake_case		,			__snake_case		,			return_labels=__snake_case		)
															UpperCAmelCase :       Optional[Any] 							=		model(**__snake_case		).loss
															loss.backward()







	def      A	(						self			:     Optional[int]		)			->		str:
								if not self.model_tester.is_training:
															return

								for model_class in self.all_model_classes:
															UpperCAmelCase							,		UpperCAmelCase :       Dict 							=		self.model_tester.prepare_config_and_inputs_with_labels()
															UpperCAmelCase :       Optional[int] 							=		False
															UpperCAmelCase :       Optional[Any] 							=		True

															if (
															    model_class.__name__
															    in [*get_values(__snake_case		), *get_values(__snake_case		)]
															    or not model_class.supports_gradient_checkpointing
															):
																						continue

															UpperCAmelCase :       str 							=		model_class(__snake_case		)
															model.to(__snake_case		)
															model.gradient_checkpointing_enable()
															model.train()
															UpperCAmelCase :       str 							=		self._prepare_for_class(__snake_case		,			__snake_case		,			return_labels=__snake_case		)
															UpperCAmelCase :       List[Any] 							=		model(**__snake_case		).loss
															loss.backward()







	def      A	(						self			:     int		)			->		Any:
								UpperCAmelCase							,		UpperCAmelCase :       Tuple 							=		self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase :       int 							=		['''pixel_values''']
															self.assertListEqual(arg_names[:1]		,			__snake_case		)







	def      A	(						self			:     Any		)			->		Dict:
								UpperCAmelCase :       Dict 							=		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__snake_case		)







	def      A	(						self			:     Optional[Any]		)			->		Tuple:
								def check_hidden_states_output(__snake_case			:     Any		,			__snake_case			:     Dict		,			__snake_case			:     int		):
															UpperCAmelCase :       Optional[int] 							=		model_class(__snake_case		)
															model.to(__snake_case		)
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase :       str 							=		model(**self._prepare_for_class(__snake_case		,			__snake_case		)		)

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

															UpperCAmelCase :       Optional[int] 							=		self.model_tester.num_stages
															self.assertEqual(len(__snake_case		)		,			expected_num_stages + 1		)

															# ConvNextV2'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 :       Optional[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(__snake_case		,			__snake_case		,			__snake_case		)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															UpperCAmelCase :       List[str] 							=		True

															check_hidden_states_output(__snake_case		,			__snake_case		,			__snake_case		)







	def      A	(						self			:     Any		)			->		Optional[Any]:
								UpperCAmelCase :       Optional[int] 							=		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__snake_case		)







	@slow
	def      A	(						self			:     Dict		)			->		Optional[Any]:
								for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase :       Union[str, Any] 							=		ConvNextVaModel.from_pretrained(__snake_case		)
															self.assertIsNotNone(__snake_case		)


def  snake_case_     (					)      ->   Union[str, Any]:
							UpperCAmelCase :       Tuple 							=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
							return image




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







	"""simple docstring"""






	@cached_property
	def      A	(						self			:     Any		)			->		Union[str, Any]:
								return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''		) if is_vision_available() else None







	@slow
	def      A	(						self			:     Tuple		)			->		Union[str, Any]:
								UpperCAmelCase :       Tuple 							=		ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''		).to(__snake_case		)

								UpperCAmelCase :       List[Any] 							=		self.default_image_processor
								UpperCAmelCase :       Any 							=		prepare_img()
								UpperCAmelCase :       Optional[int] 							=		preprocessor(images=__snake_case		,			return_tensors='''pt'''		).to(__snake_case		)

								# forward pass
								with torch.no_grad():
															UpperCAmelCase :       Any 							=		model(**__snake_case		)

								# verify the logits
								UpperCAmelCase :       List[str] 							=		torch.Size((1, 1000)		)
								self.assertEqual(outputs.logits.shape		,			__snake_case		)

								UpperCAmelCase :       str 							=		torch.tensor([0.99_96, 0.19_66, -0.43_86]		).to(__snake_case		)
								self.assertTrue(torch.allclose(outputs.logits[0, :3]		,			__snake_case		,			atol=1E-4		)		)










'''simple docstring'''






from math import isclose, sqrt


def  snake_case_     (					_lowerCAmelCase  :						float   ,      _lowerCAmelCase  :						float   ,      _lowerCAmelCase  :						float  )      ->   tuple[float, float, float]:
							UpperCAmelCase :       Optional[int] 							=		point_y / 4 / point_x
							UpperCAmelCase :       str 							=		2 * normal_gradient / (1 + normal_gradient * normal_gradient)
							UpperCAmelCase :       Any 							=		(1 - normal_gradient * normal_gradient) / (
							    1 + normal_gradient * normal_gradient
							)
							UpperCAmelCase :       Union[str, Any] 							=		(sa - ca * incoming_gradient) / (ca + sa * incoming_gradient)

							# to find the next point, solve the simultaeneous equations:
							# y^2 + 4x^2 = 100
							# y - b = m * (x - a)
							# ==> A x^2 + B x + C = 0
							UpperCAmelCase :       Union[str, Any] 							=		outgoing_gradient**2 + 4
							UpperCAmelCase :       Dict 							=		2 * outgoing_gradient * (point_y - outgoing_gradient * point_x)
							UpperCAmelCase :       List[Any] 							=		(point_y - outgoing_gradient * point_x) ** 2 - 100

							UpperCAmelCase :       List[str] 							=		(
							    -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term  )
							) / (2 * quadratic_term)
							UpperCAmelCase :       Optional[int] 							=		(
							    -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term  )
							) / (2 * quadratic_term)

							# two solutions, one of which is our input point
							UpperCAmelCase :       Optional[Any] 							=		x_minus if isclose(_lowerCAmelCase   ,      _lowerCAmelCase  ) else x_plus
							UpperCAmelCase :       Union[str, Any] 							=		point_y + outgoing_gradient * (next_x - point_x)

							return next_x, next_y, outgoing_gradient


def  snake_case_     (					_lowerCAmelCase  :						float = 1.4   ,      _lowerCAmelCase  :						float = -9.6  )      ->   int:
							UpperCAmelCase :       int 							=		0
							UpperCAmelCase :       float 							=		first_x_coord
							UpperCAmelCase :       float 							=		first_y_coord
							UpperCAmelCase :       float 							=		(1_0.1 - point_y) / (0.0 - point_x)

							while not (-0.0_1 <= point_x <= 0.0_1 and point_y > 0):
														UpperCAmelCase							,		UpperCAmelCase							,		UpperCAmelCase :       str 							=		next_point(_lowerCAmelCase   ,      _lowerCAmelCase   ,      _lowerCAmelCase  )
														num_reflections += 1

							return num_reflections


if __name__ == "__main__":
						print(F"{solution() = }")





