




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


a_				:    Tuple										=     logging.get_logger(__name__)

# General docstring
a_				:    Optional[int]										=     '''RegNetConfig'''

# Base docstring
a_				:    Union[str, Any]										=     '''facebook/regnet-y-040'''
a_				:    Optional[Any]										=     [1, 10_88, 7, 7]

# Image classification docstring
a_				:    Any										=     '''facebook/regnet-y-040'''
a_				:    List[Any]										=     '''tabby, tabby cat'''

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

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




					'''simple docstring'''


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





					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	int	       =				self.convolution(self.padding(__a     )     )
								__lowerCamelCase					:	List[str]	       =				self.normalization(__a     )
								__lowerCamelCase					:	List[str]	       =				self.activation(__a     )
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	int	       =				config.num_channels
								__lowerCamelCase					:	str	       =				TFRegNetConvLayer(
								    out_channels=config.embedding_size						,	kernel_size=3						,	stride=2						,	activation=config.hidden_act						,	name='embedder'						,	)





					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	Optional[int]	       =				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)
								__lowerCamelCase					:	List[str]	       =				tf.transpose(__a						,	perm=(0, 2, 3, 1)     )
								__lowerCamelCase					:	Optional[Any]	       =				self.embedder(__a     )
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a = 2						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	str	       =				tf.keras.layers.ConvaD(
								    filters=__a						,	kernel_size=1						,	strides=__a						,	use_bias=__a						,	name='convolution'     )
								__lowerCamelCase					:	Union[str, Any]	       =				tf.keras.layers.BatchNormalization(epsilon=1E-5						,	momentum=0.9						,	name='normalization'     )





					def     snake_case_				(    self						,	__a						,	__a = False     ):
								return self.normalization(self.convolution(__a     )						,	training=__a     )



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	List[str]	       =				tf.keras.layers.GlobalAveragePoolingaD(keepdims=__a						,	name='pooler'     )
								__lowerCamelCase					:	int	       =				[
								    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     snake_case_				(    self						,	__a     ):
								# [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
								__lowerCamelCase					:	str	       =				self.pooler(__a     )
								for layer_module in self.attention:
											__lowerCamelCase					:	int	       =				layer_module(__a     )
								__lowerCamelCase					:	List[Any]	       =				hidden_state * pooled
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a						,	__a						,	__a = 1						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	List[str]	       =				in_channels != out_channels or stride != 1
								__lowerCamelCase					:	Optional[Any]	       =				max(1						,	out_channels // config.groups_width     )
								__lowerCamelCase					:	Any	       =				(
								    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.
								__lowerCamelCase					:	Optional[Any]	       =				[
								    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'     ),
								]
								__lowerCamelCase					:	Optional[Any]	       =				ACTaFN[config.hidden_act]





					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	List[str]	       =				hidden_state
								for layer_module in self.layers:
											__lowerCamelCase					:	Union[str, Any]	       =				layer_module(__a     )
								__lowerCamelCase					:	Optional[Any]	       =				self.shortcut(__a     )
								hidden_state += residual
								__lowerCamelCase					:	Optional[int]	       =				self.activation(__a     )
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a						,	__a						,	__a = 1						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	int	       =				in_channels != out_channels or stride != 1
								__lowerCamelCase					:	Dict	       =				max(1						,	out_channels // config.groups_width     )
								__lowerCamelCase					:	Union[str, Any]	       =				(
								    TFRegNetShortCut(__a						,	stride=__a						,	name='shortcut'     )
								    if should_apply_shortcut
								    else tf.keras.layers.Activation('linear'						,	name='shortcut'     )
								)
								__lowerCamelCase					:	Optional[Any]	       =				[
								    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'     ),
								]
								__lowerCamelCase					:	Union[str, Any]	       =				ACTaFN[config.hidden_act]





					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	Dict	       =				hidden_state
								for layer_module in self.layers:
											__lowerCamelCase					:	List[Any]	       =				layer_module(__a     )
								__lowerCamelCase					:	Any	       =				self.shortcut(__a     )
								hidden_state += residual
								__lowerCamelCase					:	int	       =				self.activation(__a     )
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a						,	__a						,	__a = 2						,	__a = 2						,	**__a     ):
								super().__init__(**__a     )

								__lowerCamelCase					:	Optional[int]	       =				TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer
								__lowerCamelCase					:	Optional[Any]	       =				[
								    # 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     snake_case_				(    self						,	__a     ):
								for layer_module in self.layers:
											__lowerCamelCase					:	List[str]	       =				layer_module(__a     )
								return hidden_state



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




					'''simple docstring'''


					def __init__(    self						,	__a						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	Dict	       =				[]
								# 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'						,	)     )
								__lowerCamelCase					:	Optional[Any]	       =				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     snake_case_				(    self						,	__a						,	__a = False						,	__a = True     ):
								__lowerCamelCase					:	str	       =				() if output_hidden_states else None

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

											__lowerCamelCase					:	str	       =				stage_module(__a     )

								if output_hidden_states:
											__lowerCamelCase					:	Dict	       =				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 __lowercase(      tf.keras.layers.Layer				):




					'''simple docstring'''


					__a						:						int     		= RegNetConfig
					def __init__(    self						,	__a						,	**__a     ):
								super().__init__(**__a     )
								__lowerCamelCase					:	str	       =				config
								__lowerCamelCase					:	Dict	       =				TFRegNetEmbeddings(__a						,	name='embedder'     )
								__lowerCamelCase					:	Union[str, Any]	       =				TFRegNetEncoder(__a						,	name='encoder'     )
								__lowerCamelCase					:	Tuple	       =				tf.keras.layers.GlobalAveragePoolingaD(keepdims=__a						,	name='pooler'     )





					@unpack_inputs
					def     snake_case_				(    self						,	__a						,	__a = None						,	__a = None						,	__a = False						,	):
								__lowerCamelCase					:	Any	       =				(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								__lowerCamelCase					:	Optional[int]	       =				return_dict if return_dict is not None else self.config.use_return_dict

								__lowerCamelCase					:	Tuple	       =				self.embedder(__a						,	training=__a     )

								__lowerCamelCase					:	Optional[Any]	       =				self.encoder(
								    __a						,	output_hidden_states=__a						,	return_dict=__a						,	training=__a     )

								__lowerCamelCase					:	Optional[Any]	       =				encoder_outputs[0]
								__lowerCamelCase					:	Tuple	       =				self.pooler(__a     )

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

								# Change the other hidden state outputs to NCHW as well
								if output_hidden_states:
											__lowerCamelCase					:	Optional[Any]	       =				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 __lowercase(      lowercase__				):




					'''simple docstring'''


					__a						:						Optional[int]     		= RegNetConfig
					__a						:						Optional[int]     		= 'regnet'
					__a						:						Optional[Any]     		= 'pixel_values'
					@property
					def     snake_case_				(    self     ):
								return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224)						,	dtype=tf.floataa     )}



a_				:    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.
'''

a_				:    List[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
            [`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.'	,	lowercase__	,	)
class __lowercase(      lowercase__				):




					'''simple docstring'''


					def __init__(    self						,	__a						,	*__a						,	**__a     ):
								super().__init__(__a						,	*__a						,	**__a     )
								__lowerCamelCase					:	Optional[int]	       =				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     snake_case_				(    self						,	__a						,	__a = None						,	__a = None						,	__a=False						,	):
								__lowerCamelCase					:	Optional[int]	       =				(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								__lowerCamelCase					:	Optional[Any]	       =				return_dict if return_dict is not None else self.config.use_return_dict

								__lowerCamelCase					:	List[str]	       =				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(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '	,	lowercase__	,	)
class __lowercase(      lowercase__	,	lowercase__				):




					'''simple docstring'''


					def __init__(    self						,	__a						,	*__a						,	**__a     ):
								super().__init__(__a						,	*__a						,	**__a     )
								__lowerCamelCase					:	List[Any]	       =				config.num_labels
								__lowerCamelCase					:	str	       =				TFRegNetMainLayer(__a						,	name='regnet'     )
								# classification head
								__lowerCamelCase					:	List[str]	       =				[
								    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     snake_case_				(    self						,	__a = None						,	__a = None						,	__a = None						,	__a = None						,	__a=False						,	):
								__lowerCamelCase					:	int	       =				(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								__lowerCamelCase					:	List[Any]	       =				return_dict if return_dict is not None else self.config.use_return_dict

								__lowerCamelCase					:	Optional[int]	       =				self.regnet(
								    __a						,	output_hidden_states=__a						,	return_dict=__a						,	training=__a     )

								__lowerCamelCase					:	Optional[int]	       =				outputs.pooler_output if return_dict else outputs[1]

								__lowerCamelCase					:	List[Any]	       =				self.classifier[0](__a     )
								__lowerCamelCase					:	Optional[Any]	       =				self.classifier[1](__a     )

								__lowerCamelCase					:	List[str]	       =				None if labels is None else self.hf_compute_loss(labels=__a						,	logits=__a     )

								if not return_dict:
											__lowerCamelCase					:	Optional[int]	       =				(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 os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
					from .tokenization_barthez import BarthezTokenizer
else:
					a_				:    List[str]										=     None

a_				:    Any										=     logging.get_logger(__name__)

a_				:    List[Any]										=     {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}

a_				:    int										=     {
    '''vocab_file''': {
        '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''',
        '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''',
        '''moussaKam/barthez-orangesum-title''': (
            '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'''
        ),
    },
    '''tokenizer_file''': {
        '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json''',
        '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json''',
        '''moussaKam/barthez-orangesum-title''': (
            '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json'''
        ),
    },
}

a_				:    Any										=     {
    '''moussaKam/mbarthez''': 10_24,
    '''moussaKam/barthez''': 10_24,
    '''moussaKam/barthez-orangesum-title''': 10_24,
}

a_				:    Union[str, Any]										=     '''▁'''

class __lowercase(      lowercase__				):




					'''simple docstring'''


					__a						:						Optional[Any]     		= VOCAB_FILES_NAMES
					__a						:						Optional[int]     		= PRETRAINED_VOCAB_FILES_MAP
					__a						:						List[str]     		= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					__a						:						Union[str, Any]     		= ['input_ids', 'attention_mask']
					__a						:						Optional[Any]     		= BarthezTokenizer
					def __init__(    self						,	__a=None						,	__a=None						,	__a="<s>"						,	__a="</s>"						,	__a="</s>"						,	__a="<s>"						,	__a="<unk>"						,	__a="<pad>"						,	__a="<mask>"						,	**__a						,	):
								# Mask token behave like a normal word, i.e. include the space before it
								__lowerCamelCase					:	Optional[Any]	       =				AddedToken(__a						,	lstrip=__a						,	rstrip=__a     ) if isinstance(__a						,	__a     ) else mask_token

								super().__init__(
								    __a						,	tokenizer_file=__a						,	bos_token=__a						,	eos_token=__a						,	unk_token=__a						,	sep_token=__a						,	cls_token=__a						,	pad_token=__a						,	mask_token=__a						,	**__a						,	)

								__lowerCamelCase					:	Tuple	       =				vocab_file
								__lowerCamelCase					:	List[str]	       =				False if not self.vocab_file else True
					def     snake_case_				(    self						,	__a						,	__a = None     ):

								if token_ids_a is None:
											return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
								__lowerCamelCase					:	Optional[Any]	       =				[self.cls_token_id]
								__lowerCamelCase					:	Dict	       =				[self.sep_token_id]
								return cls + token_ids_a + sep + sep + token_ids_a + sep
					def     snake_case_				(    self						,	__a						,	__a = None     ):
								__lowerCamelCase					:	Optional[int]	       =				[self.sep_token_id]
								__lowerCamelCase					:	int	       =				[self.cls_token_id]

								if token_ids_a is None:
											return len(cls + token_ids_a + sep     ) * [0]
								return len(cls + token_ids_a + sep + sep + token_ids_a + sep     ) * [0]





					def     snake_case_				(    self						,	__a						,	__a = None     ):
								if not self.can_save_slow_tokenizer:
											raise ValueError(
											    'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
											    'tokenizer.'     )

								if not os.path.isdir(__a     ):
											logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''     )
											return
								__lowerCamelCase					:	List[Any]	       =				os.path.join(
								    __a						,	(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']     )

								if os.path.abspath(self.vocab_file     ) != os.path.abspath(__a     ):
											copyfile(self.vocab_file						,	__a     )

								return (out_vocab_file,)



