
'''simple docstring'''
from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


A__ :		Dict					=logging.get_logger(__name__)

# General docstring
A__ :		Union[str, Any]					='ResNetConfig'

# Base docstring
A__ :		Optional[int]					='microsoft/resnet-50'
A__ :		List[Any]					=[1, 2_048, 7, 7]

# Image classification docstring
A__ :		Any					='microsoft/resnet-50'
A__ :		List[str]					='tiger cat'

A__ :		int					=[
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     Tuple					, lowerCamelCase      :     int					, lowerCamelCase      :     int = 3					, lowerCamelCase      :     int = 1					, lowerCamelCase      :     str = "relu"					, **lowerCamelCase      :     Optional[Any]							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  Optional[int]       				=		kernel_size // 2
   __A		:  List[str]       				=		tf.keras.layers.ConvaD(
       _lowerCAmelCase					, kernel_size=_lowerCAmelCase					, strides=_lowerCAmelCase					, padding="""valid"""					, use_bias=_lowerCAmelCase					, name="""convolution"""							)
   # Use same default momentum and epsilon as PyTorch equivalent
   __A		:  Optional[int]       				=		tf.keras.layers.BatchNormalization(epsilon=1e-5					, momentum=0.9					, name="""normalization"""							)
   __A		:  List[str]       				=		ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("""linear"""							)
 def 		lowercase_( self      :     Union[str, Any]					, lowerCamelCase      :     tf.Tensor							):



   """simple docstring"""





   __A		:  str       				=		(self.pad_value, self.pad_value)
   __A		:  int       				=		tf.pad(_lowerCAmelCase					, [(0, 0), height_pad, width_pad, (0, 0)]							)
   __A		:  Tuple       				=		self.conv(_lowerCAmelCase							)
   return hidden_state






 def 		lowercase_( self      :     List[str]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   __A		:  List[str]       				=		self.convolution(_lowerCAmelCase							)
   __A		:  Any       				=		self.normalization(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  Optional[int]       				=		self.activation(_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     str					, lowerCamelCase      :     ResNetConfig					, **lowerCamelCase      :     int							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  Any       				=		TFResNetConvLayer(
       config.embedding_size					, kernel_size=7					, stride=2					, activation=config.hidden_act					, name="""embedder"""					, )
   __A		:  Optional[Any]       				=		tf.keras.layers.MaxPoolaD(pool_size=3					, strides=2					, padding="""valid"""					, name="""pooler"""							)
   __A		:  Tuple       				=		config.num_channels






 def 		lowercase_( self      :     List[str]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   __A				,       __A				,       __A				,       __A		:  Tuple       				=		shape_list(_lowerCAmelCase							)
   if tf.executing_eagerly() and num_channels != self.num_channels:
     raise ValueError(
         """Make sure that the channel dimension of the pixel values match with the one set in the configuration."""							)
   __A		:  Dict       				=		pixel_values
   __A		:  Dict       				=		self.embedder(_lowerCAmelCase							)
   __A		:  int       				=		tf.pad(_lowerCAmelCase					, [[0, 0], [1, 1], [1, 1], [0, 0]]							)
   __A		:  Dict       				=		self.pooler(_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     List[Any]					, lowerCamelCase      :     int					, lowerCamelCase      :     int = 2					, **lowerCamelCase      :     Dict							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  str       				=		tf.keras.layers.ConvaD(
       _lowerCAmelCase					, kernel_size=1					, strides=_lowerCAmelCase					, use_bias=_lowerCAmelCase					, name="""convolution"""							)
   # Use same default momentum and epsilon as PyTorch equivalent
   __A		:  Any       				=		tf.keras.layers.BatchNormalization(epsilon=1e-5					, momentum=0.9					, name="""normalization"""							)






 def 		lowercase_( self      :     List[str]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   __A		:  Tuple       				=		x
   __A		:  str       				=		self.convolution(_lowerCAmelCase							)
   __A		:  Optional[Any]       				=		self.normalization(_lowerCAmelCase					, training=_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     Tuple					, lowerCamelCase      :     int					, lowerCamelCase      :     int					, lowerCamelCase      :     int = 1					, lowerCamelCase      :     str = "relu"					, **lowerCamelCase      :     List[str]							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  Optional[int]       				=		in_channels != out_channels or stride != 1
   __A		:  Optional[Any]       				=		TFResNetConvLayer(_lowerCAmelCase					, stride=_lowerCAmelCase					, name="""layer.0"""							)
   __A		:  int       				=		TFResNetConvLayer(_lowerCAmelCase					, activation=_lowerCAmelCase					, name="""layer.1"""							)
   __A		:  Any       				=		(
       TFResNetShortCut(_lowerCAmelCase					, stride=_lowerCAmelCase					, name="""shortcut"""							)
       if should_apply_shortcut
       else tf.keras.layers.Activation("""linear"""					, name="""shortcut"""							)
   )
   __A		:  List[Any]       				=		ACTaFN[activation]






 def 		lowercase_( self      :     Optional[int]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   __A		:  str       				=		hidden_state
   __A		:  Any       				=		self.conva(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  List[Any]       				=		self.conva(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  Any       				=		self.shortcut(_lowerCAmelCase					, training=_lowerCAmelCase							)
   hidden_state += residual
   __A		:  Tuple       				=		self.activation(_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     Union[str, Any]					, lowerCamelCase      :     int					, lowerCamelCase      :     int					, lowerCamelCase      :     int = 1					, lowerCamelCase      :     str = "relu"					, lowerCamelCase      :     int = 4					, **lowerCamelCase      :     Optional[Any]					, ):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  Optional[int]       				=		in_channels != out_channels or stride != 1
   __A		:  Union[str, Any]       				=		out_channels // reduction
   __A		:  str       				=		TFResNetConvLayer(_lowerCAmelCase					, kernel_size=1					, name="""layer.0"""							)
   __A		:  Tuple       				=		TFResNetConvLayer(_lowerCAmelCase					, stride=_lowerCAmelCase					, name="""layer.1"""							)
   __A		:  List[str]       				=		TFResNetConvLayer(_lowerCAmelCase					, kernel_size=1					, activation=_lowerCAmelCase					, name="""layer.2"""							)
   __A		:  Union[str, Any]       				=		(
       TFResNetShortCut(_lowerCAmelCase					, stride=_lowerCAmelCase					, name="""shortcut"""							)
       if should_apply_shortcut
       else tf.keras.layers.Activation("""linear"""					, name="""shortcut"""							)
   )
   __A		:  Optional[Any]       				=		ACTaFN[activation]






 def 		lowercase_( self      :     Optional[int]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   __A		:  Tuple       				=		hidden_state
   __A		:  Dict       				=		self.conva(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  List[Any]       				=		self.conva(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  str       				=		self.conva(_lowerCAmelCase					, training=_lowerCAmelCase							)
   __A		:  Any       				=		self.shortcut(_lowerCAmelCase					, training=_lowerCAmelCase							)
   hidden_state += residual
   __A		:  Any       				=		self.activation(_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     Optional[int]					, lowerCamelCase      :     ResNetConfig					, lowerCamelCase      :     int					, lowerCamelCase      :     int					, lowerCamelCase      :     int = 2					, lowerCamelCase      :     int = 2					, **lowerCamelCase      :     List[str]							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)

   __A		:  Dict       				=		TFResNetBottleNeckLayer if config.layer_type == """bottleneck""" else TFResNetBasicLayer

   __A		:  List[Any]       				=		[layer(_lowerCAmelCase					, _lowerCAmelCase					, stride=_lowerCAmelCase					, activation=config.hidden_act					, name="""layers.0"""							)]
   layers += [
       layer(_lowerCAmelCase					, _lowerCAmelCase					, activation=config.hidden_act					, name=f"layers.{i + 1}"							)
       for i in range(depth - 1							)
   ]
   __A		:  List[str]       				=		layers






 def 		lowercase_( self      :     Union[str, Any]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False							):



   """simple docstring"""





   for layer in self.stage_layers:
     __A		:  Optional[int]       				=		layer(_lowerCAmelCase					, training=_lowerCAmelCase							)
   return hidden_state







class 			__A					(			tf.keras.layers.Layer      ):
 def __init__( self      :     Tuple					, lowerCamelCase      :     ResNetConfig					, **lowerCamelCase      :     Optional[Any]							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
   __A		:  Tuple       				=		[
       TFResNetStage(
           _lowerCAmelCase					, config.embedding_size					, config.hidden_sizes[0]					, stride=2 if config.downsample_in_first_stage else 1					, depth=config.depths[0]					, name="""stages.0"""					, )
   ]
   for i, (in_channels, out_channels, depth) in enumerate(
       zip(config.hidden_sizes					, config.hidden_sizes[1:]					, config.depths[1:]							)							):
     self.stages.append(TFResNetStage(_lowerCAmelCase					, _lowerCAmelCase					, _lowerCAmelCase					, depth=_lowerCAmelCase					, name=f"stages.{i + 1}"							)							)






 def 		lowercase_( self      :     Union[str, Any]					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     bool = False					, lowerCamelCase      :     bool = True					, lowerCamelCase      :     bool = False					, ):



   """simple docstring"""





   __A		:  int       				=		() if output_hidden_states else None

   for stage_module in self.stages:
     if output_hidden_states:
       __A		:  List[Any]       				=		hidden_states + (hidden_state,)

     __A		:  Union[str, Any]       				=		stage_module(_lowerCAmelCase					, training=_lowerCAmelCase							)

   if output_hidden_states:
     __A		:  Optional[int]       				=		hidden_states + (hidden_state,)

   if not return_dict:
     return tuple(v for v in [hidden_state, hidden_states] if v is not None							)

   return TFBaseModelOutputWithNoAttention(last_hidden_state=_lowerCAmelCase					, hidden_states=_lowerCAmelCase							)







class 			__A					(			A__      ):
 lowerCamelCase												=ResNetConfig
 lowerCamelCase												='''resnet'''
 lowerCamelCase												='''pixel_values'''
 @property
 def 		lowercase_( self      :     Dict							):



   """simple docstring"""





   return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)					, dtype=tf.floataa							)}

A__ :		Any					=R'\n    This model is a TensorFlow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n'


A__ :		Tuple					=R'\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'







@keras_serializable
class 			__A					(			tf.keras.layers.Layer      ):
 lowerCamelCase												=ResNetConfig
 def __init__( self      :     Dict					, lowerCamelCase      :     ResNetConfig					, **lowerCamelCase      :     Union[str, Any]							):



   """simple docstring"""





   super().__init__(**_lowerCAmelCase							)
   __A		:  List[str]       				=		config
   __A		:  Any       				=		TFResNetEmbeddings(_lowerCAmelCase					, name="""embedder"""							)
   __A		:  Optional[int]       				=		TFResNetEncoder(_lowerCAmelCase					, name="""encoder"""							)
   __A		:  Union[str, Any]       				=		tf.keras.layers.GlobalAveragePoolingaD(keepdims=_lowerCAmelCase							)






 @unpack_inputs
 def 		lowercase_( self      :     Dict					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     Optional[bool] = None					, lowerCamelCase      :     Optional[bool] = None					, lowerCamelCase      :     bool = False					, ):



   """simple docstring"""





   __A		:  Tuple       				=		(
       output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
   )
   __A		:  Union[str, Any]       				=		return_dict if return_dict is not None else self.config.use_return_dict

   # TF 2.0 image layers can't use NCHW format when running on CPU.
   # We transpose to NHWC format and then transpose back after the full forward pass.
   # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
   __A		:  Dict       				=		tf.transpose(_lowerCAmelCase					, perm=[0, 2, 3, 1]							)
   __A		:  List[str]       				=		self.embedder(_lowerCAmelCase					, training=_lowerCAmelCase							)

   __A		:  str       				=		self.encoder(
       _lowerCAmelCase					, output_hidden_states=_lowerCAmelCase					, return_dict=_lowerCAmelCase					, training=_lowerCAmelCase							)

   __A		:  Optional[int]       				=		encoder_outputs[0]

   __A		:  Union[str, Any]       				=		self.pooler(_lowerCAmelCase							)

   # Transpose all the outputs to the NCHW format
   # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
   __A		:  Tuple       				=		tf.transpose(_lowerCAmelCase					, (0, 3, 1, 2)							)
   __A		:  List[Any]       				=		tf.transpose(_lowerCAmelCase					, (0, 3, 1, 2)							)
   __A		:  List[Any]       				=		()
   for hidden_state in encoder_outputs[1:]:
     __A		:  Optional[int]       				=		hidden_states + tuple(tf.transpose(_lowerCAmelCase					, (0, 3, 1, 2)							) for h in hidden_state							)

   if not return_dict:
     return (last_hidden_state, pooled_output) + hidden_states

   __A		:  str       				=		hidden_states if output_hidden_states else None

   return TFBaseModelOutputWithPoolingAndNoAttention(
       last_hidden_state=_lowerCAmelCase					, pooler_output=_lowerCAmelCase					, hidden_states=_lowerCAmelCase					, )







@add_start_docstrings(
    '''The bare ResNet model outputting raw features without any specific head on top.'''     ,    A__     ,    )
class 			__A					(			A__      ):
 def __init__( self      :     Optional[Any]					, lowerCamelCase      :     ResNetConfig					, **lowerCamelCase      :     Dict							):



   """simple docstring"""





   super().__init__(_lowerCAmelCase					, **_lowerCAmelCase							)
   __A		:  Dict       				=		TFResNetMainLayer(config=_lowerCAmelCase					, name="""resnet"""							)






 @add_start_docstrings_to_model_forward(_lowerCAmelCase							)
 @add_code_sample_docstrings(
     checkpoint=_CHECKPOINT_FOR_DOC					, output_type=_lowerCAmelCase					, config_class=_CONFIG_FOR_DOC					, modality="""vision"""					, expected_output=_EXPECTED_OUTPUT_SHAPE					, )
 @unpack_inputs
 def 		lowercase_( self      :     Any					, lowerCamelCase      :     tf.Tensor					, lowerCamelCase      :     Optional[bool] = None					, lowerCamelCase      :     Optional[bool] = None					, lowerCamelCase      :     bool = False					, ):



   """simple docstring"""





   __A		:  Tuple       				=		(
       output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
   )
   __A		:  Optional[Any]       				=		return_dict if return_dict is not None else self.config.use_return_dict

   __A		:  Dict       				=		self.resnet(
       pixel_values=_lowerCAmelCase					, output_hidden_states=_lowerCAmelCase					, return_dict=_lowerCAmelCase					, training=_lowerCAmelCase					, )
   return resnet_outputs







@add_start_docstrings(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''     ,    A__     ,    )
class 			__A					(			A__     ,    A__      ):
 def __init__( self      :     Optional[Any]					, lowerCamelCase      :     ResNetConfig					, **lowerCamelCase      :     int							):



   """simple docstring"""





   super().__init__(_lowerCAmelCase					, **_lowerCAmelCase							)
   __A		:  Tuple       				=		config.num_labels
   __A		:  Tuple       				=		TFResNetMainLayer(_lowerCAmelCase					, name="""resnet"""							)
   # classification head
   __A		:  str       				=		(
       tf.keras.layers.Dense(config.num_labels					, name="""classifier.1"""							)
       if config.num_labels > 0
       else tf.keras.layers.Activation("""linear"""					, name="""classifier.1"""							)
   )
 def 		lowercase_( self      :     List[str]					, lowerCamelCase      :     tf.Tensor							):



   """simple docstring"""





   __A		:  List[str]       				=		tf.keras.layers.Flatten()(_lowerCAmelCase							)
   __A		:  str       				=		self.classifier_layer(_lowerCAmelCase							)
   return logits






 @add_start_docstrings_to_model_forward(_lowerCAmelCase							)
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT					, output_type=_lowerCAmelCase					, config_class=_CONFIG_FOR_DOC					, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT					, )
 @unpack_inputs
 def 		lowercase_( self      :     List[str]					, lowerCamelCase      :     tf.Tensor = None					, lowerCamelCase      :     tf.Tensor = None					, lowerCamelCase      :     bool = None					, lowerCamelCase      :     bool = None					, lowerCamelCase      :     bool = False					, ):



   """simple docstring"""





   __A		:  int       				=		return_dict if return_dict is not None else self.config.use_return_dict

   __A		:  Tuple       				=		self.resnet(
       _lowerCAmelCase					, output_hidden_states=_lowerCAmelCase					, return_dict=_lowerCAmelCase					, training=_lowerCAmelCase							)

   __A		:  Any       				=		outputs.pooler_output if return_dict else outputs[1]

   __A		:  int       				=		self.classifier(_lowerCAmelCase							)

   __A		:  Union[str, Any]       				=		None if labels is None else self.hf_compute_loss(_lowerCAmelCase					, _lowerCAmelCase							)

   if not return_dict:
     __A		:  Dict       				=		(logits,) + outputs[2:]
     return (loss,) + output if loss is not None else output

   return TFImageClassifierOutputWithNoAttention(loss=_lowerCAmelCase					, logits=_lowerCAmelCase					, hidden_states=outputs.hidden_states							)










'''simple docstring'''


from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


_lowerCamelCase					:						str					     =							{
    'configuration_ernie_m': ['ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieMConfig'],
}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_lowerCamelCase					:						List[str]					     =							['ErnieMTokenizer']

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_lowerCamelCase					:						Union[str, Any]					     =							[
				    'ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST',
				    'ErnieMForMultipleChoice',
				    'ErnieMForQuestionAnswering',
				    'ErnieMForSequenceClassification',
				    'ErnieMForTokenClassification',
				    'ErnieMModel',
				    'ErnieMPreTrainedModel',
				    'ErnieMForInformationExtraction',
				]


if TYPE_CHECKING:
				from .configuration_ernie_m import ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieMConfig

				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_ernie_m import ErnieMTokenizer

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_ernie_m import (
								    ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST,
								    ErnieMForInformationExtraction,
								    ErnieMForMultipleChoice,
								    ErnieMForQuestionAnswering,
								    ErnieMForSequenceClassification,
								    ErnieMForTokenClassification,
								    ErnieMModel,
								    ErnieMPreTrainedModel,
								)


else:
				import sys

				_lowerCamelCase					:						int					     =							_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

