

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







						def __init__(			self     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE=13     ,						_SCREAMING_SNAKE_CASE=32     ,						_SCREAMING_SNAKE_CASE=3     ,						_SCREAMING_SNAKE_CASE=4     ,						_SCREAMING_SNAKE_CASE=[10, 20, 30, 40]     ,						_SCREAMING_SNAKE_CASE=[2, 2, 3, 2]     ,						_SCREAMING_SNAKE_CASE=True     ,						_SCREAMING_SNAKE_CASE=True     ,						_SCREAMING_SNAKE_CASE=37     ,						_SCREAMING_SNAKE_CASE="gelu"     ,						_SCREAMING_SNAKE_CASE=10     ,						_SCREAMING_SNAKE_CASE=0.0_2     ,						_SCREAMING_SNAKE_CASE=3     ,						_SCREAMING_SNAKE_CASE=None     ,						)->							str:
													lowerCamelCase_								=parent
													lowerCamelCase_								=batch_size
													lowerCamelCase_								=image_size
													lowerCamelCase_								=num_channels
													lowerCamelCase_								=num_stages
													lowerCamelCase_								=hidden_sizes
													lowerCamelCase_								=depths
													lowerCamelCase_								=is_training
													lowerCamelCase_								=use_labels
													lowerCamelCase_								=intermediate_size
													lowerCamelCase_								=hidden_act
													lowerCamelCase_								=type_sequence_label_size
													lowerCamelCase_								=initializer_range
													lowerCamelCase_								=scope







						def        _snake_case				(			self							)->							Union[str, Any]:
													lowerCamelCase_								=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

													lowerCamelCase_								=self.get_config()

													return config, pixel_values, labels







						def        _snake_case				(			self							)->							Optional[Any]:
													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        _snake_case				(			self     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)->							int:
													lowerCamelCase_								=TFConvNextModel(config=_SCREAMING_SNAKE_CASE							)
													lowerCamelCase_								=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 // 32, self.image_size // 32)     ,						)







						def        _snake_case				(			self     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)->							List[Any]:
													lowerCamelCase_								=self.type_sequence_label_size
													lowerCamelCase_								=TFConvNextForImageClassification(_SCREAMING_SNAKE_CASE							)
													lowerCamelCase_								=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        _snake_case				(			self							)->							str:
													lowerCamelCase_								=self.prepare_config_and_inputs()
													lowerCamelCase_	,   lowerCamelCase_	,   lowerCamelCase_								=config_and_inputs
													lowerCamelCase_								={"""pixel_values""": pixel_values}
													return config, inputs_dict


@require_tf
class 			_SCREAMING_SNAKE_CASE      (  lowerCAmelCase__ ,    lowerCAmelCase__ ,    unittest.TestCase):
						_UpperCamelCase:Optional[int]	=		(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
						_UpperCamelCase:Any	=		(
						    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
						    if is_tf_available()
						    else {}
						)

						_UpperCamelCase:List[Any]	=		False
						_UpperCamelCase:List[str]	=		False
						_UpperCamelCase:Dict	=		False
						_UpperCamelCase:List[str]	=		False
						_UpperCamelCase:Optional[Any]	=		False







						def        _snake_case				(			self							)->							Any:
													lowerCamelCase_								=TFConvNextModelTester(self							)
													lowerCamelCase_								=ConfigTester(
													    self     ,						config_class=_SCREAMING_SNAKE_CASE     ,						has_text_modality=_SCREAMING_SNAKE_CASE     ,						hidden_size=37     ,						)







						@unittest.skip(reason="""ConvNext does not use inputs_embeds"""							)
						def        _snake_case				(			self							)->							List[Any]:
													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        _snake_case				(			self							)->							int:
													super().test_keras_fit()







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







						def        _snake_case				(			self							)->							Optional[int]:
													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

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

																				lowerCamelCase_								=["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]     ,						_SCREAMING_SNAKE_CASE							)







						def        _snake_case				(			self							)->							Tuple:
													lowerCamelCase_								=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        _snake_case				(			self							)->							Optional[int]:
													super().test_dataset_conversion()







						def        _snake_case				(			self							)->							Optional[Any]:
													def check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							):
																				lowerCamelCase_								=model_class(_SCREAMING_SNAKE_CASE							)

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

																				lowerCamelCase_								=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]     ,						)

													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				lowerCamelCase_								=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"]
																				lowerCamelCase_								=True

																				check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)







						def        _snake_case				(			self							)->							int:
													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

													def check_equivalence(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE={}							):
																				lowerCamelCase_								=model(_SCREAMING_SNAKE_CASE     ,						return_dict=_SCREAMING_SNAKE_CASE     ,						**_SCREAMING_SNAKE_CASE							)
																				lowerCamelCase_								=model(_SCREAMING_SNAKE_CASE     ,						return_dict=_SCREAMING_SNAKE_CASE     ,						**_SCREAMING_SNAKE_CASE							).to_tuple()

																				def recursive_check(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							):
																											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:
																				lowerCamelCase_								=model_class(_SCREAMING_SNAKE_CASE							)

																				lowerCamelCase_								=self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)
																				lowerCamelCase_								=self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)
																				check_equivalence(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)

																				lowerCamelCase_								=self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						return_labels=_SCREAMING_SNAKE_CASE							)
																				lowerCamelCase_								=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							)

																				lowerCamelCase_								=self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)
																				lowerCamelCase_								=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}							)

																				lowerCamelCase_								=self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						return_labels=_SCREAMING_SNAKE_CASE							)
																				lowerCamelCase_								=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        _snake_case				(			self							)->							str:
													lowerCamelCase_								=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE							)







						@slow
						def        _snake_case				(			self							)->							Tuple:
													lowerCamelCase_								=TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""							)
													self.assertIsNotNone(_SCREAMING_SNAKE_CASE							)




def        __UpperCamelCase     (      )				->str:



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






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







						@cached_property
						def        _snake_case				(			self							)->							List[Any]:
													return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""							) if is_vision_available() else None







						@slow
						def        _snake_case				(			self							)->							str:
													lowerCamelCase_								=TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""							)

													lowerCamelCase_								=self.default_image_processor
													lowerCamelCase_								=prepare_img()
													lowerCamelCase_								=image_processor(images=_SCREAMING_SNAKE_CASE     ,						return_tensors="""tf"""							)

													# forward pass
													lowerCamelCase_								=model(**_SCREAMING_SNAKE_CASE							)

													# verify the logits
													lowerCamelCase_								=tf.TensorShape((1, 1000)							)
													self.assertEqual(outputs.logits.shape     ,						_SCREAMING_SNAKE_CASE							)

													lowerCamelCase_								=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							)



from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__A	:   List[Any]	=					logging.get_logger(__name__)

__A	:   Tuple	=					{
    'google/electra-small-generator': 'https://huggingface.co/google/electra-small-generator/resolve/main/config.json',
    'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/config.json',
    'google/electra-large-generator': 'https://huggingface.co/google/electra-large-generator/resolve/main/config.json',
    'google/electra-small-discriminator': (
        'https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json'
    ),
    'google/electra-base-discriminator': (
        'https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json'
    ),
    'google/electra-large-discriminator': (
        'https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json'
    ),
}


class 			_SCREAMING_SNAKE_CASE      (  lowerCAmelCase__):
						_UpperCamelCase:Tuple	=		"electra"







						def __init__(			self     ,						_SCREAMING_SNAKE_CASE=3_0522     ,						_SCREAMING_SNAKE_CASE=128     ,						_SCREAMING_SNAKE_CASE=256     ,						_SCREAMING_SNAKE_CASE=12     ,						_SCREAMING_SNAKE_CASE=4     ,						_SCREAMING_SNAKE_CASE=1024     ,						_SCREAMING_SNAKE_CASE="gelu"     ,						_SCREAMING_SNAKE_CASE=0.1     ,						_SCREAMING_SNAKE_CASE=0.1     ,						_SCREAMING_SNAKE_CASE=512     ,						_SCREAMING_SNAKE_CASE=2     ,						_SCREAMING_SNAKE_CASE=0.0_2     ,						_SCREAMING_SNAKE_CASE=1E-12     ,						_SCREAMING_SNAKE_CASE="first"     ,						_SCREAMING_SNAKE_CASE=True     ,						_SCREAMING_SNAKE_CASE="gelu"     ,						_SCREAMING_SNAKE_CASE=0.1     ,						_SCREAMING_SNAKE_CASE=0     ,						_SCREAMING_SNAKE_CASE="absolute"     ,						_SCREAMING_SNAKE_CASE=True     ,						_SCREAMING_SNAKE_CASE=None     ,						**_SCREAMING_SNAKE_CASE     ,						)->							Optional[int]:
													super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE     ,						**_SCREAMING_SNAKE_CASE							)

													lowerCamelCase_								=vocab_size
													lowerCamelCase_								=embedding_size
													lowerCamelCase_								=hidden_size
													lowerCamelCase_								=num_hidden_layers
													lowerCamelCase_								=num_attention_heads
													lowerCamelCase_								=intermediate_size
													lowerCamelCase_								=hidden_act
													lowerCamelCase_								=hidden_dropout_prob
													lowerCamelCase_								=attention_probs_dropout_prob
													lowerCamelCase_								=max_position_embeddings
													lowerCamelCase_								=type_vocab_size
													lowerCamelCase_								=initializer_range
													lowerCamelCase_								=layer_norm_eps

													lowerCamelCase_								=summary_type
													lowerCamelCase_								=summary_use_proj
													lowerCamelCase_								=summary_activation
													lowerCamelCase_								=summary_last_dropout
													lowerCamelCase_								=position_embedding_type
													lowerCamelCase_								=use_cache
													lowerCamelCase_								=classifier_dropout


class 			_SCREAMING_SNAKE_CASE      (  lowerCAmelCase__):







						@property
						def        _snake_case				(			self							)->							Mapping[str, Mapping[int, str]]:
													if self.task == "multiple-choice":
																				lowerCamelCase_								={0: """batch""", 1: """choice""", 2: """sequence"""}
													else:
																				lowerCamelCase_								={0: """batch""", 1: """sequence"""}
													return OrderedDict(
													    [
													        ("""input_ids""", dynamic_axis),
													        ("""attention_mask""", dynamic_axis),
													        ("""token_type_ids""", dynamic_axis),
													    ]							)
