





from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    """RegNetConfig"""

# Base docstring
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE__							:      Dict         =    [1, 1_0_8_8, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE__							:      List[Any]         =    """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    """tabby, tabby cat"""

SCREAMING_SNAKE_CASE__							:      str         =    [
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]







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





   def __init__(			self       ,      snake_case       ,      snake_case = 3       ,      snake_case = 1       ,      snake_case = 1       ,      snake_case = "relu"       ,      **snake_case       ,      )					->	Dict:
      """simple docstring"""





      super().__init__(**snake_case   )
      # The padding and conv has been verified in
      # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
      a__						:    List[str]   		=	tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2   )
      a__						:    Tuple   		=	tf.keras.layers.ConvaD(
          filters=snake_case       ,      kernel_size=snake_case       ,      strides=snake_case       ,      padding="VALID"       ,      groups=snake_case       ,      use_bias=snake_case       ,      name="convolution"       ,      )
      a__						:    Any   		=	tf.keras.layers.BatchNormalization(epsilon=1E-5       ,      momentum=0.9       ,      name="normalization"   )
      a__						:    List[str]   		=	ACTaFN[activation] if activation is not None else tf.identity





   def 						_snake_case			(			self       ,      snake_case   )					->	Dict:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	self.convolution(self.padding(snake_case   )   )
      a__						:    Dict   		=	self.normalization(snake_case   )
      a__						:    Optional[int]   		=	self.activation(snake_case   )
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      **snake_case   )					->	str:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    List[Any]   		=	config.num_channels
      a__						:    Optional[int]   		=	TFRegNetConvLayer(
          out_channels=config.embedding_size       ,      kernel_size=3       ,      stride=2       ,      activation=config.hidden_act       ,      name="embedder"       ,      )





   def 						_snake_case			(			self       ,      snake_case   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	shape_list(snake_case   )[1]
      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."   )

      # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
      # So change the input format from `NCHW` to `NHWC`.
      # shape = (batch_size, in_height, in_width, in_channels=num_channels)
      a__						:    Union[str, Any]   		=	tf.transpose(snake_case       ,      perm=(0, 2, 3, 1)   )
      a__						:    Tuple   		=	self.embedder(snake_case   )
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      snake_case = 2       ,      **snake_case   )					->	Optional[Any]:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    List[str]   		=	tf.keras.layers.ConvaD(
          filters=snake_case       ,      kernel_size=1       ,      strides=snake_case       ,      use_bias=snake_case       ,      name="convolution"   )
      a__						:    Dict   		=	tf.keras.layers.BatchNormalization(epsilon=1E-5       ,      momentum=0.9       ,      name="normalization"   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = False   )					->	tf.Tensor:
      """simple docstring"""





      return self.normalization(self.convolution(snake_case   )       ,      training=snake_case   )







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





   def __init__(			self       ,      snake_case       ,      snake_case       ,      **snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    int   		=	tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case       ,      name="pooler"   )
      a__						:    List[str]   		=	[
          tf.keras.layers.ConvaD(filters=snake_case       ,      kernel_size=1       ,      activation="relu"       ,      name="attention.0"   ),
          tf.keras.layers.ConvaD(filters=snake_case       ,      kernel_size=1       ,      activation="sigmoid"       ,      name="attention.2"   ),
      ]





   def 						_snake_case			(			self       ,      snake_case   )					->	Any:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	self.pooler(snake_case   )
      for layer_module in self.attention:
         a__						:    Optional[int]   		=	layer_module(snake_case   )
      a__						:    Any   		=	hidden_state * pooled
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case = 1       ,      **snake_case   )					->	Any:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    Optional[Any]   		=	in_channels != out_channels or stride != 1
      a__						:    Dict   		=	max(1       ,      out_channels // config.groups_width   )
      a__						:    Dict   		=	(
          TFRegNetShortCut(snake_case       ,      stride=snake_case       ,      name="shortcut"   )
          if should_apply_shortcut
          else tf.keras.layers.Activation("linear"       ,      name="shortcut"   )
      )
      # `self.layers` instead of `self.layer` because that is a reserved argument.
      a__						:    Dict   		=	[
          TFRegNetConvLayer(snake_case       ,      kernel_size=1       ,      activation=config.hidden_act       ,      name="layer.0"   ),
          TFRegNetConvLayer(
              snake_case       ,      stride=snake_case       ,      groups=snake_case       ,      activation=config.hidden_act       ,      name="layer.1"   ),
          TFRegNetConvLayer(snake_case       ,      kernel_size=1       ,      activation=snake_case       ,      name="layer.2"   ),
      ]
      a__						:    int   		=	ACTaFN[config.hidden_act]





   def 						_snake_case			(			self       ,      snake_case   )					->	Dict:
      """simple docstring"""





      a__						:    int   		=	hidden_state
      for layer_module in self.layers:
         a__						:    int   		=	layer_module(snake_case   )
      a__						:    Optional[int]   		=	self.shortcut(snake_case   )
      hidden_state += residual
      a__						:    int   		=	self.activation(snake_case   )
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case = 1       ,      **snake_case   )					->	int:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    Dict   		=	in_channels != out_channels or stride != 1
      a__						:    Tuple   		=	max(1       ,      out_channels // config.groups_width   )
      a__						:    Dict   		=	(
          TFRegNetShortCut(snake_case       ,      stride=snake_case       ,      name="shortcut"   )
          if should_apply_shortcut
          else tf.keras.layers.Activation("linear"       ,      name="shortcut"   )
      )
      a__						:    Tuple   		=	[
          TFRegNetConvLayer(snake_case       ,      kernel_size=1       ,      activation=config.hidden_act       ,      name="layer.0"   ),
          TFRegNetConvLayer(
              snake_case       ,      stride=snake_case       ,      groups=snake_case       ,      activation=config.hidden_act       ,      name="layer.1"   ),
          TFRegNetSELayer(snake_case       ,      reduced_channels=int(round(in_channels / 4   )   )       ,      name="layer.2"   ),
          TFRegNetConvLayer(snake_case       ,      kernel_size=1       ,      activation=snake_case       ,      name="layer.3"   ),
      ]
      a__						:    str   		=	ACTaFN[config.hidden_act]





   def 						_snake_case			(			self       ,      snake_case   )					->	Tuple:
      """simple docstring"""





      a__						:    int   		=	hidden_state
      for layer_module in self.layers:
         a__						:    int   		=	layer_module(snake_case   )
      a__						:    int   		=	self.shortcut(snake_case   )
      hidden_state += residual
      a__						:    List[Any]   		=	self.activation(snake_case   )
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case = 2       ,      snake_case = 2       ,      **snake_case   )					->	Dict:
      """simple docstring"""





      super().__init__(**snake_case   )

      a__						:    str   		=	TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer
      a__						:    Any   		=	[
          # downsampling is done in the first layer with stride of 2
          layer(snake_case       ,      snake_case       ,      snake_case       ,      stride=snake_case       ,      name="layers.0"   ),
          *[layer(snake_case       ,      snake_case       ,      snake_case       ,      name=F"""layers.{i+1}"""   ) for i in range(depth - 1   )],
      ]





   def 						_snake_case			(			self       ,      snake_case   )					->	Optional[int]:
      """simple docstring"""





      for layer_module in self.layers:
         a__						:    List[str]   		=	layer_module(snake_case   )
      return hidden_state







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





   def __init__(			self       ,      snake_case       ,      **snake_case   )					->	List[str]:
      """simple docstring"""





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





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = False       ,      snake_case = True   )					->	TFBaseModelOutputWithNoAttention:
      """simple docstring"""





      a__						:    Tuple   		=	() if output_hidden_states else None

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

         a__						:    Optional[Any]   		=	stage_module(snake_case   )

      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=snake_case       ,      hidden_states=snake_case   )







@keras_serializable
class 	__lowerCAmelCase      (       tf.keras.layers.Layer	):
   _UpperCamelCase			:    int  		=					RegNetConfig





   def __init__(			self       ,      snake_case       ,      **snake_case   )					->	Optional[Any]:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    List[str]   		=	config
      a__						:    List[str]   		=	TFRegNetEmbeddings(snake_case       ,      name="embedder"   )
      a__						:    Any   		=	TFRegNetEncoder(snake_case       ,      name="encoder"   )
      a__						:    Optional[int]   		=	tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case       ,      name="pooler"   )





   @unpack_inputs
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None       ,      snake_case = None       ,      snake_case = False       ,      )					->	TFBaseModelOutputWithPoolingAndNoAttention:
      """simple docstring"""





      a__						:    int   		=	(
          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__						:    Union[str, Any]   		=	self.embedder(snake_case       ,      training=snake_case   )

      a__						:    List[Any]   		=	self.encoder(
          snake_case       ,      output_hidden_states=snake_case       ,      return_dict=snake_case       ,      training=snake_case   )

      a__						:    List[str]   		=	encoder_outputs[0]
      a__						:    List[str]   		=	self.pooler(snake_case   )

      # Change to NCHW output format have uniformity in the modules
      a__						:    Any   		=	tf.transpose(snake_case       ,      perm=(0, 3, 1, 2)   )
      a__						:    Dict   		=	tf.transpose(snake_case       ,      perm=(0, 3, 1, 2)   )

      # Change the other hidden state outputs to NCHW as well
      if output_hidden_states:
         a__						:    Optional[int]   		=	tuple([tf.transpose(snake_case       ,      perm=(0, 3, 1, 2)   ) for h in encoder_outputs[1]]   )

      if not return_dict:
         return (last_hidden_state, pooled_output) + encoder_outputs[1:]

      return TFBaseModelOutputWithPoolingAndNoAttention(
          last_hidden_state=snake_case       ,      pooler_output=snake_case       ,      hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states       ,      )







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    Optional[int]  		=					RegNetConfig
   _UpperCamelCase			:    str  		=					"""regnet"""
   _UpperCamelCase			:    Tuple  		=					"""pixel_values"""





   @property
   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





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







SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    R"""
    Parameters:
    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.
        config ([`RegNetConfig`]): 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__							:      str         =    R"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__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.
"""







@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top."""		,_UpperCamelCase		,)
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   def __init__(			self       ,      snake_case       ,      *snake_case       ,      **snake_case   )					->	Any:
      """simple docstring"""





      super().__init__(snake_case       ,      *snake_case       ,      **snake_case   )
      a__						:    int   		=	TFRegNetMainLayer(snake_case       ,      name="regnet"   )





   @unpack_inputs
   @add_start_docstrings_to_model_forward(snake_case   )
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC       ,      output_type=snake_case       ,      config_class=_CONFIG_FOR_DOC       ,      modality="vision"       ,      expected_output=_EXPECTED_OUTPUT_SHAPE       ,      )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None       ,      snake_case = None       ,      snake_case=False       ,      )					->	Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
      """simple docstring"""





      a__						:    Optional[int]   		=	(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      a__						:    Optional[int]   		=	return_dict if return_dict is not None else self.config.use_return_dict

      a__						:    List[Any]   		=	self.regnet(
          pixel_values=snake_case       ,      output_hidden_states=snake_case       ,      return_dict=snake_case       ,      training=snake_case       ,      )
      if not return_dict:
         return (outputs[0],) + outputs[1:]

      return TFBaseModelOutputWithPoolingAndNoAttention(
          last_hidden_state=outputs.last_hidden_state       ,      pooler_output=outputs.pooler_output       ,      hidden_states=outputs.hidden_states       ,      )







@add_start_docstrings(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """		,_UpperCamelCase		,)
class 	__lowerCAmelCase      (       _UpperCamelCase		,_UpperCamelCase	):





   def __init__(			self       ,      snake_case       ,      *snake_case       ,      **snake_case   )					->	Optional[int]:
      """simple docstring"""





      super().__init__(snake_case       ,      *snake_case       ,      **snake_case   )
      a__						:    str   		=	config.num_labels
      a__						:    Dict   		=	TFRegNetMainLayer(snake_case       ,      name="regnet"   )
      # classification head
      a__						:    Optional[int]   		=	[
          tf.keras.layers.Flatten(),
          tf.keras.layers.Dense(config.num_labels       ,      name="classifier.1"   ) if config.num_labels > 0 else tf.identity,
      ]





   @unpack_inputs
   @add_start_docstrings_to_model_forward(snake_case   )
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT       ,      output_type=snake_case       ,      config_class=_CONFIG_FOR_DOC       ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,      )
   def 						_snake_case			(			self       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case=False       ,      )					->	Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
      """simple docstring"""





      a__						:    Tuple   		=	(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      a__						:    Dict   		=	return_dict if return_dict is not None else self.config.use_return_dict

      a__						:    List[Any]   		=	self.regnet(
          snake_case       ,      output_hidden_states=snake_case       ,      return_dict=snake_case       ,      training=snake_case   )

      a__						:    List[str]   		=	outputs.pooler_output if return_dict else outputs[1]

      a__						:    Tuple   		=	self.classifier[0](snake_case   )
      a__						:    Optional[Any]   		=	self.classifier[1](snake_case   )

      a__						:    int   		=	None if labels is None else self.hf_compute_loss(labels=snake_case       ,      logits=snake_case   )

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

      return TFSequenceClassifierOutput(loss=snake_case       ,      logits=snake_case       ,      hidden_states=outputs.hidden_states   )








import argparse
import os
import re


SCREAMING_SNAKE_CASE__							:      Any         =    """src/transformers/models/auto"""


# re pattern that matches mapping introductions:
#    SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    re.compile(R"""[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict""")
# re pattern that matches identifiers in mappings
SCREAMING_SNAKE_CASE__							:      Optional[int]         =    re.compile(R"""\s*\(\s*\"(\S[^\"]+)\"""")






def    _A	(   lowerCamelCase				,			lowerCamelCase = False ):
   with open(lowerCamelCase				,			"r"				,			encoding="utf-8" ) as f:
      a__						:    Optional[int]   		=	f.read()

   a__						:    Optional[Any]   		=	content.split("\n" )
   a__						:    Optional[int]   		=	[]
   a__						:    Optional[Any]   		=	0
   while line_idx < len(lowerCamelCase ):
      if _re_intro_mapping.search(lines[line_idx] ) is not None:
         a__						:    str   		=	len(re.search(r"^(\s*)\S"				,			lines[line_idx] ).groups()[0] ) + 8
         # Start of a new mapping!
         while not lines[line_idx].startswith(" " * indent + "(" ):
            new_lines.append(lines[line_idx] )
            line_idx += 1

         a__						:    Union[str, Any]   		=	[]
         while lines[line_idx].strip() != "]":
            # Blocks either fit in one line or not
            if lines[line_idx].strip() == "(":
               a__						:    int   		=	line_idx
               while not lines[line_idx].startswith(" " * indent + ")" ):
                  line_idx += 1
               blocks.append("\n".join(lines[start_idx : line_idx + 1] ) )
            else:
               blocks.append(lines[line_idx] )
            line_idx += 1

         # Sort blocks by their identifiers
         a__						:    Optional[Any]   		=	sorted(lowerCamelCase				,			key=lambda lowerCamelCase : _re_identifier.search(lowerCamelCase ).groups()[0] )
         new_lines += blocks
      else:
         new_lines.append(lines[line_idx] )
         line_idx += 1

   if overwrite:
      with open(lowerCamelCase				,			"w"				,			encoding="utf-8" ) as f:
         f.write("\n".join(lowerCamelCase ) )
   elif "\n".join(lowerCamelCase ) != content:
      return True






def    _A	(   lowerCamelCase = False ):
   a__						:    List[str]   		=	[os.path.join(lowerCamelCase				,			lowerCamelCase ) for f in os.listdir(lowerCamelCase ) if f.endswith(".py" )]
   a__						:    Any   		=	[sort_auto_mapping(lowerCamelCase				,			overwrite=lowerCamelCase ) for fname in fnames]

   if not overwrite and any(lowerCamelCase ):
      a__						:    Dict   		=	[f for f, d in zip(lowerCamelCase				,			lowerCamelCase ) if d]
      raise ValueError(
          F"""The following files have auto mappings that need sorting: {", ".join(lowerCamelCase )}. Run `make style` to fix"""
          " this." )


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE__							:      Dict         =    argparse.ArgumentParser()
  parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""")
  SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    parser.parse_args()

  sort_all_auto_mappings(not args.check_only)

