






"""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


UpperCamelCase =			logging.get_logger(__name__)

# General docstring
UpperCamelCase =			"""ResNetConfig"""

# Base docstring
UpperCamelCase =			"""microsoft/resnet-50"""
UpperCamelCase =			[1, 20_48, 7, 7]

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

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







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = 3 ,      UpperCAmelCase_ = 1 ,      UpperCAmelCase_ = "relu" ,      **UpperCAmelCase_)       ->					Optional[int]:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_)       ->					int:




          '''simple docstring'''




          lowercase__:				Dict			  =			(self.pad_value, self.pad_value)
          lowercase__:				List[Any]			  =			tf.pad(A_ ,      [(0, 0), height_pad, width_pad, (0, 0)])
          lowercase__:				int			  =			self.conv(A_)
          return hidden_state





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					Any:




          '''simple docstring'''




          lowercase__:				Optional[int]			  =			self.convolution(A_)
          lowercase__:				Optional[Any]			  =			self.normalization(A_ ,      training=A_)
          lowercase__:				Dict			  =			self.activation(A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      **UpperCAmelCase_)       ->					Union[str, Any]:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					Union[str, Any]:




          '''simple docstring'''




          lowercase__:				Dict			  =			shape_list(A_)
          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.")
          lowercase__:				Any			  =			pixel_values
          lowercase__:				List[str]			  =			self.embedder(A_)
          lowercase__:				int			  =			tf.pad(A_ ,      [[0, 0], [1, 1], [1, 1], [0, 0]])
          lowercase__:				Dict			  =			self.pooler(A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = 2 ,      **UpperCAmelCase_)       ->					str:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					str:




          '''simple docstring'''




          lowercase__:				str			  =			x
          lowercase__:				str			  =			self.convolution(A_)
          lowercase__:				str			  =			self.normalization(A_ ,      training=A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ = 1 ,      UpperCAmelCase_ = "relu" ,      **UpperCAmelCase_)       ->					Optional[Any]:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					List[Any]:




          '''simple docstring'''




          lowercase__:				Union[str, Any]			  =			hidden_state
          lowercase__:				Optional[int]			  =			self.conva(A_ ,      training=A_)
          lowercase__:				Union[str, Any]			  =			self.conva(A_ ,      training=A_)
          lowercase__:				List[Any]			  =			self.shortcut(A_ ,      training=A_)
          hidden_state += residual
          lowercase__:				Any			  =			self.activation(A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ = 1 ,      UpperCAmelCase_ = "relu" ,      UpperCAmelCase_ = 4 ,      **UpperCAmelCase_ ,      )       ->					Tuple:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					Optional[Any]:




          '''simple docstring'''




          lowercase__:				Optional[Any]			  =			hidden_state
          lowercase__:				Union[str, Any]			  =			self.conva(A_ ,      training=A_)
          lowercase__:				Tuple			  =			self.conva(A_ ,      training=A_)
          lowercase__:				Dict			  =			self.conva(A_ ,      training=A_)
          lowercase__:				Optional[Any]			  =			self.shortcut(A_ ,      training=A_)
          hidden_state += residual
          lowercase__:				Any			  =			self.activation(A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ = 2 ,      UpperCAmelCase_ = 2 ,      **UpperCAmelCase_)       ->					Dict:




          '''simple docstring'''




          super().__init__(**A_)

          lowercase__:				str			  =			TFResNetBottleNeckLayer if config.layer_type == "bottleneck" else TFResNetBasicLayer

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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False)       ->					str:




          '''simple docstring'''




          for layer in self.stage_layers:
                 lowercase__:				Union[str, Any]			  =			layer(A_ ,      training=A_)
          return hidden_state







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      **UpperCAmelCase_)       ->					Any:




          '''simple docstring'''




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





   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = False ,      UpperCAmelCase_ = True ,      UpperCAmelCase_ = False ,      )       ->					str:




          '''simple docstring'''




          lowercase__:				str			  =			() if output_hidden_states else None

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

                 lowercase__:				Union[str, Any]			  =			stage_module(A_ ,      training=A_)

          if output_hidden_states:
                 lowercase__:				Union[str, Any]			  =			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=A_ ,      hidden_states=A_)







class 		_a   (						lowercase_    ):





   '''simple docstring'''






   UpperCamelCase__			     =				ResNetConfig
   UpperCamelCase__			     =				"""resnet"""
   UpperCamelCase__			     =				"""pixel_values"""





   @property
   def __lowercase				(    self)       ->					Dict:




          '''simple docstring'''




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







UpperCamelCase =			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"""


UpperCamelCase =			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    ):





   '''simple docstring'''






   UpperCamelCase__			     =				ResNetConfig





   def __init__(    self ,      UpperCAmelCase_ ,      **UpperCAmelCase_)       ->					Tuple:




          '''simple docstring'''




          super().__init__(**A_)
          lowercase__:				List[Any]			  =			config
          lowercase__:				Optional[Any]			  =			TFResNetEmbeddings(A_ ,      name="embedder")
          lowercase__:				Tuple			  =			TFResNetEncoder(A_ ,      name="encoder")
          lowercase__:				Tuple			  =			tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_)





   @unpack_inputs
   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = False ,      )       ->					List[Any]:




          '''simple docstring'''




          lowercase__:				Dict			  =			(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          lowercase__:				int			  =			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)
          lowercase__:				List[Any]			  =			tf.transpose(A_ ,      perm=[0, 2, 3, 1])
          lowercase__:				Dict			  =			self.embedder(A_ ,      training=A_)

          lowercase__:				Any			  =			self.encoder(
              A_ ,      output_hidden_states=A_ ,      return_dict=A_ ,      training=A_)

          lowercase__:				Optional[int]			  =			encoder_outputs[0]

          lowercase__:				Tuple			  =			self.pooler(A_)

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

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

          lowercase__:				Any			  =			hidden_states if output_hidden_states else None

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







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





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      **UpperCAmelCase_)       ->					Tuple:




          '''simple docstring'''




          super().__init__(A_ ,      **A_)
          lowercase__:				int			  =			TFResNetMainLayer(config=A_ ,      name="resnet")





   @add_start_docstrings_to_model_forward(A_)
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC ,      output_type=A_ ,      config_class=_CONFIG_FOR_DOC ,      modality="vision" ,      expected_output=_EXPECTED_OUTPUT_SHAPE ,      )
   @unpack_inputs
   def __lowercase				(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = False ,      )       ->					List[Any]:




          '''simple docstring'''




          lowercase__:				List[Any]			  =			(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          lowercase__:				str			  =			return_dict if return_dict is not None else self.config.use_return_dict

          lowercase__:				List[Any]			  =			self.resnet(
              pixel_values=A_ ,      output_hidden_states=A_ ,      return_dict=A_ ,      training=A_ ,      )
          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    """				,     lowercase_				,     )
class 		_a   (						lowercase_				,     lowercase_    ):





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      **UpperCAmelCase_)       ->					List[str]:




          '''simple docstring'''




          super().__init__(A_ ,      **A_)
          lowercase__:				Dict			  =			config.num_labels
          lowercase__:				List[Any]			  =			TFResNetMainLayer(A_ ,      name="resnet")
          # classification head
          lowercase__:				Union[str, Any]			  =			(
              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 ,      UpperCAmelCase_)       ->					Any:




          '''simple docstring'''




          lowercase__:				Tuple			  =			tf.keras.layers.Flatten()(A_)
          lowercase__:				Dict			  =			self.classifier_layer(A_)
          return logits





   @add_start_docstrings_to_model_forward(A_)
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT ,      output_type=A_ ,      config_class=_CONFIG_FOR_DOC ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,      )
   @unpack_inputs
   def __lowercase				(    self ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = None ,      UpperCAmelCase_ = False ,      )       ->					List[str]:




          '''simple docstring'''




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

          lowercase__:				Optional[Any]			  =			self.resnet(
              A_ ,      output_hidden_states=A_ ,      return_dict=A_ ,      training=A_)

          lowercase__:				Tuple			  =			outputs.pooler_output if return_dict else outputs[1]

          lowercase__:				int			  =			self.classifier(A_)

          lowercase__:				str			  =			None if labels is None else self.hf_compute_loss(A_ ,      A_)

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

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









from hashlib import mda, shaaaa

SCREAMING_SNAKE_CASE_						=					(shaaaa, mda)

class  a     :


						def __init__(				self  ,    A_ = 8		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			0B0
										_UpperCAmelCase				:						Optional[Any]       						=			size


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[Any]       						=			self.hash_(A_		)
										self.bitarray |= h


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						int       						=			self.hash_(A_		)
										return (h & self.bitarray) == h


						def __contains__(				self  ,    A_		):







										'''simple docstring'''


										return self.exists(A_		)


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[int]       						=			bin(A_		)[2:]
										return res.zfill(self.size		)


						@property
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										return self.format_bin(self.bitarray		)


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Union[str, Any]       						=			0B0
										for func in HASH_FUNCTIONS:
														_UpperCAmelCase				:						str       						=			(
														    int.from_bytes(func(value.encode()		).digest()  ,    "little"		) % self.size
														)
														res |= 2**position
										return res


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										return self.format_bin(self.hash_(A_		)		)





						@property
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Union[str, Any]       						=			bin(self.bitarray		).count("1"		)
										return (n_ones / self.size) ** len(A_		)


