





"""simple docstring"""


from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
      from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor







class       __a  (    _SCREAMING_SNAKE_CASE						):



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   self.config_class(**self.inputs_dict  )
            self.parent.assertTrue(hasattr(_lowerCAmelCase   ,	'embed_dim'  )  )
            self.parent.assertTrue(hasattr(_lowerCAmelCase   ,	'num_heads'  )  )







class       __a  :



     def __init__(			self   ,	a__   ,	a__=13   ,	a__=64   ,	a__=3   ,	a__=[16, 48, 96]   ,	a__=[1, 3, 6]   ,	a__=[1, 2, 10]   ,	a__=[7, 3, 3]   ,	a__=[4, 2, 2]   ,	a__=[2, 1, 1]   ,	a__=[2, 2, 2]   ,	a__=[False, False, True]   ,	a__=[0.0, 0.0, 0.0]   ,	a__=0.02   ,	a__=1e-12   ,	a__=True   ,	a__=True   ,	a__=2   ,	):
            _lowerCamelCase             =   parent
            _lowerCamelCase             =   batch_size
            _lowerCamelCase             =   image_size
            _lowerCamelCase             =   patch_sizes
            _lowerCamelCase             =   patch_stride
            _lowerCamelCase             =   patch_padding
            _lowerCamelCase             =   is_training
            _lowerCamelCase             =   use_labels
            _lowerCamelCase             =   num_labels
            _lowerCamelCase             =   num_channels
            _lowerCamelCase             =   embed_dim
            _lowerCamelCase             =   num_heads
            _lowerCamelCase             =   stride_kv
            _lowerCamelCase             =   depth
            _lowerCamelCase             =   cls_token
            _lowerCamelCase             =   attention_drop_rate
            _lowerCamelCase             =   initializer_range
            _lowerCamelCase             =   layer_norm_eps



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

            _lowerCamelCase             =   None
            if self.use_labels:
                   # create a random int32 tensor of given shape
                   _lowerCamelCase             =   ids_tensor([self.batch_size]   ,	self.num_labels  )

            _lowerCamelCase             =   self.get_config()
            return config, pixel_values, labels



     def 		snake_case_     (			self  ):
            return CvtConfig(
                image_size=self.image_size   ,	num_labels=self.num_labels   ,	num_channels=self.num_channels   ,	embed_dim=self.embed_dim   ,	num_heads=self.num_heads   ,	patch_sizes=self.patch_sizes   ,	patch_padding=self.patch_padding   ,	patch_stride=self.patch_stride   ,	stride_kv=self.stride_kv   ,	depth=self.depth   ,	cls_token=self.cls_token   ,	attention_drop_rate=self.attention_drop_rate   ,	initializer_range=self.initializer_range   ,	)



     def 		snake_case_     (			self   ,	a__   ,	a__   ,	a__  ):
            _lowerCamelCase             =   TFCvtModel(config=_lowerCAmelCase  )
            _lowerCamelCase             =   model(_lowerCAmelCase   ,	training=_lowerCAmelCase  )
            _lowerCamelCase             =   (self.image_size, self.image_size)
            _lowerCamelCase      ,      _lowerCamelCase             =   image_size[0], image_size[1]
            for i in range(len(self.depth  )  ):
                   _lowerCamelCase             =   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1  )
                   _lowerCamelCase             =   floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1  )
            self.parent.assertEqual(result.last_hidden_state.shape   ,	(self.batch_size, self.embed_dim[-1], height, width)  )



     def 		snake_case_     (			self   ,	a__   ,	a__   ,	a__  ):
            _lowerCamelCase             =   self.num_labels
            _lowerCamelCase             =   TFCvtForImageClassification(_lowerCAmelCase  )
            _lowerCamelCase             =   model(_lowerCAmelCase   ,	labels=_lowerCAmelCase   ,	training=_lowerCAmelCase  )
            self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.num_labels)  )



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   self.prepare_config_and_inputs()
            _lowerCamelCase      ,      _lowerCamelCase      ,      _lowerCamelCase             =   config_and_inputs
            _lowerCamelCase             =   {'pixel_values': pixel_values}
            return config, inputs_dict







@require_tf
class       __a  (    _SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		unittest.TestCase						):
     SCREAMING_SNAKE_CASE__					: int									=     (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE__					: int									=     (
         {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
         if is_tf_available()
         else {}
     )
     SCREAMING_SNAKE_CASE__					: List[str]									=     False
     SCREAMING_SNAKE_CASE__					: Union[str, Any]									=     False
     SCREAMING_SNAKE_CASE__					: Optional[int]									=     False
     SCREAMING_SNAKE_CASE__					: Dict									=     False
     SCREAMING_SNAKE_CASE__					: Dict									=     False



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   TFCvtModelTester(self  )
            _lowerCamelCase             =   TFCvtConfigTester(self   ,	config_class=_lowerCAmelCase   ,	has_text_modality=_lowerCAmelCase   ,	hidden_size=37  )



     def 		snake_case_     (			self  ):
            self.config_tester.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()



     @unittest.skip(reason='Cvt does not output attentions'  )
     def 		snake_case_     (			self  ):
            pass



     @unittest.skip(reason='Cvt does not use inputs_embeds'  )
     def 		snake_case_     (			self  ):
            pass



     @unittest.skip(reason='Cvt does not support input and output embeddings'  )
     def 		snake_case_     (			self  ):
            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.'   ,	)
     def 		snake_case_     (			self  ):
            super().test_dataset_conversion()



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



     @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'  )
     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   tf.keras.mixed_precision.Policy('mixed_float16'  )
            tf.keras.mixed_precision.set_global_policy(_lowerCAmelCase  )
            super().test_keras_fit()
            tf.keras.mixed_precision.set_global_policy('float32'  )



     def 		snake_case_     (			self  ):
            _lowerCamelCase      ,      _lowerCamelCase             =   self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                   _lowerCamelCase             =   model_class(_lowerCAmelCase  )
                   _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]   ,	_lowerCAmelCase  )



     def 		snake_case_     (			self  ):
            def check_hidden_states_output(a__   ,	a__   ,	a__  ):
                   _lowerCamelCase             =   model_class(_lowerCAmelCase  )

                   _lowerCamelCase             =   model(**self._prepare_for_class(_lowerCAmelCase   ,	_lowerCAmelCase  )  )
                   _lowerCamelCase             =   outputs.hidden_states

                   _lowerCamelCase             =   len(self.model_tester.depth  )
                   self.assertEqual(len(_lowerCAmelCase  )   ,	_lowerCAmelCase  )

                   # verify the first hidden states (first block)
                   self.assertListEqual(
                       list(hidden_states[0].shape[-3:]  )   ,	[
                           self.model_tester.embed_dim[0],
                           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(_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase  )

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

                   check_hidden_states_output(_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase  )



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_lowerCAmelCase  )



     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase  )



     @slow
     def 		snake_case_     (			self  ):
            for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCamelCase             =   TFCvtModel.from_pretrained(_lowerCAmelCase  )
                   self.assertIsNotNone(_lowerCAmelCase  )





def SCREAMING_SNAKE_CASE_  (			)->						str:
       _lowerCamelCase             =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
       return image







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



     @cached_property
     def 		snake_case_     (			self  ):
            return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )



     @slow
     def 		snake_case_     (			self  ):
            _lowerCamelCase             =   TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

            _lowerCamelCase             =   self.default_image_processor
            _lowerCamelCase             =   prepare_img()
            _lowerCamelCase             =   image_processor(images=_lowerCAmelCase   ,	return_tensors='tf'  )

            # forward pass
            _lowerCamelCase             =   model(**_lowerCAmelCase  )

            # verify the logits
            _lowerCamelCase             =   tf.TensorShape((1, 10_00)  )
            self.assertEqual(outputs.logits.shape   ,	_lowerCAmelCase  )

            _lowerCamelCase             =   tf.constant([0.9285, 0.9015, -0.3150]  )
            self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()   ,	_lowerCAmelCase   ,	atol=1e-4  )  )












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


lowerCamelCase__					:  str      							=				logging.get_logger(__name__)

lowerCamelCase__					:  Tuple      							=				{
    'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/config.json',
    'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json',
    'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/config.json',
    'funnel-transformer/medium-base': 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json',
    'funnel-transformer/intermediate': (
        'https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json'
    ),
    'funnel-transformer/intermediate-base': (
        'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json'
    ),
    'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/config.json',
    'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json',
    'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json',
    'funnel-transformer/xlarge-base': 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json',
}





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       "funnel"
 lowercase_							       =       {
     "hidden_size": "d_model",
     "num_attention_heads": "n_head",
 }



 def __init__(				self    :						int							,							_lowerCAmelCase    :						Optional[int]=30_522							,							_lowerCAmelCase    :						List[str]=[4, 4, 4]							,							_lowerCAmelCase    :						Tuple=None							,							_lowerCAmelCase    :						Optional[int]=2							,							_lowerCAmelCase    :						int=768							,							_lowerCAmelCase    :						Optional[Any]=12							,							_lowerCAmelCase    :						Optional[Any]=64							,							_lowerCAmelCase    :						Optional[Any]=3_072							,							_lowerCAmelCase    :						List[str]="gelu_new"							,							_lowerCAmelCase    :						Any=0.1							,							_lowerCAmelCase    :						int=0.1							,							_lowerCAmelCase    :						Tuple=0.0							,							_lowerCAmelCase    :						List[Any]=0.1							,							_lowerCAmelCase    :						Dict=None							,							_lowerCAmelCase    :						str=1E-9							,							_lowerCAmelCase    :						Any="mean"							,							_lowerCAmelCase    :						Union[str, Any]="relative_shift"							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Tuple=True							,							**_lowerCAmelCase    :						Optional[Any]							,							):
       SCREAMING_SNAKE_CASE_      		=     vocab_size
       SCREAMING_SNAKE_CASE_      		=     block_sizes
       SCREAMING_SNAKE_CASE_      		=     [1] * len(_lowerCAmelCase		) if block_repeats is None else block_repeats
       assert len(_lowerCAmelCase		) == len(
           self.block_repeats		), "`block_sizes` and `block_repeats` should have the same length."
       SCREAMING_SNAKE_CASE_      		=     num_decoder_layers
       SCREAMING_SNAKE_CASE_      		=     d_model
       SCREAMING_SNAKE_CASE_      		=     n_head
       SCREAMING_SNAKE_CASE_      		=     d_head
       SCREAMING_SNAKE_CASE_      		=     d_inner
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout
       SCREAMING_SNAKE_CASE_      		=     attention_dropout
       SCREAMING_SNAKE_CASE_      		=     activation_dropout
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     initializer_std
       SCREAMING_SNAKE_CASE_      		=     layer_norm_eps
       assert pooling_type in [
           "mean",
           "max",
       ], F"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
       SCREAMING_SNAKE_CASE_      		=     pooling_type
       assert attention_type in [
           "relative_shift",
           "factorized",
       ], F"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
       SCREAMING_SNAKE_CASE_      		=     attention_type
       SCREAMING_SNAKE_CASE_      		=     separate_cls
       SCREAMING_SNAKE_CASE_      		=     truncate_seq
       SCREAMING_SNAKE_CASE_      		=     pool_q_only

       super().__init__(**_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       return sum(self.block_sizes		)



 @num_hidden_layers.setter
 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						List[Any]		):
       raise NotImplementedError(
           'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.'		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       return len(self.block_sizes		)




 @num_blocks.setter
 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Union[str, Any]		):
       raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.'		)