



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


SCREAMING_SNAKE_CASE				:     Optional[Any]          =	logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	"""ResNetConfig"""

# Base docstring
SCREAMING_SNAKE_CASE				:     Dict          =	"""microsoft/resnet-50"""
SCREAMING_SNAKE_CASE				:     Tuple          =	[1, 2_0_4_8, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE				:     Dict          =	"""microsoft/resnet-50"""
SCREAMING_SNAKE_CASE				:     int          =	"""tiger cat"""

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


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







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase = 3       ,	lowerCamelCase = 1       ,	lowerCamelCase = "relu"       ,	**lowerCamelCase				):




      '''simple docstring'''




      super().__init__(**lowerCamelCase				)
      _lowerCAmelCase					     =		kernel_size // 2
      _lowerCAmelCase					     =		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
      _lowerCAmelCase					     =		tf.keras.layers.BatchNormalization(epsilon=1e-5       ,	momentum=0.9       ,	name="""normalization"""				)
      _lowerCAmelCase					     =		ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("""linear"""				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




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







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.convolution(lowerCamelCase				)
      _lowerCAmelCase					     =		self.normalization(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.activation(lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''simple docstring'''




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







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      _lowerCAmelCase					     =		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."""				)
      _lowerCAmelCase					     =		pixel_values
      _lowerCAmelCase					     =		self.embedder(lowerCamelCase				)
      _lowerCAmelCase					     =		tf.pad(lowerCamelCase       ,	[[0, 0], [1, 1], [1, 1], [0, 0]]				)
      _lowerCAmelCase					     =		self.pooler(lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase = 2       ,	**lowerCamelCase				):




      '''simple docstring'''




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







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      _lowerCAmelCase					     =		x
      _lowerCAmelCase					     =		self.convolution(lowerCamelCase				)
      _lowerCAmelCase					     =		self.normalization(lowerCamelCase       ,	training=lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase = 1       ,	lowerCamelCase = "relu"       ,	**lowerCamelCase				):




      '''simple docstring'''




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







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      _lowerCAmelCase					     =		hidden_state
      _lowerCAmelCase					     =		self.conva(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.conva(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.shortcut(lowerCamelCase       ,	training=lowerCamelCase				)
      hidden_state += residual
      _lowerCAmelCase					     =		self.activation(lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase = 1       ,	lowerCamelCase = "relu"       ,	lowerCamelCase = 4       ,	**lowerCamelCase       ,	):




      '''simple docstring'''




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







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      _lowerCAmelCase					     =		hidden_state
      _lowerCAmelCase					     =		self.conva(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.conva(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.conva(lowerCamelCase       ,	training=lowerCamelCase				)
      _lowerCAmelCase					     =		self.shortcut(lowerCamelCase       ,	training=lowerCamelCase				)
      hidden_state += residual
      _lowerCAmelCase					     =		self.activation(lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase = 2       ,	lowerCamelCase = 2       ,	**lowerCamelCase				):




      '''simple docstring'''




      super().__init__(**lowerCamelCase				)

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

      _lowerCAmelCase					     =		[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				)
      ]
      _lowerCAmelCase					     =		layers







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False				):




      '''simple docstring'''




      for layer in self.stage_layers:
         _lowerCAmelCase					     =		layer(lowerCamelCase       ,	training=lowerCamelCase				)
      return hidden_state





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







   def __init__(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''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
      _lowerCAmelCase					     =		[
          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 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = False       ,	lowerCamelCase = True       ,	lowerCamelCase = False       ,	):




      '''simple docstring'''




      _lowerCAmelCase					     =		() if output_hidden_states else None

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

         _lowerCAmelCase					     =		stage_module(lowerCamelCase       ,	training=lowerCamelCase				)

      if output_hidden_states:
         _lowerCAmelCase					     =		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       __lowerCamelCase	(   snake_case__    ):
   __UpperCamelCase									=   ResNetConfig
   __UpperCamelCase									=   'resnet'
   __UpperCamelCase									=   'pixel_values'







   @property
   def 							A__						(self				):




      '''simple docstring'''




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





SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	r"""
    This model is a TensorFlow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""


SCREAMING_SNAKE_CASE				:     Optional[Any]          =	r"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""


@keras_serializable
class       __lowerCamelCase	(   tf.keras.layers.Layer    ):
   __UpperCamelCase									=   ResNetConfig







   def __init__(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''simple docstring'''




      super().__init__(**lowerCamelCase				)
      _lowerCAmelCase					     =		config
      _lowerCAmelCase					     =		TFResNetEmbeddings(lowerCamelCase       ,	name="""embedder"""				)
      _lowerCAmelCase					     =		TFResNetEncoder(lowerCamelCase       ,	name="""encoder"""				)
      _lowerCAmelCase					     =		tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCamelCase				)







   @unpack_inputs
   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None       ,	lowerCamelCase = None       ,	lowerCamelCase = False       ,	):




      '''simple docstring'''




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

      _lowerCAmelCase					     =		self.encoder(
          lowerCamelCase       ,	output_hidden_states=lowerCamelCase       ,	return_dict=lowerCamelCase       ,	training=lowerCamelCase				)

      _lowerCAmelCase					     =		encoder_outputs[0]

      _lowerCAmelCase					     =		self.pooler(lowerCamelCase				)

      # Transpose all the outputs to the NCHW format
      # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
      _lowerCAmelCase					     =		tf.transpose(lowerCamelCase       ,	(0, 3, 1, 2)				)
      _lowerCAmelCase					     =		tf.transpose(lowerCamelCase       ,	(0, 3, 1, 2)				)
      _lowerCAmelCase					     =		()
      for hidden_state in encoder_outputs[1:]:
         _lowerCAmelCase					     =		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

      _lowerCAmelCase					     =		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.'   ,							snake_case__   ,							)
class       __lowerCamelCase	(   snake_case__    ):







   def __init__(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''simple docstring'''




      super().__init__(lowerCamelCase       ,	**lowerCamelCase				)
      _lowerCAmelCase					     =		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 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None       ,	lowerCamelCase = None       ,	lowerCamelCase = False       ,	):




      '''simple docstring'''




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

      _lowerCAmelCase					     =		self.resnet(
          pixel_values=lowerCamelCase       ,	output_hidden_states=lowerCamelCase       ,	return_dict=lowerCamelCase       ,	training=lowerCamelCase       ,	)
      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    '   ,							snake_case__   ,							)
class       __lowerCamelCase	(   snake_case__   ,							snake_case__    ):







   def __init__(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''simple docstring'''




      super().__init__(lowerCamelCase       ,	**lowerCamelCase				)
      _lowerCAmelCase					     =		config.num_labels
      _lowerCAmelCase					     =		TFResNetMainLayer(lowerCamelCase       ,	name="""resnet"""				)
      # classification head
      _lowerCAmelCase					     =		(
          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 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		tf.keras.layers.Flatten()(lowerCamelCase				)
      _lowerCAmelCase					     =		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 							A__						(self       ,	lowerCamelCase = None       ,	lowerCamelCase = None       ,	lowerCamelCase = None       ,	lowerCamelCase = None       ,	lowerCamelCase = False       ,	):




      '''simple docstring'''




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

      _lowerCAmelCase					     =		self.resnet(
          lowerCamelCase       ,	output_hidden_states=lowerCamelCase       ,	return_dict=lowerCamelCase       ,	training=lowerCamelCase				)

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

      _lowerCAmelCase					     =		self.classifier(lowerCamelCase				)

      _lowerCAmelCase					     =		None if labels is None else self.hf_compute_loss(lowerCamelCase       ,	lowerCamelCase				)

      if not return_dict:
         _lowerCAmelCase					     =		(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"""





def 	__UpperCAmelCase					(       snake_case_  :  Optional[int]   ,	snake_case_  :  List[str]   )							->	Optional[int]:






   """simple docstring"""


   if n < 0:
      return 0
   # table[i] represents the number of ways to get to amount i
   _lowerCAmelCase					     =		[0] * (n + 1)

   # There is exactly 1 way to get to zero(You pick no coins).
   _lowerCAmelCase					     =		1

   # Pick all coins one by one and update table[] values
   # after the index greater than or equal to the value of the
   # picked coin
   for coin_val in s:
      for j in range(snake_case_   ,	n + 1   ):
         table[j] += table[j - coin_val]

   return table[n]


if __name__ == "__main__":
  import doctest

  doctest.testmod()