

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__							=				logging.get_logger(__name__)

# General docstring
A__							=				"ResNetConfig"

# Base docstring
A__							=				"microsoft/resnet-50"
A__							=				[1, 2048, 7, 7]

# Image classification docstring
A__							=				"microsoft/resnet-50"
A__							=				"tiger cat"

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

class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			int	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int = 3	,			__UpperCamelCase:			int = 1	,			__UpperCamelCase:			str = "relu"	,			**__UpperCamelCase:			Optional[int]   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     kernel_size // 2
						__magic_name__				=     tf.keras.layers.ConvaD(
						    __UpperCamelCase	,			kernel_size=__UpperCamelCase	,			strides=__UpperCamelCase	,			padding='valid'	,			use_bias=__UpperCamelCase	,			name='convolution'   )
						# Use same default momentum and epsilon as PyTorch equivalent
						__magic_name__				=     tf.keras.layers.BatchNormalization(epsilon=1E-5	,			momentum=0.9	,			name='normalization'   )
						__magic_name__				=     ACTaFN[activation] if activation is not None else tf.keras.layers.Activation('linear'   )







	def 						_SCREAMING_SNAKE_CASE				( self:			Dict	,			__UpperCamelCase:			tf.Tensor   ):

						'''simple docstring'''





						__magic_name__				=     __magic_name__				=     (self.pad_value, self.pad_value)
						__magic_name__				=     tf.pad(__UpperCamelCase	,			[(0, 0), height_pad, width_pad, (0, 0)]   )
						__magic_name__				=     self.conv(__UpperCamelCase   )
						return hidden_state







	def 						_SCREAMING_SNAKE_CASE				( self:			int	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False   ):

						'''simple docstring'''





						__magic_name__				=     self.convolution(__UpperCamelCase   )
						__magic_name__				=     self.normalization(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.activation(__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			Optional[Any]	,			__UpperCamelCase:			ResNetConfig	,			**__UpperCamelCase:			Union[str, Any]   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     TFResNetConvLayer(
						    config.embedding_size	,			kernel_size=7	,			stride=2	,			activation=config.hidden_act	,			name='embedder'	,			)
						__magic_name__				=     tf.keras.layers.MaxPoolaD(pool_size=3	,			strides=2	,			padding='valid'	,			name='pooler'   )
						__magic_name__				=     config.num_channels







	def 						_SCREAMING_SNAKE_CASE				( self:			Dict	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False   ):

						'''simple docstring'''





						__magic_name__,						__magic_name__,						__magic_name__,						__magic_name__				=     shape_list(__UpperCamelCase   )
						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.'   )
						__magic_name__				=     pixel_values
						__magic_name__				=     self.embedder(__UpperCamelCase   )
						__magic_name__				=     tf.pad(__UpperCamelCase	,			[[0, 0], [1, 1], [1, 1], [0, 0]]   )
						__magic_name__				=     self.pooler(__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			Union[str, Any]	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int = 2	,			**__UpperCamelCase:			List[Any]   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     tf.keras.layers.ConvaD(
						    __UpperCamelCase	,			kernel_size=1	,			strides=__UpperCamelCase	,			use_bias=__UpperCamelCase	,			name='convolution'   )
						# Use same default momentum and epsilon as PyTorch equivalent
						__magic_name__				=     tf.keras.layers.BatchNormalization(epsilon=1E-5	,			momentum=0.9	,			name='normalization'   )







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

						'''simple docstring'''





						__magic_name__				=     x
						__magic_name__				=     self.convolution(__UpperCamelCase   )
						__magic_name__				=     self.normalization(__UpperCamelCase	,			training=__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			Union[str, Any]	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int = 1	,			__UpperCamelCase:			str = "relu"	,			**__UpperCamelCase:			Optional[int]   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     in_channels != out_channels or stride != 1
						__magic_name__				=     TFResNetConvLayer(__UpperCamelCase	,			stride=__UpperCamelCase	,			name='layer.0'   )
						__magic_name__				=     TFResNetConvLayer(__UpperCamelCase	,			activation=__UpperCamelCase	,			name='layer.1'   )
						__magic_name__				=     (
						    TFResNetShortCut(__UpperCamelCase	,			stride=__UpperCamelCase	,			name='shortcut'   )
						    if should_apply_shortcut
						    else tf.keras.layers.Activation('linear'	,			name='shortcut'   )
						)
						__magic_name__				=     ACTaFN[activation]







	def 						_SCREAMING_SNAKE_CASE				( self:			Any	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False   ):

						'''simple docstring'''





						__magic_name__				=     hidden_state
						__magic_name__				=     self.conva(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.conva(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.shortcut(__UpperCamelCase	,			training=__UpperCamelCase   )
						hidden_state += residual
						__magic_name__				=     self.activation(__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			Union[str, Any]	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int = 1	,			__UpperCamelCase:			str = "relu"	,			__UpperCamelCase:			int = 4	,			**__UpperCamelCase:			Union[str, Any]	,			):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     in_channels != out_channels or stride != 1
						__magic_name__				=     out_channels // reduction
						__magic_name__				=     TFResNetConvLayer(__UpperCamelCase	,			kernel_size=1	,			name='layer.0'   )
						__magic_name__				=     TFResNetConvLayer(__UpperCamelCase	,			stride=__UpperCamelCase	,			name='layer.1'   )
						__magic_name__				=     TFResNetConvLayer(__UpperCamelCase	,			kernel_size=1	,			activation=__UpperCamelCase	,			name='layer.2'   )
						__magic_name__				=     (
						    TFResNetShortCut(__UpperCamelCase	,			stride=__UpperCamelCase	,			name='shortcut'   )
						    if should_apply_shortcut
						    else tf.keras.layers.Activation('linear'	,			name='shortcut'   )
						)
						__magic_name__				=     ACTaFN[activation]







	def 						_SCREAMING_SNAKE_CASE				( self:			Optional[Any]	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False   ):

						'''simple docstring'''





						__magic_name__				=     hidden_state
						__magic_name__				=     self.conva(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.conva(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.conva(__UpperCamelCase	,			training=__UpperCamelCase   )
						__magic_name__				=     self.shortcut(__UpperCamelCase	,			training=__UpperCamelCase   )
						hidden_state += residual
						__magic_name__				=     self.activation(__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			int	,			__UpperCamelCase:			ResNetConfig	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int	,			__UpperCamelCase:			int = 2	,			__UpperCamelCase:			int = 2	,			**__UpperCamelCase:			List[str]   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )

						__magic_name__				=     TFResNetBottleNeckLayer if config.layer_type == 'bottleneck' else TFResNetBasicLayer

						__magic_name__				=     [layer(__UpperCamelCase	,			__UpperCamelCase	,			stride=__UpperCamelCase	,			activation=config.hidden_act	,			name='layers.0'   )]
						layers += [
						    layer(__UpperCamelCase	,			__UpperCamelCase	,			activation=config.hidden_act	,			name=F'layers.{i + 1}'   )
						    for i in range(depth - 1   )
						]
						__magic_name__				=     layers







	def 						_SCREAMING_SNAKE_CASE				( self:			int	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False   ):

						'''simple docstring'''





						for layer in self.stage_layers:
											__magic_name__				=     layer(__UpperCamelCase	,			training=__UpperCamelCase   )
						return hidden_state




class 					__UpperCamelCase					(       tf.keras.layers.Layer      ):







	def __init__( self:			int	,			__UpperCamelCase:			ResNetConfig	,			**__UpperCamelCase:			Any   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
						__magic_name__				=     [
						    TFResNetStage(
						        __UpperCamelCase	,			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(__UpperCamelCase	,			__UpperCamelCase	,			__UpperCamelCase	,			depth=__UpperCamelCase	,			name=F'stages.{i + 1}'   )   )







	def 						_SCREAMING_SNAKE_CASE				( self:			List[str]	,			__UpperCamelCase:			tf.Tensor	,			__UpperCamelCase:			bool = False	,			__UpperCamelCase:			bool = True	,			__UpperCamelCase:			bool = False	,			):

						'''simple docstring'''





						__magic_name__				=     () if output_hidden_states else None

						for stage_module in self.stages:
											if output_hidden_states:
																__magic_name__				=     hidden_states + (hidden_state,)

											__magic_name__				=     stage_module(__UpperCamelCase	,			training=__UpperCamelCase   )

						if output_hidden_states:
											__magic_name__				=     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=__UpperCamelCase	,			hidden_states=__UpperCamelCase   )




class 					__UpperCamelCase					(       SCREAMING_SNAKE_CASE      ):
	_lowercase	: Optional[int]												=	ResNetConfig
	_lowercase	: int												=	"resnet"
	_lowercase	: Union[str, Any]												=	"pixel_values"







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

						'''simple docstring'''





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




A__							=				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__							=				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 					__UpperCamelCase					(       tf.keras.layers.Layer      ):
	_lowercase	: int												=	ResNetConfig







	def __init__( self:			Dict	,			__UpperCamelCase:			ResNetConfig	,			**__UpperCamelCase:			str   ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase   )
						__magic_name__				=     config
						__magic_name__				=     TFResNetEmbeddings(__UpperCamelCase	,			name='embedder'   )
						__magic_name__				=     TFResNetEncoder(__UpperCamelCase	,			name='encoder'   )
						__magic_name__				=     tf.keras.layers.GlobalAveragePoolingaD(keepdims=__UpperCamelCase   )







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

						'''simple docstring'''





						__magic_name__				=     (
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						__magic_name__				=     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)
						__magic_name__				=     tf.transpose(__UpperCamelCase	,			perm=[0, 2, 3, 1]   )
						__magic_name__				=     self.embedder(__UpperCamelCase	,			training=__UpperCamelCase   )

						__magic_name__				=     self.encoder(
						    __UpperCamelCase	,			output_hidden_states=__UpperCamelCase	,			return_dict=__UpperCamelCase	,			training=__UpperCamelCase   )

						__magic_name__				=     encoder_outputs[0]

						__magic_name__				=     self.pooler(__UpperCamelCase   )

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

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

						__magic_name__				=     hidden_states if output_hidden_states else None

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




@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."	,    SCREAMING_SNAKE_CASE	,    )
class 					__UpperCamelCase					(       SCREAMING_SNAKE_CASE      ):







	def __init__( self:			Optional[int]	,			__UpperCamelCase:			ResNetConfig	,			**__UpperCamelCase:			Optional[int]   ):

						'''simple docstring'''





						super().__init__(__UpperCamelCase	,			**__UpperCamelCase   )
						__magic_name__				=     TFResNetMainLayer(config=__UpperCamelCase	,			name='resnet'   )







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

						'''simple docstring'''





						__magic_name__				=     (
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						__magic_name__				=     return_dict if return_dict is not None else self.config.use_return_dict

						__magic_name__				=     self.resnet(
						    pixel_values=__UpperCamelCase	,			output_hidden_states=__UpperCamelCase	,			return_dict=__UpperCamelCase	,			training=__UpperCamelCase	,			)
						return resnet_outputs




@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "	,    SCREAMING_SNAKE_CASE	,    )
class 					__UpperCamelCase					(       SCREAMING_SNAKE_CASE	,    SCREAMING_SNAKE_CASE      ):







	def __init__( self:			Any	,			__UpperCamelCase:			ResNetConfig	,			**__UpperCamelCase:			Optional[int]   ):

						'''simple docstring'''





						super().__init__(__UpperCamelCase	,			**__UpperCamelCase   )
						__magic_name__				=     config.num_labels
						__magic_name__				=     TFResNetMainLayer(__UpperCamelCase	,			name='resnet'   )
						# classification head
						__magic_name__				=     (
						    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 						_SCREAMING_SNAKE_CASE				( self:			Dict	,			__UpperCamelCase:			tf.Tensor   ):

						'''simple docstring'''





						__magic_name__				=     tf.keras.layers.Flatten()(__UpperCamelCase   )
						__magic_name__				=     self.classifier_layer(__UpperCamelCase   )
						return logits







	@add_start_docstrings_to_model_forward(__UpperCamelCase   )
	@add_code_sample_docstrings(
	    checkpoint=_IMAGE_CLASS_CHECKPOINT	,			output_type=__UpperCamelCase	,			config_class=_CONFIG_FOR_DOC	,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT	,			)
	@unpack_inputs
	def 						_SCREAMING_SNAKE_CASE				( self:			str	,			__UpperCamelCase:			tf.Tensor = None	,			__UpperCamelCase:			tf.Tensor = None	,			__UpperCamelCase:			bool = None	,			__UpperCamelCase:			bool = None	,			__UpperCamelCase:			bool = False	,			):

						'''simple docstring'''





						__magic_name__				=     return_dict if return_dict is not None else self.config.use_return_dict

						__magic_name__				=     self.resnet(
						    __UpperCamelCase	,			output_hidden_states=__UpperCamelCase	,			return_dict=__UpperCamelCase	,			training=__UpperCamelCase   )

						__magic_name__				=     outputs.pooler_output if return_dict else outputs[1]

						__magic_name__				=     self.classifier(__UpperCamelCase   )

						__magic_name__				=     None if labels is None else self.hf_compute_loss(__UpperCamelCase	,			__UpperCamelCase   )

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

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







from hashlib import mda, shaaaa

A__							=				(shaaaa, mda)

class 					__UpperCamelCase					:







	def __init__( self:			Optional[int]	,			__UpperCamelCase:			int = 8   ):

						'''simple docstring'''





						__magic_name__				=     0b0
						__magic_name__				=     size







	def 						_SCREAMING_SNAKE_CASE				( self:			Tuple	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     self.hash_(__UpperCamelCase   )
						self.bitarray |= h







	def 						_SCREAMING_SNAKE_CASE				( self:			List[str]	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     self.hash_(__UpperCamelCase   )
						return (h & self.bitarray) == h







	def __contains__( self:			Optional[int]	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						return self.exists(__UpperCamelCase   )







	def 						_SCREAMING_SNAKE_CASE				( self:			int	,			__UpperCamelCase:			int   ):

						'''simple docstring'''





						__magic_name__				=     bin(__UpperCamelCase   )[2:]
						return res.zfill(self.size   )







	@property
	def 						_SCREAMING_SNAKE_CASE				( self:			str   ):

						'''simple docstring'''





						return self.format_bin(self.bitarray   )







	def 						_SCREAMING_SNAKE_CASE				( self:			str	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     0b0
						for func in HASH_FUNCTIONS:
											__magic_name__				=     (
											    int.from_bytes(func(value.encode()   ).digest()	,			'little'   ) % self.size
											)
											res |= 2**position
						return res







	def 						_SCREAMING_SNAKE_CASE				( self:			Dict	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						return self.format_bin(self.hash_(__UpperCamelCase   )   )







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

						'''simple docstring'''





						__magic_name__				=     bin(self.bitarray   ).count('1'   )
						return (n_ones / self.size) ** len(__UpperCamelCase   )




