



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







	"""simple docstring"""






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







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

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

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







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







	def      A	(						self			:     str		,			__snake_case			:     Union[str, Any]		,			__snake_case			:     Any		,			__snake_case			:     str		)			->		Dict:
								UpperCAmelCase :       Union[str, Any] 							=		ConvNextBackbone(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 :       Dict 							=		None
								UpperCAmelCase :       int 							=		ConvNextBackbone(config=__snake_case		)
								model.to(__snake_case		)
								model.eval()
								UpperCAmelCase :       int 							=		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			:     Union[str, Any]		)			->		Dict:
								UpperCAmelCase :       Any 							=		self.prepare_config_and_inputs()
								UpperCAmelCase							,		UpperCAmelCase							,		UpperCAmelCase :       int 							=		config_and_inputs
								UpperCAmelCase :       Dict 							=		{'''pixel_values''': pixel_values}
								return config, inputs_dict

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







	"""simple docstring"""






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

	lowerCamelCase__			 =       True
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False
	lowerCamelCase__			 =       False







	def      A	(						self			:     List[Any]		)			->		Any:
								UpperCAmelCase :       Optional[int] 							=		ConvNextModelTester(self		)
								UpperCAmelCase :       List[Any] 							=		ConfigTester(self		,			config_class=__snake_case		,			has_text_modality=__snake_case		,			hidden_size=37		)







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







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







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







	@unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
	def      A	(						self			:     Optional[int]		)			->		int:
								pass







	def      A	(						self			:     Optional[int]		)			->		Optional[int]:
								UpperCAmelCase							,		UpperCAmelCase :       List[Any] 							=		self.model_tester.prepare_config_and_inputs_for_common()

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

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







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







	def      A	(						self			:     Union[str, Any]		)			->		List[str]:
								UpperCAmelCase :       List[str] 							=		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*__snake_case		)







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

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

															UpperCAmelCase :       Dict 							=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															UpperCAmelCase :       Union[str, Any] 							=		self.model_tester.num_stages
															self.assertEqual(len(__snake_case		)		,			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 :       Any 							=		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase :       List[Any] 							=		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[Any] 							=		True

															check_hidden_states_output(__snake_case		,			__snake_case		,			__snake_case		)







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







	@slow
	def      A	(						self			:     List[Any]		)			->		List[str]:
								for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase :       List[str] 							=		ConvNextModel.from_pretrained(__snake_case		)
															self.assertIsNotNone(__snake_case		)


def  snake_case_     (					)      ->   int:
							UpperCAmelCase :       List[Any] 							=		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			:     Optional[Any]		)			->		Dict:
								return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''		) if is_vision_available() else None







	@slow
	def      A	(						self			:     Union[str, Any]		)			->		Dict:
								UpperCAmelCase :       Dict 							=		ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(__snake_case		)

								UpperCAmelCase :       Tuple 							=		self.default_image_processor
								UpperCAmelCase :       Optional[Any] 							=		prepare_img()
								UpperCAmelCase :       str 							=		image_processor(images=__snake_case		,			return_tensors='''pt'''		).to(__snake_case		)

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

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

								UpperCAmelCase :       Optional[Any] 							=		torch.tensor([-0.02_60, -0.47_39, 0.19_11]		).to(__snake_case		)

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

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







	"""simple docstring"""






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

	lowerCamelCase__			 =       False







	def      A	(						self			:     str		)			->		str:
								UpperCAmelCase :       List[Any] 							=		ConvNextModelTester(self		)










'''simple docstring'''






from __future__ import annotations


def  snake_case_     (					_lowerCAmelCase  :						list[int | float]   ,      _lowerCAmelCase  :						int   ,      _lowerCAmelCase  :						int  )      ->   int | float:
							if len(_lowerCAmelCase  ) == 0:
														raise ValueError('''find_max() arg is an empty sequence'''  )
							if (
							    left >= len(_lowerCAmelCase  )
							    or left < -len(_lowerCAmelCase  )
							    or right >= len(_lowerCAmelCase  )
							    or right < -len(_lowerCAmelCase  )
							):
														raise IndexError('''list index out of range'''  )
							if left == right:
														return nums[left]
							UpperCAmelCase :       List[Any] 							=		(left + right) >> 1  # the middle
							UpperCAmelCase :       Optional[Any] 							=		find_max(_lowerCAmelCase   ,      _lowerCAmelCase   ,      _lowerCAmelCase  )  # find max in range[left, mid]
							UpperCAmelCase :       Dict 							=		find_max(_lowerCAmelCase   ,      mid + 1   ,      _lowerCAmelCase  )  # find max in range[mid + 1, right]

							return left_max if left_max >= right_max else right_max


if __name__ == "__main__":
						import doctest

						doctest.testmod(verbose=True)





