

"""simple docstring"""




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
	from PIL import Image

	from transformers import ConvNextImageProcessor





class 			__UpperCamelCase :


		def __init__(self :		str     ,     __SCREAMING_SNAKE_CASE :		str     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]=1_3     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=3_2     ,     __SCREAMING_SNAKE_CASE :		int=3     ,     __SCREAMING_SNAKE_CASE :		int=4     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=[1_0, 2_0, 3_0, 4_0]     ,     __SCREAMING_SNAKE_CASE :		Tuple=[2, 2, 3, 2]     ,     __SCREAMING_SNAKE_CASE :		List[str]=True     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=True     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=3_7     ,     __SCREAMING_SNAKE_CASE :		str="gelu"     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=1_0     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]=0.0_2     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]=3     ,     __SCREAMING_SNAKE_CASE :		int=None     ,     ):
							A			=					parent
							A			=					batch_size
							A			=					image_size
							A			=					num_channels
							A			=					num_stages
							A			=					hidden_sizes
							A			=					depths
							A			=					is_training
							A			=					use_labels
							A			=					intermediate_size
							A			=					hidden_act
							A			=					type_sequence_label_size
							A			=					initializer_range
							A			=					scope


		def 					SCREAMING_SNAKE_CASE__   (self :		List[Any]):
							A			=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

							A			=					None
							if self.use_labels:
												A			=					ids_tensor([self.batch_size]     ,     self.type_sequence_label_size)

							A			=					self.get_config()

							return config, pixel_values, labels


		def 					SCREAMING_SNAKE_CASE__   (self :		List[str]):
							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=__SCREAMING_SNAKE_CASE     ,     initializer_range=self.initializer_range     ,     )


		def 					SCREAMING_SNAKE_CASE__   (self :		Tuple     ,     __SCREAMING_SNAKE_CASE :		str     ,     __SCREAMING_SNAKE_CASE :		List[str]     ,     __SCREAMING_SNAKE_CASE :		str):
							A			=					TFConvNextModel(config=__SCREAMING_SNAKE_CASE)
							A			=					model(__SCREAMING_SNAKE_CASE     ,     training=__SCREAMING_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 // 3_2, self.image_size // 3_2)     ,     )


		def 					SCREAMING_SNAKE_CASE__   (self :		List[str]     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]     ,     __SCREAMING_SNAKE_CASE :		str     ,     __SCREAMING_SNAKE_CASE :		Dict):
							A			=					self.type_sequence_label_size
							A			=					TFConvNextForImageClassification(__SCREAMING_SNAKE_CASE)
							A			=					model(__SCREAMING_SNAKE_CASE     ,     labels=__SCREAMING_SNAKE_CASE     ,     training=__SCREAMING_SNAKE_CASE)
							self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.type_sequence_label_size))


		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[Any]):
							A			=					self.prepare_config_and_inputs()
							A			,    A			,    A			=					config_and_inputs
							A			=					{"pixel_values": pixel_values}
							return config, inputs_dict





@require_tf
class 			__UpperCamelCase (   _A     ,		_A     ,		unittest.TestCase						):
		SCREAMING_SNAKE_CASE								=    (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
		SCREAMING_SNAKE_CASE								=    (
		    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
		    if is_tf_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE								=    False
		SCREAMING_SNAKE_CASE								=    False
		SCREAMING_SNAKE_CASE								=    False
		SCREAMING_SNAKE_CASE								=    False
		SCREAMING_SNAKE_CASE								=    False


		def 					SCREAMING_SNAKE_CASE__   (self :		Dict):
							A			=					TFConvNextModelTester(self)
							A			=					ConfigTester(
							    self     ,     config_class=__SCREAMING_SNAKE_CASE     ,     has_text_modality=__SCREAMING_SNAKE_CASE     ,     hidden_size=3_7     ,     )


		@unittest.skip(reason="ConvNext does not use inputs_embeds")
		def 					SCREAMING_SNAKE_CASE__   (self :		List[str]):
							pass


		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0     ,     reason="TF does not support backprop for grouped convolutions on CPU."     ,     )
		@slow
		def 					SCREAMING_SNAKE_CASE__   (self :		List[Any]):
							super().test_keras_fit()


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


		def 					SCREAMING_SNAKE_CASE__   (self :		Dict):
							A			,    A			=					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												A			=					model_class(__SCREAMING_SNAKE_CASE)
												A			=					inspect.signature(model.call)
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												A			=					[*signature.parameters.keys()]

												A			=					["pixel_values"]
												self.assertListEqual(arg_names[:1]     ,     __SCREAMING_SNAKE_CASE)


		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[int]):
							A			=					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE)


		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0     ,     reason="TF does not support backprop for grouped convolutions on CPU."     ,     )
		def 					SCREAMING_SNAKE_CASE__   (self :		Tuple):
							super().test_dataset_conversion()


		def 					SCREAMING_SNAKE_CASE__   (self :		List[Any]):
							def check_hidden_states_output(__SCREAMING_SNAKE_CASE :		List[Any]     ,     __SCREAMING_SNAKE_CASE :		Any     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]):
												A			=					model_class(__SCREAMING_SNAKE_CASE)

												A			=					model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE))
												A			=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												A			=					self.model_tester.num_stages
												self.assertEqual(len(__SCREAMING_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]     ,     )

							A			,    A			=					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												A			=					True
												check_hidden_states_output(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)

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

												check_hidden_states_output(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)


		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[int]):
							A			,    A			=					self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(__SCREAMING_SNAKE_CASE :		Union[str, Any]     ,     __SCREAMING_SNAKE_CASE :		List[Any]     ,     __SCREAMING_SNAKE_CASE :		List[str]     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]={}):
												A			=					model(__SCREAMING_SNAKE_CASE     ,     return_dict=__SCREAMING_SNAKE_CASE     ,     **__SCREAMING_SNAKE_CASE)
												A			=					model(__SCREAMING_SNAKE_CASE     ,     return_dict=__SCREAMING_SNAKE_CASE     ,     **__SCREAMING_SNAKE_CASE).to_tuple()

												def recursive_check(__SCREAMING_SNAKE_CASE :		Tuple     ,     __SCREAMING_SNAKE_CASE :		Tuple):
																	if isinstance(__SCREAMING_SNAKE_CASE     ,     (List, Tuple)):
																						for tuple_iterable_value, dict_iterable_value in zip(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE):
																											recursive_check(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)
																	elif tuple_object is None:
																						return
																	else:
																						self.assertTrue(
																						    all(tf.equal(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE))     ,     msg=(
																						        "Tuple and dict output are not equal. Difference:"
																						        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"""
																						    )     ,     )

																	recursive_check(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)

							for model_class in self.all_model_classes:
												A			=					model_class(__SCREAMING_SNAKE_CASE)

												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)
												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)
												check_equivalence(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)

												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     return_labels=__SCREAMING_SNAKE_CASE)
												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     return_labels=__SCREAMING_SNAKE_CASE)
												check_equivalence(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)

												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)
												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE)
												check_equivalence(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     {"output_hidden_states": True})

												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     return_labels=__SCREAMING_SNAKE_CASE)
												A			=					self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     return_labels=__SCREAMING_SNAKE_CASE)
												check_equivalence(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     {"output_hidden_states": True})


		def 					SCREAMING_SNAKE_CASE__   (self :		Any):
							A			=					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE)


		@slow
		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[Any]):
							A			=					TFConvNextModel.from_pretrained("facebook/convnext-tiny-224")
							self.assertIsNotNone(__SCREAMING_SNAKE_CASE)

def    __SCREAMING_SNAKE_CASE						(						):
					"""simple docstring"""
					A			=					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
					return image





@require_tf
@require_vision
class 			__UpperCamelCase (   unittest.TestCase						):


		@cached_property
		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[int]):
							return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224") if is_vision_available() else None


		@slow
		def 					SCREAMING_SNAKE_CASE__   (self :		Tuple):
							A			=					TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224")

							A			=					self.default_image_processor
							A			=					prepare_img()
							A			=					image_processor(images=__SCREAMING_SNAKE_CASE     ,     return_tensors="tf")

							# forward pass
							A			=					model(**__SCREAMING_SNAKE_CASE)

							# verify the logits
							A			=					tf.TensorShape((1, 1_0_0_0))
							self.assertEqual(outputs.logits.shape     ,     __SCREAMING_SNAKE_CASE)

							A			=					tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1])

							tf.debugging.assert_near(outputs.logits[0, :3]     ,     __SCREAMING_SNAKE_CASE     ,     atol=1E-4)








"""simple docstring"""




import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A     :    str    =		logging.get_logger(__name__)

__A     :    Union[str, Any]    =		{
    'facebook/sam-vit-huge': 'https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json',
    'facebook/sam-vit-large': 'https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json',
    'facebook/sam-vit-base': 'https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json',
}





class 			__UpperCamelCase (   _A						):


		def __init__(self :		int     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=2_5_6     ,     __SCREAMING_SNAKE_CASE :		List[str]=1_0_2_4     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=1_6     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=1_6     ,     __SCREAMING_SNAKE_CASE :		List[str]=4     ,     __SCREAMING_SNAKE_CASE :		List[Any]="gelu"     ,     __SCREAMING_SNAKE_CASE :		str=1E-6     ,     **__SCREAMING_SNAKE_CASE :		Optional[int]     ,     ):
							super().__init__(**__SCREAMING_SNAKE_CASE)
							A			=					hidden_size
							A			=					image_size
							A			=					patch_size
							A			=					image_size // patch_size
							A			=					mask_input_channels
							A			=					num_point_embeddings
							A			=					hidden_act
							A			=					layer_norm_eps





class 			__UpperCamelCase (   _A						):


		def __init__(self :		List[Any]     ,     __SCREAMING_SNAKE_CASE :		Tuple=2_5_6     ,     __SCREAMING_SNAKE_CASE :		str="relu"     ,     __SCREAMING_SNAKE_CASE :		List[Any]=2_0_4_8     ,     __SCREAMING_SNAKE_CASE :		Tuple=2     ,     __SCREAMING_SNAKE_CASE :		Any=8     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]=2     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=3     ,     __SCREAMING_SNAKE_CASE :		List[Any]=3     ,     __SCREAMING_SNAKE_CASE :		Tuple=2_5_6     ,     __SCREAMING_SNAKE_CASE :		int=1E-6     ,     **__SCREAMING_SNAKE_CASE :		int     ,     ):
							super().__init__(**__SCREAMING_SNAKE_CASE)
							A			=					hidden_size
							A			=					hidden_act
							A			=					mlp_dim
							A			=					num_hidden_layers
							A			=					num_attention_heads
							A			=					attention_downsample_rate
							A			=					num_multimask_outputs
							A			=					iou_head_depth
							A			=					iou_head_hidden_dim
							A			=					layer_norm_eps





class 			__UpperCamelCase (   _A						):


		def __init__(self :		List[str]     ,     __SCREAMING_SNAKE_CASE :		List[Any]=7_6_8     ,     __SCREAMING_SNAKE_CASE :		int=2_5_6     ,     __SCREAMING_SNAKE_CASE :		Tuple=1_2     ,     __SCREAMING_SNAKE_CASE :		str=1_2     ,     __SCREAMING_SNAKE_CASE :		Any=3     ,     __SCREAMING_SNAKE_CASE :		Dict=1_0_2_4     ,     __SCREAMING_SNAKE_CASE :		str=1_6     ,     __SCREAMING_SNAKE_CASE :		Tuple="gelu"     ,     __SCREAMING_SNAKE_CASE :		int=1E-06     ,     __SCREAMING_SNAKE_CASE :		Dict=0.0     ,     __SCREAMING_SNAKE_CASE :		str=1E-10     ,     __SCREAMING_SNAKE_CASE :		List[str]=True     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]=4.0     ,     __SCREAMING_SNAKE_CASE :		str=True     ,     __SCREAMING_SNAKE_CASE :		Any=True     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=1_4     ,     __SCREAMING_SNAKE_CASE :		Tuple=[2, 5, 8, 1_1]     ,     __SCREAMING_SNAKE_CASE :		str=1_2_8     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=None     ,     **__SCREAMING_SNAKE_CASE :		Optional[Any]     ,     ):
							super().__init__(**__SCREAMING_SNAKE_CASE)

							A			=					hidden_size
							A			=					output_channels
							A			=					num_hidden_layers
							A			=					num_attention_heads
							A			=					num_channels
							A			=					image_size
							A			=					patch_size
							A			=					hidden_act
							A			=					layer_norm_eps
							A			=					attention_dropout
							A			=					initializer_range
							A			=					qkv_bias
							A			=					mlp_ratio
							A			=					use_abs_pos
							A			=					use_rel_pos
							A			=					window_size
							A			=					global_attn_indexes
							A			=					num_pos_feats
							A			=					int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim





class 			__UpperCamelCase (   _A						):
		SCREAMING_SNAKE_CASE								=    "sam"
		SCREAMING_SNAKE_CASE								=    True


		def __init__(self :		Optional[int]     ,     __SCREAMING_SNAKE_CASE :		Dict=None     ,     __SCREAMING_SNAKE_CASE :		Union[str, Any]=None     ,     __SCREAMING_SNAKE_CASE :		Optional[int]=None     ,     __SCREAMING_SNAKE_CASE :		List[Any]=0.0_2     ,     **__SCREAMING_SNAKE_CASE :		Optional[Any]     ,     ):
							super().__init__(**__SCREAMING_SNAKE_CASE)
							A			=					vision_config if vision_config is not None else {}
							A			=					prompt_encoder_config if prompt_encoder_config is not None else {}
							A			=					mask_decoder_config if mask_decoder_config is not None else {}

							if isinstance(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE):
												A			=					vision_config.to_dict()
							if isinstance(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE):
												A			=					prompt_encoder_config.to_dict()
							if isinstance(__SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE):
												A			=					mask_decoder_config.to_dict()

							A			=					SamVisionConfig(**__SCREAMING_SNAKE_CASE)
							A			=					SamPromptEncoderConfig(**__SCREAMING_SNAKE_CASE)
							A			=					SamMaskDecoderConfig(**__SCREAMING_SNAKE_CASE)
							A			=					initializer_range


		def 					SCREAMING_SNAKE_CASE__   (self :		List[str]):
							A			=					copy.deepcopy(self.__dict__)
							A			=					self.vision_config.to_dict()
							A			=					self.prompt_encoder_config.to_dict()
							A			=					self.mask_decoder_config.to_dict()
							A			=					self.__class__.model_type
							return output





