


from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
 import tensorflow as tf

 from ..tf_utils import stable_softmax


if is_torch_available():
 import torch


SCREAMING_SNAKE_CASE :   int							      =				logging.get_logger(__name__)






@add_end_docstrings(
    _a,				R"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """,				)
class _lowerCamelCase(		_a     ):
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     np.ndarray:




           """simple docstring"""

           if self.framework == "tf":
               _lowercase :							Dict   	=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
           elif self.framework == "pt":
               _lowercase :							Dict   	=	torch.nonzero(input_ids == self.tokenizer.mask_token_id,   as_tuple=lowerCamelCase)
           else:
               raise ValueError('Unsupported framework')
           return masked_index
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     np.ndarray:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.get_masked_index(lowerCamelCase)
           _lowercase :							Tuple   	=	np.prod(masked_index.shape)
           if numel < 1:
               raise PipelineException(
                   'fill-mask',   self.model.base_model_prefix,   F'''No mask_token ({self.tokenizer.mask_token}) found on the input''',   )
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[Any]:




           """simple docstring"""

           if isinstance(lowerCamelCase,   lowerCamelCase):
               for model_input in model_inputs:
                   self._ensure_exactly_one_mask_token(model_input['input_ids'][0])
           else:
               for input_ids in model_inputs["input_ids"]:
                   self._ensure_exactly_one_mask_token(lowerCamelCase)
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase=None,   **lowerCamelCase) ->     Dict[str, GenericTensor]:




           """simple docstring"""

           if return_tensors is None:
               _lowercase :							Tuple   	=	self.framework
           _lowercase :							Optional[Any]   	=	self.tokenizer(lowerCamelCase,   return_tensors=lowerCamelCase)
           self.ensure_exactly_one_mask_token(lowerCamelCase)
           return model_inputs
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.model(**lowerCamelCase)
           _lowercase :							Union[str, Any]   	=	model_inputs['input_ids']
           return model_outputs
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase=5,   lowerCamelCase=None) ->     List[str]:




           """simple docstring"""

           if target_ids is not None and target_ids.shape[0] < top_k:
               _lowercase :							Tuple   	=	target_ids.shape[0]
           _lowercase :							Optional[int]   	=	model_outputs['input_ids'][0]
           _lowercase :							Any   	=	model_outputs['logits']

           if self.framework == "tf":
               _lowercase :							Optional[Any]   	=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

               _lowercase :							Tuple   	=	outputs.numpy()

               _lowercase :							str   	=	outputs[0, masked_index, :]
               _lowercase :							Tuple   	=	stable_softmax(lowerCamelCase,   axis=-1)
               if target_ids is not None:
                   _lowercase :							str   	=	tf.gather_nd(tf.squeeze(lowerCamelCase,   0),   target_ids.reshape(-1,   1))
                   _lowercase :							Dict   	=	tf.expand_dims(lowerCamelCase,   0)

               _lowercase :							int   	=	tf.math.top_k(lowerCamelCase,   k=lowerCamelCase)
               _lowercase	,       _lowercase :							List[Any]   	=	topk.values.numpy(), topk.indices.numpy()
           else:
               _lowercase :							Optional[Any]   	=	torch.nonzero(input_ids == self.tokenizer.mask_token_id,   as_tuple=lowerCamelCase).squeeze(-1)
               # Fill mask pipeline supports only one ${mask_token} per sample

               _lowercase :							Tuple   	=	outputs[0, masked_index, :]
               _lowercase :							List[str]   	=	logits.softmax(dim=-1)
               if target_ids is not None:
                   _lowercase :							Union[str, Any]   	=	probs[..., target_ids]

               _lowercase	,       _lowercase :							List[Any]   	=	probs.topk(lowerCamelCase)

           _lowercase :							int   	=	[]
           _lowercase :							str   	=	values.shape[0] == 1
           for i, (_values, _predictions) in enumerate(zip(values.tolist(),   predictions.tolist())):
               _lowercase :							str   	=	[]
               for v, p in zip(_values,   _predictions):
                   # Copy is important since we're going to modify this array in place
                   _lowercase :							List[Any]   	=	input_ids.numpy().copy()
                   if target_ids is not None:
                       _lowercase :							Optional[int]   	=	target_ids[p].tolist()

                   _lowercase :							Tuple   	=	p
                   # Filter padding out:
                   _lowercase :							Tuple   	=	tokens[np.where(tokens != self.tokenizer.pad_token_id)]
                   # Originally we skip special tokens to give readable output.
                   # For multi masks though, the other [MASK] would be removed otherwise
                   # making the output look odd, so we add them back
                   _lowercase :							Optional[int]   	=	self.tokenizer.decode(lowerCamelCase,   skip_special_tokens=lowerCamelCase)
                   _lowercase :							Optional[int]   	=	{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]), 'sequence': sequence}
                   row.append(lowerCamelCase)
               result.append(lowerCamelCase)
           if single_mask:
               return result[0]
           return result
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase=None) ->     List[str]:




           """simple docstring"""

           if isinstance(lowerCamelCase,   lowerCamelCase):
               _lowercase :							str   	=	[targets]
           try:
               _lowercase :							Any   	=	self.tokenizer.get_vocab()
           except Exception:
               _lowercase :							List[Any]   	=	{}
           _lowercase :							List[str]   	=	[]
           for target in targets:
               _lowercase :							str   	=	vocab.get(lowerCamelCase,   lowerCamelCase)
               if id_ is None:
                   _lowercase :							Optional[Any]   	=	self.tokenizer(
                       lowerCamelCase,   add_special_tokens=lowerCamelCase,   return_attention_mask=lowerCamelCase,   return_token_type_ids=lowerCamelCase,   max_length=1,   truncation=lowerCamelCase,   )['input_ids']
                   if len(lowerCamelCase) == 0:
                       logger.warning(
                           F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                           'We cannot replace it with anything meaningful, ignoring it')
                       continue
                   _lowercase :							List[Any]   	=	input_ids[0]
                   # XXX: If users encounter this pass
                   # it becomes pretty slow, so let's make sure
                   # The warning enables them to fix the input to
                   # get faster performance.
                   logger.warning(
                       F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                       F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.''')
               target_ids.append(id_)
           _lowercase :							List[str]   	=	list(set(lowerCamelCase))
           if len(lowerCamelCase) == 0:
               raise ValueError('At least one target must be provided when passed.')
           _lowercase :							Tuple   	=	np.array(lowerCamelCase)
           return target_ids
       def     UpperCamelCase  (      self,   lowerCamelCase=None,   lowerCamelCase=None) ->     str:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	{}

           if targets is not None:
               _lowercase :							str   	=	self.get_target_ids(lowerCamelCase,   lowerCamelCase)
               _lowercase :							str   	=	target_ids

           if top_k is not None:
               _lowercase :							str   	=	top_k

           if self.tokenizer.mask_token_id is None:
               raise PipelineException(
                   'fill-mask',   self.model.base_model_prefix,   'The tokenizer does not define a `mask_token`.')
           return {}, {}, postprocess_params




       def __call__(      self,   lowerCamelCase,   *lowerCamelCase,   **lowerCamelCase) ->     int:




           """simple docstring"""

           _lowercase :							Dict   	=	super().__call__(lowerCamelCase,   **lowerCamelCase)
           if isinstance(lowerCamelCase,   lowerCamelCase) and len(lowerCamelCase) == 1:
               return outputs[0]
           return outputs






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

# General docstring
SCREAMING_SNAKE_CASE :   str							      =				"RegNetConfig"

# Base docstring
SCREAMING_SNAKE_CASE :   Tuple							      =				"facebook/regnet-y-040"
SCREAMING_SNAKE_CASE :   Dict							      =				[1, 1088, 7, 7]

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

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






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase = 3,   lowerCamelCase = 1,   lowerCamelCase = 1,   lowerCamelCase = "relu",   **lowerCamelCase,   ) ->     int:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							str   	=	self.convolution(self.padding(lowerCamelCase))
           _lowercase :							int   	=	self.normalization(lowerCamelCase)
           _lowercase :							Optional[Any]   	=	self.activation(lowerCamelCase)
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   **lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           super().__init__(**lowerCamelCase)
           _lowercase :							Tuple   	=	config.num_channels
           _lowercase :							Tuple   	=	TFRegNetConvLayer(
               out_channels=config.embedding_size,   kernel_size=3,   stride=2,   activation=config.hidden_act,   name='embedder',   )




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Dict   	=	shape_list(lowerCamelCase)[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)
           _lowercase :							Optional[Any]   	=	tf.transpose(lowerCamelCase,   perm=(0, 2, 3, 1))
           _lowercase :							int   	=	self.embedder(lowerCamelCase)
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase = 2,   **lowerCamelCase) ->     Optional[Any]:




           """simple docstring"""

           super().__init__(**lowerCamelCase)
           _lowercase :							List[Any]   	=	tf.keras.layers.ConvaD(
               filters=lowerCamelCase,   kernel_size=1,   strides=lowerCamelCase,   use_bias=lowerCamelCase,   name='convolution')
           _lowercase :							Optional[int]   	=	tf.keras.layers.BatchNormalization(epsilon=1E-5,   momentum=0.9,   name='normalization')




       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase = False) ->     tf.Tensor:




           """simple docstring"""

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






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   **lowerCamelCase) ->     Any:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.pooler(lowerCamelCase)
           for layer_module in self.attention:
               _lowercase :							Optional[int]   	=	layer_module(lowerCamelCase)
           _lowercase :							Optional[int]   	=	hidden_state * pooled
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase = 1,   **lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           super().__init__(**lowerCamelCase)
           _lowercase :							Optional[Any]   	=	in_channels != out_channels or stride != 1
           _lowercase :							List[Any]   	=	max(1,   out_channels // config.groups_width)
           _lowercase :							List[str]   	=	(
               TFRegNetShortCut(lowerCamelCase,   stride=lowerCamelCase,   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.
           _lowercase :							str   	=	[
               TFRegNetConvLayer(lowerCamelCase,   kernel_size=1,   activation=config.hidden_act,   name='layer.0'),
               TFRegNetConvLayer(
                   lowerCamelCase,   stride=lowerCamelCase,   groups=lowerCamelCase,   activation=config.hidden_act,   name='layer.1'),
               TFRegNetConvLayer(lowerCamelCase,   kernel_size=1,   activation=lowerCamelCase,   name='layer.2'),
           ]
           _lowercase :							Tuple   	=	ACTaFN[config.hidden_act]




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							str   	=	hidden_state
           for layer_module in self.layers:
               _lowercase :							List[Any]   	=	layer_module(lowerCamelCase)
           _lowercase :							Dict   	=	self.shortcut(lowerCamelCase)
           hidden_state += residual
           _lowercase :							Tuple   	=	self.activation(lowerCamelCase)
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase = 1,   **lowerCamelCase) ->     List[str]:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	hidden_state
           for layer_module in self.layers:
               _lowercase :							Any   	=	layer_module(lowerCamelCase)
           _lowercase :							Optional[int]   	=	self.shortcut(lowerCamelCase)
           hidden_state += residual
           _lowercase :							Optional[int]   	=	self.activation(lowerCamelCase)
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase = 2,   lowerCamelCase = 2,   **lowerCamelCase) ->     Tuple:




           """simple docstring"""

           super().__init__(**lowerCamelCase)

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




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Tuple:




           """simple docstring"""

           for layer_module in self.layers:
               _lowercase :							Tuple   	=	layer_module(lowerCamelCase)
           return hidden_state






class _lowerCamelCase(		tf.keras.layers.Layer     ):
       def __init__(      self,   lowerCamelCase,   **lowerCamelCase) ->     Any:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase = False,   lowerCamelCase = True) ->     TFBaseModelOutputWithNoAttention:




           """simple docstring"""

           _lowercase :							int   	=	() if output_hidden_states else None

           for stage_module in self.stages:
               if output_hidden_states:
                   _lowercase :							Optional[Any]   	=	hidden_states + (hidden_state,)

               _lowercase :							Tuple   	=	stage_module(lowerCamelCase)

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






@keras_serializable
class _lowerCamelCase(		tf.keras.layers.Layer     ):
       lowercase_				:			Dict									=    RegNetConfig
       def __init__(      self,   lowerCamelCase,   **lowerCamelCase) ->     str:




           """simple docstring"""

           super().__init__(**lowerCamelCase)
           _lowercase :							int   	=	config
           _lowercase :							List[Any]   	=	TFRegNetEmbeddings(lowerCamelCase,   name='embedder')
           _lowercase :							List[Any]   	=	TFRegNetEncoder(lowerCamelCase,   name='encoder')
           _lowercase :							Union[str, Any]   	=	tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCamelCase,   name='pooler')




       @unpack_inputs
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase = False,   ) ->     TFBaseModelOutputWithPoolingAndNoAttention:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	(
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           _lowercase :							Tuple   	=	return_dict if return_dict is not None else self.config.use_return_dict

           _lowercase :							Dict   	=	self.embedder(lowerCamelCase,   training=lowerCamelCase)

           _lowercase :							int   	=	self.encoder(
               lowerCamelCase,   output_hidden_states=lowerCamelCase,   return_dict=lowerCamelCase,   training=lowerCamelCase)

           _lowercase :							Optional[int]   	=	encoder_outputs[0]
           _lowercase :							List[Any]   	=	self.pooler(lowerCamelCase)

           # Change to NCHW output format have uniformity in the modules
           _lowercase :							Tuple   	=	tf.transpose(lowerCamelCase,   perm=(0, 3, 1, 2))
           _lowercase :							Tuple   	=	tf.transpose(lowerCamelCase,   perm=(0, 3, 1, 2))

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






class _lowerCamelCase(		_a     ):
       lowercase_				:			List[str]									=    RegNetConfig
       lowercase_				:			Optional[int]									=    """regnet"""
       lowercase_				:			int									=    """pixel_values"""
       @property
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

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


SCREAMING_SNAKE_CASE :   Union[str, Any]							      =				r"\n    Parameters:\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        config ([`RegNetConfig`]): 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"

SCREAMING_SNAKE_CASE :   Tuple							      =				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            [`ConveNextImageProcessor.__call__`] for details.\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"






@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top.""",				_a,				)
class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase,   *lowerCamelCase,   **lowerCamelCase) ->     Tuple:




           """simple docstring"""

           super().__init__(lowerCamelCase,   *lowerCamelCase,   **lowerCamelCase)
           _lowercase :							List[Any]   	=	TFRegNetMainLayer(lowerCamelCase,   name='regnet')




       @unpack_inputs
       @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,   )
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase=False,   ) ->     Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:




           """simple docstring"""

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

           _lowercase :							str   	=	self.regnet(
               pixel_values=lowerCamelCase,   output_hidden_states=lowerCamelCase,   return_dict=lowerCamelCase,   training=lowerCamelCase,   )
           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.
    """,				_a,				)
class _lowerCamelCase(		_a,				_a     ):
       def __init__(      self,   lowerCamelCase,   *lowerCamelCase,   **lowerCamelCase) ->     Any:




           """simple docstring"""

           super().__init__(lowerCamelCase,   *lowerCamelCase,   **lowerCamelCase)
           _lowercase :							Dict   	=	config.num_labels
           _lowercase :							Optional[int]   	=	TFRegNetMainLayer(lowerCamelCase,   name='regnet')
           # classification head
           _lowercase :							Tuple   	=	[
               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(lowerCamelCase)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT,   output_type=lowerCamelCase,   config_class=_CONFIG_FOR_DOC,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,   )
       def     UpperCamelCase  (      self,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase=False,   ) ->     Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:




           """simple docstring"""

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

           _lowercase :							Dict   	=	self.regnet(
               lowerCamelCase,   output_hidden_states=lowerCamelCase,   return_dict=lowerCamelCase,   training=lowerCamelCase)

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

           _lowercase :							Union[str, Any]   	=	self.classifier[0](lowerCamelCase)
           _lowercase :							List[Any]   	=	self.classifier[1](lowerCamelCase)

           _lowercase :							Optional[Any]   	=	None if labels is None else self.hf_compute_loss(labels=lowerCamelCase,   logits=lowerCamelCase)

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

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


