




'''simple docstring'''







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


lowerCAmelCase_     						=				logging.get_logger(__name__)

# General docstring
lowerCAmelCase_     						=				'''RegNetConfig'''

# Base docstring
lowerCAmelCase_     						=				'''facebook/regnet-y-040'''
lowerCAmelCase_     						=				[1, 1_0_8_8, 7, 7]

# Image classification docstring
lowerCAmelCase_     						=				'''facebook/regnet-y-040'''
lowerCAmelCase_     						=				'''tabby, tabby cat'''

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

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






 def __init__(self       :  List[Any]    ,		a       :  int    ,		a       :  int = 3    ,		a       :  int = 1    ,		a       :  int = 1    ,		a       :  Optional[str] = "relu"    ,		**a       :  str    ,		)       ->   List[Any]:






    """simple docstring"""


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






 def 						_UpperCamelCase (self       :  Any    ,		a       :  Optional[int]    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     self.convolution(self.padding(a    )    )
    A__       =     self.normalization(a    )
    A__       =     self.activation(a    )
    return hidden_state




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






 def __init__(self       :  List[str]    ,		a       :  RegNetConfig    ,		**a       :  Tuple    )       ->   Union[str, Any]:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     config.num_channels
    A__       =     TFRegNetConvLayer(
        out_channels=config.embedding_size    ,		kernel_size=3    ,		stride=2    ,		activation=config.hidden_act    ,		name='embedder'    ,		)






 def 						_UpperCamelCase (self       :  List[Any]    ,		a       :  Union[str, Any]    )       ->   Any:






    """simple docstring"""


    A__       =     shape_list(a    )[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__       =     tf.transpose(a    ,		perm=(0, 2, 3, 1)    )
    A__       =     self.embedder(a    )
    return hidden_state




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






 def __init__(self       :  str    ,		a       :  int    ,		a       :  int = 2    ,		**a       :  Tuple    )       ->   Tuple:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     tf.keras.layers.ConvaD(
        filters=a    ,		kernel_size=1    ,		strides=a    ,		use_bias=a    ,		name='convolution'    )
    A__       =     tf.keras.layers.BatchNormalization(epsilon=1e-5    ,		momentum=0.9    ,		name='normalization'    )






 def 						_UpperCamelCase (self       :  int    ,		a       :  tf.Tensor    ,		a       :  bool = False    )       ->   tf.Tensor:






    """simple docstring"""


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




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






 def __init__(self       :  Any    ,		a       :  int    ,		a       :  int    ,		**a       :  Optional[Any]    )       ->   Optional[int]:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     tf.keras.layers.GlobalAveragePoolingaD(keepdims=a    ,		name='pooler'    )
    A__       =     [
        tf.keras.layers.ConvaD(filters=a    ,		kernel_size=1    ,		activation='relu'    ,		name='attention.0'    ),
        tf.keras.layers.ConvaD(filters=a    ,		kernel_size=1    ,		activation='sigmoid'    ,		name='attention.2'    ),
    ]






 def 						_UpperCamelCase (self       :  str    ,		a       :  Union[str, Any]    )       ->   Any:






    """simple docstring"""


    A__       =     self.pooler(a    )
    for layer_module in self.attention:
       A__       =     layer_module(a    )
    A__       =     hidden_state * pooled
    return hidden_state




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






 def __init__(self       :  Optional[int]    ,		a       :  RegNetConfig    ,		a       :  int    ,		a       :  int    ,		a       :  int = 1    ,		**a       :  List[Any]    )       ->   List[str]:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     in_channels != out_channels or stride != 1
    A__       =     max(1    ,		out_channels // config.groups_width    )
    A__       =     (
        TFRegNetShortCut(a    ,		stride=a    ,		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__       =     [
        TFRegNetConvLayer(a    ,		kernel_size=1    ,		activation=config.hidden_act    ,		name='layer.0'    ),
        TFRegNetConvLayer(
            a    ,		stride=a    ,		groups=a    ,		activation=config.hidden_act    ,		name='layer.1'    ),
        TFRegNetConvLayer(a    ,		kernel_size=1    ,		activation=a    ,		name='layer.2'    ),
    ]
    A__       =     ACTaFN[config.hidden_act]






 def 						_UpperCamelCase (self       :  List[str]    ,		a       :  Tuple    )       ->   Dict:






    """simple docstring"""


    A__       =     hidden_state
    for layer_module in self.layers:
       A__       =     layer_module(a    )
    A__       =     self.shortcut(a    )
    hidden_state += residual
    A__       =     self.activation(a    )
    return hidden_state




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






 def __init__(self       :  Any    ,		a       :  RegNetConfig    ,		a       :  int    ,		a       :  int    ,		a       :  int = 1    ,		**a       :  Dict    )       ->   Optional[int]:






    """simple docstring"""


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






 def 						_UpperCamelCase (self       :  Optional[Any]    ,		a       :  str    )       ->   Tuple:






    """simple docstring"""


    A__       =     hidden_state
    for layer_module in self.layers:
       A__       =     layer_module(a    )
    A__       =     self.shortcut(a    )
    hidden_state += residual
    A__       =     self.activation(a    )
    return hidden_state




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






 def __init__(self       :  str    ,		a       :  RegNetConfig    ,		a       :  int    ,		a       :  int    ,		a       :  int = 2    ,		a       :  int = 2    ,		**a       :  Tuple    )       ->   Tuple:






    """simple docstring"""


    super().__init__(**a    )

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






 def 						_UpperCamelCase (self       :  Union[str, Any]    ,		a       :  Dict    )       ->   int:






    """simple docstring"""


    for layer_module in self.layers:
       A__       =     layer_module(a    )
    return hidden_state




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






 def __init__(self       :  Optional[Any]    ,		a       :  RegNetConfig    ,		**a       :  Any    )       ->   List[Any]:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     []
    # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
    self.stages.append(
        TFRegNetStage(
            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'    ,		)    )
    A__       =     zip(config.hidden_sizes    ,		config.hidden_sizes[1:]    )
    for i, ((in_channels, out_channels), depth) in enumerate(zip(a    ,		config.depths[1:]    )    ):
       self.stages.append(TFRegNetStage(a    ,		a    ,		a    ,		depth=a    ,		name=f"""stages.{i+1}"""    )    )






 def 						_UpperCamelCase (self       :  int    ,		a       :  tf.Tensor    ,		a       :  bool = False    ,		a       :  bool = True    )       ->   TFBaseModelOutputWithNoAttention:






    """simple docstring"""


    A__       =     () if output_hidden_states else None

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

       A__       =     stage_module(a    )

    if output_hidden_states:
       A__       =     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    )




@keras_serializable
class 	_snake_case(			tf.keras.layers.Layer      ):
 __snake_case:							Dict						=					RegNetConfig






 def __init__(self       :  List[str]    ,		a       :  Tuple    ,		**a       :  Any    )       ->   List[str]:






    """simple docstring"""


    super().__init__(**a    )
    A__       =     config
    A__       =     TFRegNetEmbeddings(a    ,		name='embedder'    )
    A__       =     TFRegNetEncoder(a    ,		name='encoder'    )
    A__       =     tf.keras.layers.GlobalAveragePoolingaD(keepdims=a    ,		name='pooler'    )






 @unpack_inputs
 def 						_UpperCamelCase (self       :  Union[str, Any]    ,		a       :  tf.Tensor    ,		a       :  Optional[bool] = None    ,		a       :  Optional[bool] = None    ,		a       :  bool = False    ,		)       ->   TFBaseModelOutputWithPoolingAndNoAttention:






    """simple docstring"""


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

    A__       =     self.embedder(a    ,		training=a    )

    A__       =     self.encoder(
        a    ,		output_hidden_states=a    ,		return_dict=a    ,		training=a    )

    A__       =     encoder_outputs[0]
    A__       =     self.pooler(a    )

    # Change to NCHW output format have uniformity in the modules
    A__       =     tf.transpose(a    ,		perm=(0, 3, 1, 2)    )
    A__       =     tf.transpose(a    ,		perm=(0, 3, 1, 2)    )

    # Change the other hidden state outputs to NCHW as well
    if output_hidden_states:
       A__       =     tuple([tf.transpose(a    ,		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=a    ,		pooler_output=a    ,		hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states    ,		)




class 	_snake_case(			UpperCAmelCase      ):
 __snake_case:							Optional[Any]						=					RegNetConfig
 __snake_case:							List[str]						=					'''regnet'''
 __snake_case:							Tuple						=					'''pixel_values'''






 @property
 def 						_UpperCamelCase (self       :  str    )       ->   List[Any]:






    """simple docstring"""


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




lowerCAmelCase_     						=				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.
'''

lowerCAmelCase_     						=				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 	_snake_case(			UpperCAmelCase      ):






 def __init__(self       :  List[Any]    ,		a       :  RegNetConfig    ,		*a       :  str    ,		**a       :  Dict    )       ->   int:






    """simple docstring"""


    super().__init__(a    ,		*a    ,		**a    )
    A__       =     TFRegNetMainLayer(a    ,		name='regnet'    )






 @unpack_inputs
 @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    ,		)
 def 						_UpperCamelCase (self       :  Dict    ,		a       :  tf.Tensor    ,		a       :  Optional[bool] = None    ,		a       :  Optional[bool] = None    ,		a       :  Optional[int]=False    ,		)       ->   Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:






    """simple docstring"""


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

    A__       =     self.regnet(
        pixel_values=a    ,		output_hidden_states=a    ,		return_dict=a    ,		training=a    ,		)
    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 	_snake_case(			UpperCAmelCase       , UpperCAmelCase      ):






 def __init__(self       :  Union[str, Any]    ,		a       :  RegNetConfig    ,		*a       :  Optional[int]    ,		**a       :  Optional[int]    )       ->   Dict:






    """simple docstring"""


    super().__init__(a    ,		*a    ,		**a    )
    A__       =     config.num_labels
    A__       =     TFRegNetMainLayer(a    ,		name='regnet'    )
    # classification head
    A__       =     [
        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(a    )
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT    ,		output_type=a    ,		config_class=_CONFIG_FOR_DOC    ,		expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT    ,		)
 def 						_UpperCamelCase (self       :  Tuple    ,		a       :  tf.Tensor = None    ,		a       :  tf.Tensor = None    ,		a       :  bool = None    ,		a       :  bool = None    ,		a       :  List[Any]=False    ,		)       ->   Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:






    """simple docstring"""


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

    A__       =     self.regnet(
        a    ,		output_hidden_states=a    ,		return_dict=a    ,		training=a    )

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

    A__       =     self.classifier[0](a    )
    A__       =     self.classifier[1](a    )

    A__       =     None if labels is None else self.hf_compute_loss(labels=a    ,		logits=a    )

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

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








'''simple docstring'''







import re
import string

import numpy as np

import datasets


lowerCAmelCase_     						=				'''
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
'''

lowerCAmelCase_     						=				'''
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    25.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    50.0


    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    75.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results["exact_match"], 1))
    100.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]
    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    33.3

'''

lowerCAmelCase_     						=				'''
'''

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       , _KWARGS_DESCRIPTION      )
class 	_snake_case(			datasets.Metric      ):






 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   Dict:






    """simple docstring"""


    return datasets.MetricInfo(
        description=_DESCRIPTION    ,		citation=_CITATION    ,		inputs_description=_KWARGS_DESCRIPTION    ,		features=datasets.Features(
            {
                'predictions': datasets.Value('string'    ,		id='sequence'    ),
                'references': datasets.Value('string'    ,		id='sequence'    ),
            }    )    ,		reference_urls=[]    ,		)






 def 						_UpperCamelCase (self       :  List[str]    ,		a       :  str    ,		a       :  Tuple    ,		a       :  Tuple=None    ,		a       :  Dict=False    ,		a       :  Dict=False    ,		a       :  List[str]=False    ,		)       ->   int:






    """simple docstring"""


    if regexes_to_ignore is not None:
       for s in regexes_to_ignore:
          A__       =     np.array([re.sub(a    ,		''    ,		a    ) for x in predictions]    )
          A__       =     np.array([re.sub(a    ,		''    ,		a    ) for x in references]    )
    else:
       A__       =     np.asarray(a    )
       A__       =     np.asarray(a    )

    if ignore_case:
       A__       =     np.char.lower(a    )
       A__       =     np.char.lower(a    )

    if ignore_punctuation:
       A__       =     string.punctuation.maketrans(''    ,		''    ,		string.punctuation    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    if ignore_numbers:
       A__       =     string.digits.maketrans(''    ,		''    ,		string.digits    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    A__       =     predictions == references

    return {"exact_match": np.mean(a    ) * 1_00}


