






from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
   from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor







class 	SCREAMING_SNAKE_CASE	:




       def __init__(					self      : Union[str, Any]	,    A__      : Tuple	,    A__      : Dict=3	,    A__      : Dict=32	,    A__      : str=3	,    A__      : str=10	,    A__      : Optional[Any]=[10, 20, 30, 40]	,    A__      : Any=[1, 1, 2, 1]	,    A__      : Optional[int]=True	,    A__      : Dict=True	,    A__      : List[Any]="relu"	,    A__      : Optional[int]=3	,    A__      : str=None	,    ):


            """simple docstring"""







            __lowerCamelCase						:       int				   =				parent
            __lowerCamelCase						:       int				   =				batch_size
            __lowerCamelCase						:       str				   =				image_size
            __lowerCamelCase						:       int				   =				num_channels
            __lowerCamelCase						:       int				   =				embeddings_size
            __lowerCamelCase						:       Tuple				   =				hidden_sizes
            __lowerCamelCase						:       int				   =				depths
            __lowerCamelCase						:       Dict				   =				is_training
            __lowerCamelCase						:       Any				   =				use_labels
            __lowerCamelCase						:       Tuple				   =				hidden_act
            __lowerCamelCase						:       int				   =				num_labels
            __lowerCamelCase						:       str				   =				scope
            __lowerCamelCase						:       Optional[int]				   =				len(_lowercase					)




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       List[str]				   =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

            __lowerCamelCase						:       Tuple				   =				None
            if self.use_labels:
                 __lowerCamelCase						:       List[str]				   =				ids_tensor([self.batch_size]	,    self.num_labels					)

            __lowerCamelCase						:       List[Any]				   =				self.get_config()

            return config, pixel_values, labels




       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            return ResNetConfig(
                num_channels=self.num_channels	,    embeddings_size=self.embeddings_size	,    hidden_sizes=self.hidden_sizes	,    depths=self.depths	,    hidden_act=self.hidden_act	,    num_labels=self.num_labels	,    image_size=self.image_size	,    )




       def 					a_					(					self      : Tuple	,    A__      : Tuple	,    A__      : str	,    A__      : Optional[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				TFResNetModel(config=_lowercase					)
            __lowerCamelCase						:       Optional[int]				   =				model(_lowercase					)
            # 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      : List[Any]	,    A__      : int	,    A__      : int	,    A__      : int					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[Any]				   =				self.num_labels
            __lowerCamelCase						:       Union[str, Any]				   =				TFResNetForImageClassification(_lowercase					)
            __lowerCamelCase						:       int				   =				model(_lowercase	,    labels=_lowercase					)
            self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)					)




       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







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







@require_tf
class 	SCREAMING_SNAKE_CASE	(      __snake_case    ,   __snake_case    ,   unittest.TestCase  ):
       snake_case__    :     Union[str, Any]   		=			(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
       snake_case__    :     Optional[int]   		=			(
           {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
           if is_tf_available()
           else {}
       )

       snake_case__    :     Union[str, Any]   		=			False
       snake_case__    :     List[Any]   		=			False
       snake_case__    :     Dict   		=			False
       snake_case__    :     List[str]   		=			False
       snake_case__    :     Dict   		=			False




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       int				   =				TFResNetModelTester(self					)
            __lowerCamelCase						:       List[str]				   =				ConfigTester(self	,    config_class=_lowercase	,    has_text_modality=_lowercase					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            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      : Tuple					):


            """simple docstring"""







            return




       @unittest.skip(reason="""ResNet does not use inputs_embeds"""					)
       def 					a_					(					self      : Dict					):


            """simple docstring"""







            pass




       @unittest.skip(reason="""ResNet does not support input and output embeddings"""					)
       def 					a_					(					self      : Any					):


            """simple docstring"""







            pass




       def 					a_					(					self      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       List[str]				   =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 __lowerCamelCase						:       int				   =				["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]	,    _lowercase					)




       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_lowercase					)




       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            def check_hidden_states_output(A__      : Any	,    A__      : List[str]	,    A__      : List[str]					):
                 __lowerCamelCase						:       List[str]				   =				model_class(_lowercase					)
                 __lowerCamelCase						:       Any				   =				model(**self._prepare_for_class(_lowercase	,    _lowercase					)					)

                 __lowerCamelCase						:       List[str]				   =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 __lowerCamelCase						:       List[Any]				   =				self.model_tester.num_stages
                 self.assertEqual(len(_lowercase					)	,    expected_num_stages + 1					)

                 # ResNet'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						:       List[str]				   =				self.model_tester.prepare_config_and_inputs_for_common()
            __lowerCamelCase						:       int				   =				["""basic""", """bottleneck"""]
            for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                      __lowerCamelCase						:       List[str]				   =				layer_type
                      __lowerCamelCase						:       List[str]				   =				True
                      check_hidden_states_output(_lowercase	,    _lowercase	,    _lowercase					)

                      # check that output_hidden_states also work using config
                      del inputs_dict["output_hidden_states"]
                      __lowerCamelCase						:       Optional[Any]				   =				True

                      check_hidden_states_output(_lowercase	,    _lowercase	,    _lowercase					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_lowercase					)




       @slow
       def 					a_					(					self      : int					):


            """simple docstring"""







            for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __lowerCamelCase						:       List[Any]				   =				TFResNetModel.from_pretrained(_lowercase					)
                 self.assertIsNotNone(_lowercase					)

def     __lowercase  ()   ->     Optional[int]:


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







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




       @cached_property
       def 					a_					(					self      : List[Any]					):


            """simple docstring"""







            return (
                AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
                if is_vision_available()
                else None
            )




       @slow
       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

            __lowerCamelCase						:       Dict				   =				self.default_image_processor
            __lowerCamelCase						:       str				   =				prepare_img()
            __lowerCamelCase						:       str				   =				image_processor(images=_lowercase	,    return_tensors="""tf"""					)

            # forward pass
            __lowerCamelCase						:       Optional[Any]				   =				model(**_lowercase					)

            # verify the logits
            __lowerCamelCase						:       Union[str, Any]				   =				tf.TensorShape((1, 1000)					)
            self.assertEqual(outputs.logits.shape	,    _lowercase					)

            __lowerCamelCase						:       List[Any]				   =				tf.constant([-11.1069, -9.7877, -8.3777]					)

            self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()	,    _lowercase	,    atol=1e-4					)					)











'''simple docstring'''

import functools
import operator

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


UpperCAmelCase__						:Optional[int]          =			logging.get_logger(__name__)

UpperCAmelCase__						:List[Any]          =			{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     Dict   		=			'sew-d'




       def __init__(					self      : Tuple	,    A__      : Optional[int]=32	,    A__      : Optional[int]=768	,    A__      : Any=12	,    A__      : List[str]=12	,    A__      : List[Any]=3072	,    A__      : str=2	,    A__      : Dict=512	,    A__      : Optional[Any]=256	,    A__      : Optional[Any]=True	,    A__      : Any=True	,    A__      : List[str]=("p2c", "c2p")	,    A__      : List[Any]="layer_norm"	,    A__      : Union[str, Any]="gelu_python"	,    A__      : int=0.1	,    A__      : Dict=0.1	,    A__      : int=0.1	,    A__      : Dict=0.0	,    A__      : Optional[Any]=0.1	,    A__      : Dict=0.02	,    A__      : Dict=1e-7	,    A__      : List[Any]=1e-5	,    A__      : Any="group"	,    A__      : Any="gelu"	,    A__      : Dict=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)	,    A__      : Dict=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)	,    A__      : str=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)	,    A__      : Optional[Any]=False	,    A__      : Any=128	,    A__      : Optional[Any]=16	,    A__      : Union[str, Any]=True	,    A__      : Any=0.05	,    A__      : List[str]=10	,    A__      : Union[str, Any]=2	,    A__      : Dict=0.0	,    A__      : str=10	,    A__      : Tuple=0	,    A__      : Any="mean"	,    A__      : Optional[int]=False	,    A__      : int=False	,    A__      : List[str]=256	,    A__      : Union[str, Any]=0	,    A__      : int=1	,    A__      : Optional[Any]=2	,    **A__      : List[Any]	,    ):


            """simple docstring"""







            super().__init__(**A__	,    pad_token_id=A__	,    bos_token_id=A__	,    eos_token_id=A__					)
            __lowerCamelCase						:       List[str]				   =				hidden_size
            __lowerCamelCase						:       Tuple				   =				feat_extract_norm
            __lowerCamelCase						:       Tuple				   =				feat_extract_activation
            __lowerCamelCase						:       List[Any]				   =				list(A__					)
            __lowerCamelCase						:       int				   =				list(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				list(A__					)
            __lowerCamelCase						:       Tuple				   =				conv_bias
            __lowerCamelCase						:       List[str]				   =				num_conv_pos_embeddings
            __lowerCamelCase						:       Tuple				   =				num_conv_pos_embedding_groups
            __lowerCamelCase						:       int				   =				len(self.conv_dim					)
            __lowerCamelCase						:       Optional[int]				   =				num_hidden_layers
            __lowerCamelCase						:       Dict				   =				intermediate_size
            __lowerCamelCase						:       Optional[int]				   =				squeeze_factor
            __lowerCamelCase						:       Union[str, Any]				   =				max_position_embeddings
            __lowerCamelCase						:       int				   =				position_buckets
            __lowerCamelCase						:       Tuple				   =				share_att_key
            __lowerCamelCase						:       Any				   =				relative_attention
            __lowerCamelCase						:       Any				   =				norm_rel_ebd
            __lowerCamelCase						:       Dict				   =				list(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				hidden_act
            __lowerCamelCase						:       List[str]				   =				num_attention_heads
            __lowerCamelCase						:       List[str]				   =				hidden_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				attention_dropout
            __lowerCamelCase						:       Tuple				   =				activation_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				feat_proj_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				final_dropout
            __lowerCamelCase						:       List[str]				   =				layer_norm_eps
            __lowerCamelCase						:       Tuple				   =				feature_layer_norm_eps
            __lowerCamelCase						:       Union[str, Any]				   =				initializer_range
            __lowerCamelCase						:       List[str]				   =				vocab_size

            if (
                (len(self.conv_stride					) != self.num_feat_extract_layers)
                or (len(self.conv_kernel					) != self.num_feat_extract_layers)
                or (len(self.conv_dim					) != self.num_feat_extract_layers)
            ):
                 raise ValueError(
                     """Configuration for convolutional layers is incorrect."""
                     """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
                     f"but is `len(config.conv_dim) = {len(self.conv_dim					)}`, `len(config.conv_stride)"
                     f"= {len(self.conv_stride					)}`, `len(config.conv_kernel) = {len(self.conv_kernel					)}`."					)

            # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
            __lowerCamelCase						:       Any				   =				apply_spec_augment
            __lowerCamelCase						:       str				   =				mask_time_prob
            __lowerCamelCase						:       Tuple				   =				mask_time_length
            __lowerCamelCase						:       Optional[int]				   =				mask_time_min_masks
            __lowerCamelCase						:       Dict				   =				mask_feature_prob
            __lowerCamelCase						:       Optional[Any]				   =				mask_feature_length
            __lowerCamelCase						:       str				   =				mask_feature_min_masks

            # ctc loss
            __lowerCamelCase						:       Any				   =				ctc_loss_reduction
            __lowerCamelCase						:       str				   =				ctc_zero_infinity

            # sequence classification
            __lowerCamelCase						:       Dict				   =				use_weighted_layer_sum
            __lowerCamelCase						:       List[Any]				   =				classifier_proj_size




       @property
       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            return functools.reduce(operator.mul	,    self.conv_stride	,    1					)



