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					:     Optional[int]			,			_lowerCAmelCase					:     Any			,			_lowerCAmelCase					:     Dict=13			,			_lowerCAmelCase					:     List[str]=32			,			_lowerCAmelCase					:     Optional[int]=3			,			_lowerCAmelCase					:     str=4			,			_lowerCAmelCase					:     Optional[Any]=[10, 20, 30, 40]			,			_lowerCAmelCase					:     Union[str, Any]=[2, 2, 3, 2]			,			_lowerCAmelCase					:     Any=True			,			_lowerCAmelCase					:     Any=True			,			_lowerCAmelCase					:     Optional[int]=37			,			_lowerCAmelCase					:     Optional[Any]="gelu"			,			_lowerCAmelCase					:     Any=10			,			_lowerCAmelCase					:     Optional[int]=0.02			,			_lowerCAmelCase					:     int=3			,			_lowerCAmelCase					:     Optional[int]=None			,			):
           __snake_case       :				Optional[Any] 			=    parent
           __snake_case       :				Any 			=    batch_size
           __snake_case       :				Tuple 			=    image_size
           __snake_case       :				List[str] 			=    num_channels
           __snake_case       :				List[str] 			=    num_stages
           __snake_case       :				List[str] 			=    hidden_sizes
           __snake_case       :				int 			=    depths
           __snake_case       :				List[Any] 			=    is_training
           __snake_case       :				Dict 			=    use_labels
           __snake_case       :				Union[str, Any] 			=    intermediate_size
           __snake_case       :				str 			=    hidden_act
           __snake_case       :				Tuple 			=    type_sequence_label_size
           __snake_case       :				Dict 			=    initializer_range
           __snake_case       :				List[str] 			=    scope

       def 			snake_case__    (							self					:     Optional[int]			):
           __snake_case       :				Dict 			=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

           __snake_case       :				str 			=    None
           if self.use_labels:
               __snake_case       :				Tuple 			=    ids_tensor([self.batch_size]			,			self.type_sequence_label_size			)

           __snake_case       :				Tuple 			=    self.get_config()

           return config, pixel_values, labels

       def 			snake_case__    (							self					:     int			):
           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=_lowerCAmelCase			,			initializer_range=self.initializer_range			,			)

       def 			snake_case__    (							self					:     Optional[int]			,			_lowerCAmelCase					:     Optional[int]			,			_lowerCAmelCase					:     Dict			,			_lowerCAmelCase					:     Any			):
           __snake_case       :				str 			=    TFConvNextModel(config=_lowerCAmelCase			)
           __snake_case       :				Any 			=    model(_lowerCAmelCase			,			training=_lowerCAmelCase			)
           # 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					:     Dict			,			_lowerCAmelCase					:     List[Any]			,			_lowerCAmelCase					:     str			,			_lowerCAmelCase					:     int			):
           __snake_case       :				Union[str, Any] 			=    self.type_sequence_label_size
           __snake_case       :				List[str] 			=    TFConvNextForImageClassification(_lowerCAmelCase			)
           __snake_case       :				Union[str, Any] 			=    model(_lowerCAmelCase			,			labels=_lowerCAmelCase			,			training=_lowerCAmelCase			)
           self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.type_sequence_label_size)			)





       def 			snake_case__    (							self					:     Dict			):
           __snake_case       :				Union[str, Any] 			=    self.prepare_config_and_inputs()
           __snake_case			, __snake_case			, __snake_case       :				str 			=    config_and_inputs
           __snake_case       :				List[str] 			=    {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_tf
class      SCREAMING_SNAKE_CASE__					(  __UpperCamelCase   ,							__UpperCamelCase   ,							unittest.TestCase    ):
       A							:	Union[str, Any]          =	(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       A							:	Union[str, Any]          =	(
           {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       A							:	Dict          =	False
       A							:	Tuple          =	False
       A							:	List[Any]          =	False
       A							:	Optional[Any]          =	False
       A							:	List[str]          =	False

       def 			snake_case__    (							self					:     Union[str, Any]			):
           __snake_case       :				int 			=    TFConvNextModelTester(self			)
           __snake_case       :				Any 			=    ConfigTester(
               self			,			config_class=_lowerCAmelCase			,			has_text_modality=_lowerCAmelCase			,			hidden_size=37			,			)

       @unittest.skip(reason="""ConvNext does not use inputs_embeds"""			)
       def 			snake_case__    (							self					:     Optional[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]			):
           __snake_case			, __snake_case       :				Dict 			=    self.model_tester.prepare_config_and_inputs_for_common()

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

               __snake_case       :				List[str] 			=    ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]			,			_lowerCAmelCase			)

       def 			snake_case__    (							self					:     List[Any]			):
           __snake_case       :				str 			=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowerCAmelCase			)

       @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					:     int			):
           super().test_dataset_conversion()

       def 			snake_case__    (							self					:     Optional[Any]			):
           def check_hidden_states_output(_lowerCAmelCase					:     Union[str, Any]			,			_lowerCAmelCase					:     List[str]			,			_lowerCAmelCase					:     Union[str, Any]			):
               __snake_case       :				List[Any] 			=    model_class(_lowerCAmelCase			)

               __snake_case       :				str 			=    model(**self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)			)
               __snake_case       :				int 			=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               __snake_case       :				str 			=    self.model_tester.num_stages
               self.assertEqual(len(_lowerCAmelCase			)			,			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]			,			)

           __snake_case			, __snake_case       :				str 			=    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __snake_case       :				List[str] 			=    True
               check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __snake_case       :				int 			=    True

               check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

       def 			snake_case__    (							self					:     List[Any]			):
           __snake_case			, __snake_case       :				List[str] 			=    self.model_tester.prepare_config_and_inputs_for_common()

           def check_equivalence(_lowerCAmelCase					:     Union[str, Any]			,			_lowerCAmelCase					:     Optional[Any]			,			_lowerCAmelCase					:     int			,			_lowerCAmelCase					:     Optional[int]={}			):
               __snake_case       :				Tuple 			=    model(_lowerCAmelCase			,			return_dict=_lowerCAmelCase			,			**_lowerCAmelCase			)
               __snake_case       :				List[Any] 			=    model(_lowerCAmelCase			,			return_dict=_lowerCAmelCase			,			**_lowerCAmelCase			).to_tuple()

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

                   recursive_check(_lowerCAmelCase			,			_lowerCAmelCase			)

           for model_class in self.all_model_classes:
               __snake_case       :				Tuple 			=    model_class(_lowerCAmelCase			)

               __snake_case       :				Any 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)
               __snake_case       :				int 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)
               check_equivalence(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

               __snake_case       :				List[str] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			,			return_labels=_lowerCAmelCase			)
               __snake_case       :				Optional[int] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			,			return_labels=_lowerCAmelCase			)
               check_equivalence(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

               __snake_case       :				Optional[int] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)
               __snake_case       :				Union[str, Any] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)
               check_equivalence(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			{"""output_hidden_states""": True}			)

               __snake_case       :				List[str] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			,			return_labels=_lowerCAmelCase			)
               __snake_case       :				List[Any] 			=    self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			,			return_labels=_lowerCAmelCase			)
               check_equivalence(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			{"""output_hidden_states""": True}			)

       def 			snake_case__    (							self					:     Optional[int]			):
           __snake_case       :				Optional[int] 			=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase			)





       @slow
       def 			snake_case__    (							self					:     Dict			):
           __snake_case       :				List[str] 			=    TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""			)
           self.assertIsNotNone(_lowerCAmelCase			)







def 					__lowerCAmelCase				(		):







    '''simple docstring'''
    __snake_case       :				Optional[int] 			=    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					:     Tuple			):
           return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""			) if is_vision_available() else None





       @slow
       def 			snake_case__    (							self					:     int			):
           __snake_case       :				Optional[int] 			=    TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""			)

           __snake_case       :				List[Any] 			=    self.default_image_processor
           __snake_case       :				List[Any] 			=    prepare_img()
           __snake_case       :				str 			=    image_processor(images=_lowerCAmelCase			,			return_tensors="""tf"""			)

           # forward pass
           __snake_case       :				Dict 			=    model(**_lowerCAmelCase			)

           # verify the logits
           __snake_case       :				Optional[int] 			=    tf.TensorShape((1, 10_00)			)
           self.assertEqual(outputs.logits.shape			,			_lowerCAmelCase			)

           __snake_case       :				Optional[Any] 			=    tf.constant([-0.0260, -0.4739, 0.1911]			)

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




from collections import OrderedDict
from typing import Mapping

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


lowercase_  							=			logging.get_logger(__name__)

lowercase_  							=			{
    "google/mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json"
}







class      SCREAMING_SNAKE_CASE__					(  __UpperCamelCase    ):
       A							:	List[Any]          =	MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
       A							:	int          =	"mobilebert"

       def __init__(							self					:     Any			,			_lowerCAmelCase					:     Union[str, Any]=3_05_22			,			_lowerCAmelCase					:     Tuple=5_12			,			_lowerCAmelCase					:     Dict=24			,			_lowerCAmelCase					:     int=4			,			_lowerCAmelCase					:     Optional[Any]=5_12			,			_lowerCAmelCase					:     Union[str, Any]="relu"			,			_lowerCAmelCase					:     List[str]=0.0			,			_lowerCAmelCase					:     str=0.1			,			_lowerCAmelCase					:     Tuple=5_12			,			_lowerCAmelCase					:     Optional[Any]=2			,			_lowerCAmelCase					:     Optional[int]=0.02			,			_lowerCAmelCase					:     List[str]=1e-12			,			_lowerCAmelCase					:     int=0			,			_lowerCAmelCase					:     Union[str, Any]=1_28			,			_lowerCAmelCase					:     Optional[Any]=True			,			_lowerCAmelCase					:     Dict=True			,			_lowerCAmelCase					:     Any=1_28			,			_lowerCAmelCase					:     Optional[int]=False			,			_lowerCAmelCase					:     str=True			,			_lowerCAmelCase					:     Tuple=4			,			_lowerCAmelCase					:     List[str]="no_norm"			,			_lowerCAmelCase					:     Union[str, Any]=True			,			_lowerCAmelCase					:     Optional[int]=None			,			**_lowerCAmelCase					:     int			,			):
           super().__init__(pad_token_id=_lowerCAmelCase			,			**_lowerCAmelCase			)

           __snake_case       :				Any 			=    vocab_size
           __snake_case       :				Tuple 			=    hidden_size
           __snake_case       :				int 			=    num_hidden_layers
           __snake_case       :				Dict 			=    num_attention_heads
           __snake_case       :				List[Any] 			=    hidden_act
           __snake_case       :				List[Any] 			=    intermediate_size
           __snake_case       :				Union[str, Any] 			=    hidden_dropout_prob
           __snake_case       :				Any 			=    attention_probs_dropout_prob
           __snake_case       :				Any 			=    max_position_embeddings
           __snake_case       :				List[Any] 			=    type_vocab_size
           __snake_case       :				List[Any] 			=    initializer_range
           __snake_case       :				Dict 			=    layer_norm_eps
           __snake_case       :				Any 			=    embedding_size
           __snake_case       :				List[str] 			=    trigram_input
           __snake_case       :				Union[str, Any] 			=    use_bottleneck
           __snake_case       :				List[Any] 			=    intra_bottleneck_size
           __snake_case       :				Tuple 			=    use_bottleneck_attention
           __snake_case       :				Optional[Any] 			=    key_query_shared_bottleneck
           __snake_case       :				Tuple 			=    num_feedforward_networks
           __snake_case       :				int 			=    normalization_type
           __snake_case       :				List[Any] 			=    classifier_activation

           if self.use_bottleneck:
               __snake_case       :				List[str] 			=    intra_bottleneck_size
           else:
               __snake_case       :				int 			=    hidden_size

           __snake_case       :				Optional[Any] 			=    classifier_dropout







class      SCREAMING_SNAKE_CASE__					(  __UpperCamelCase    ):

       @property
       def 			snake_case__    (							self					:     Optional[Any]			):
           if self.task == "multiple-choice":
               __snake_case       :				Any 			=    {0: """batch""", 1: """choice""", 2: """sequence"""}
           else:
               __snake_case       :				Optional[Any] 			=    {0: """batch""", 1: """sequence"""}
           return OrderedDict(
               [
                   ("""input_ids""", dynamic_axis),
                   ("""attention_mask""", dynamic_axis),
                   ("""token_type_ids""", dynamic_axis),
               ]			)



