


import argparse
import os

import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn

from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


if version.parse(nlp.__version__) != version.parse("0.8.3"):
 raise Exception("requires gluonnlp == 0.8.3")

if version.parse(mx.__version__) != version.parse("1.5.0"):
 raise Exception("requires mxnet == 1.5.0")

logging.set_verbosity_info()
SCREAMING_SNAKE_CASE :   int							      =				logging.get_logger(__name__)

SCREAMING_SNAKE_CASE :   Dict							      =				"The Nymphenburg Palace is a beautiful palace in Munich!"



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_				)					->		Dict:
    _lowercase :							Union[str, Any]   	=	{
        'attention_cell': 'multi_head',
        'num_layers': 4,
        'units': 1024,
        'hidden_size': 768,
        'max_length': 512,
        'num_heads': 8,
        'scaled': True,
        'dropout': 0.1,
        'use_residual': True,
        'embed_size': 1024,
        'embed_dropout': 0.1,
        'word_embed': None,
        'layer_norm_eps': 1e-5,
        'token_type_vocab_size': 2,
    }

    _lowercase :							str   	=	bort_4_8_768_1024_hparams

    # Let's construct the original Bort model here
    # Taken from official BERT implementation, see:
    # https://github.com/alexa/bort/blob/master/bort/bort.py
    _lowercase :							Union[str, Any]   	=	BERTEncoder(
        attention_cell=predefined_args['attention_cell']							,				num_layers=predefined_args['num_layers']							,				units=predefined_args['units']							,				hidden_size=predefined_args['hidden_size']							,				max_length=predefined_args['max_length']							,				num_heads=predefined_args['num_heads']							,				scaled=predefined_args['scaled']							,				dropout=predefined_args['dropout']							,				output_attention=lowerCamelCase_							,				output_all_encodings=lowerCamelCase_							,				use_residual=predefined_args['use_residual']							,				activation=predefined_args.get('activation'							,				'gelu'				)							,				layer_norm_eps=predefined_args.get('layer_norm_eps'							,				lowerCamelCase_				)							,				)

    # Vocab information needs to be fetched first
    # It's the same as RoBERTa, so RobertaTokenizer can be used later
    _lowercase :							Union[str, Any]   	=	'openwebtext_ccnews_stories_books_cased'

    # Specify download folder to Gluonnlp's vocab
    _lowercase :							str   	=	os.path.join(get_home_dir()							,				'models'				)
    _lowercase :							str   	=	_load_vocab(lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_							,				cls=lowerCamelCase_				)

    _lowercase :							Dict   	=	nlp.model.BERTModel(
        lowerCamelCase_							,				len(lowerCamelCase_				)							,				units=predefined_args['units']							,				embed_size=predefined_args['embed_size']							,				embed_dropout=predefined_args['embed_dropout']							,				word_embed=predefined_args['word_embed']							,				use_pooler=lowerCamelCase_							,				use_token_type_embed=lowerCamelCase_							,				token_type_vocab_size=predefined_args['token_type_vocab_size']							,				use_classifier=lowerCamelCase_							,				use_decoder=lowerCamelCase_							,				)

    original_bort.load_parameters(lowerCamelCase_							,				cast_dtype=lowerCamelCase_							,				ignore_extra=lowerCamelCase_				)
    _lowercase :							Optional[Any]   	=	original_bort._collect_params_with_prefix()

    # Build our config 🤗
    _lowercase :							List[Any]   	=	{
        'architectures': ['BertForMaskedLM'],
        'attention_probs_dropout_prob': predefined_args['dropout'],
        'hidden_act': 'gelu',
        'hidden_dropout_prob': predefined_args['dropout'],
        'hidden_size': predefined_args['embed_size'],
        'initializer_range': 0.02,
        'intermediate_size': predefined_args['hidden_size'],
        'layer_norm_eps': predefined_args['layer_norm_eps'],
        'max_position_embeddings': predefined_args['max_length'],
        'model_type': 'bort',
        'num_attention_heads': predefined_args['num_heads'],
        'num_hidden_layers': predefined_args['num_layers'],
        'pad_token_id': 1,  # 2 = BERT, 1 = RoBERTa
        'type_vocab_size': 1,  # 2 = BERT, 1 = RoBERTa
        'vocab_size': len(lowerCamelCase_				),
    }

    _lowercase :							Dict   	=	BertConfig.from_dict(lowerCamelCase_				)
    _lowercase :							str   	=	BertForMaskedLM(lowerCamelCase_				)
    hf_bort_model.eval()

    # Parameter mapping table (Gluonnlp to Transformers)
    # * denotes layer index
    #
    # | Gluon Parameter                                                | Transformers Parameter
    # | -------------------------------------------------------------- | ----------------------
    # | `encoder.layer_norm.beta`                                      | `bert.embeddings.LayerNorm.bias`
    # | `encoder.layer_norm.gamma`                                     | `bert.embeddings.LayerNorm.weight`
    # | `encoder.position_weight`                                      | `bert.embeddings.position_embeddings.weight`
    # | `word_embed.0.weight`                                          | `bert.embeddings.word_embeddings.weight`
    # | `encoder.transformer_cells.*.attention_cell.proj_key.bias`     | `bert.encoder.layer.*.attention.self.key.bias`
    # | `encoder.transformer_cells.*.attention_cell.proj_key.weight`   | `bert.encoder.layer.*.attention.self.key.weight`
    # | `encoder.transformer_cells.*.attention_cell.proj_query.bias`   | `bert.encoder.layer.*.attention.self.query.bias`
    # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
    # | `encoder.transformer_cells.*.attention_cell.proj_value.bias`   | `bert.encoder.layer.*.attention.self.value.bias`
    # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
    # | `encoder.transformer_cells.*.ffn.ffn_2.bias`                   | `bert.encoder.layer.*.attention.output.dense.bias`
    # | `encoder.transformer_cells.*.ffn.ffn_2.weight`                 | `bert.encoder.layer.*.attention.output.dense.weight`
    # | `encoder.transformer_cells.*.layer_norm.beta`                  | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
    # | `encoder.transformer_cells.*.layer_norm.gamma`                 | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
    # | `encoder.transformer_cells.*.ffn.ffn_1.bias`                   | `bert.encoder.layer.*.intermediate.dense.bias`
    # | `encoder.transformer_cells.*.ffn.ffn_1.weight`                 | `bert.encoder.layer.*.intermediate.dense.weight`
    # | `encoder.transformer_cells.*.ffn.layer_norm.beta`              | `bert.encoder.layer.*.output.LayerNorm.bias`
    # | `encoder.transformer_cells.*.ffn.layer_norm.gamma`             | `bert.encoder.layer.*.output.LayerNorm.weight`
    # | `encoder.transformer_cells.*.proj.bias`                        | `bert.encoder.layer.*.output.dense.bias`
    # | `encoder.transformer_cells.*.proj.weight`                      | `bert.encoder.layer.*.output.dense.weight`

    # Helper function to convert MXNET Arrays to PyTorch
    def to_torch(lowerCamelCase_				) -> nn.Parameter:
        return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy()				)				)

    # Check param shapes and map new HF param back
    def check_and_map_params(lowerCamelCase_							,				lowerCamelCase_				):
        _lowercase :							List[str]   	=	hf_param.shape

        _lowercase :							int   	=	to_torch(params[gluon_param]				)
        _lowercase :							Optional[Any]   	=	gluon_param.shape

        assert (
            shape_hf == shape_gluon
        ), F'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'''

        return gluon_param

    _lowercase :							Union[str, Any]   	=	check_and_map_params(
        hf_bort_model.bert.embeddings.word_embeddings.weight							,				'word_embed.0.weight'				)
    _lowercase :							int   	=	check_and_map_params(
        hf_bort_model.bert.embeddings.position_embeddings.weight							,				'encoder.position_weight'				)
    _lowercase :							List[str]   	=	check_and_map_params(
        hf_bort_model.bert.embeddings.LayerNorm.bias							,				'encoder.layer_norm.beta'				)
    _lowercase :							List[str]   	=	check_and_map_params(
        hf_bort_model.bert.embeddings.LayerNorm.weight							,				'encoder.layer_norm.gamma'				)

    # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
    _lowercase :							Any   	=	torch.zeros_like(
        hf_bort_model.bert.embeddings.token_type_embeddings.weight.data				)

    for i in range(hf_bort_config.num_hidden_layers				):
        _lowercase :							BertLayer   	=	hf_bort_model.bert.encoder.layer[i]

        # self attention
        _lowercase :							BertSelfAttention   	=	layer.attention.self

        _lowercase :							Dict   	=	check_and_map_params(
            self_attn.key.bias.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias'''				)

        _lowercase :							Tuple   	=	check_and_map_params(
            self_attn.key.weight.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight'''				)
        _lowercase :							List[str]   	=	check_and_map_params(
            self_attn.query.bias.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias'''				)
        _lowercase :							Optional[Any]   	=	check_and_map_params(
            self_attn.query.weight.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight'''				)
        _lowercase :							str   	=	check_and_map_params(
            self_attn.value.bias.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias'''				)
        _lowercase :							Optional[Any]   	=	check_and_map_params(
            self_attn.value.weight.data							,				F'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight'''				)

        # self attention output
        _lowercase :							BertSelfOutput   	=	layer.attention.output

        _lowercase :							List[Any]   	=	check_and_map_params(
            self_output.dense.bias							,				F'''encoder.transformer_cells.{i}.proj.bias'''				)
        _lowercase :							Optional[Any]   	=	check_and_map_params(
            self_output.dense.weight							,				F'''encoder.transformer_cells.{i}.proj.weight'''				)
        _lowercase :							Union[str, Any]   	=	check_and_map_params(
            self_output.LayerNorm.bias							,				F'''encoder.transformer_cells.{i}.layer_norm.beta'''				)
        _lowercase :							Union[str, Any]   	=	check_and_map_params(
            self_output.LayerNorm.weight							,				F'''encoder.transformer_cells.{i}.layer_norm.gamma'''				)

        # intermediate
        _lowercase :							BertIntermediate   	=	layer.intermediate

        _lowercase :							str   	=	check_and_map_params(
            intermediate.dense.bias							,				F'''encoder.transformer_cells.{i}.ffn.ffn_1.bias'''				)
        _lowercase :							Optional[Any]   	=	check_and_map_params(
            intermediate.dense.weight							,				F'''encoder.transformer_cells.{i}.ffn.ffn_1.weight'''				)

        # output
        _lowercase :							BertOutput   	=	layer.output

        _lowercase :							Any   	=	check_and_map_params(
            bert_output.dense.bias							,				F'''encoder.transformer_cells.{i}.ffn.ffn_2.bias'''				)
        _lowercase :							Optional[int]   	=	check_and_map_params(
            bert_output.dense.weight							,				F'''encoder.transformer_cells.{i}.ffn.ffn_2.weight'''				)
        _lowercase :							Any   	=	check_and_map_params(
            bert_output.LayerNorm.bias							,				F'''encoder.transformer_cells.{i}.ffn.layer_norm.beta'''				)
        _lowercase :							str   	=	check_and_map_params(
            bert_output.LayerNorm.weight							,				F'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma'''				)

    # Save space and energy 🎄
    hf_bort_model.half()

    # Compare output of both models
    _lowercase :							int   	=	RobertaTokenizer.from_pretrained('roberta-base'				)

    _lowercase :							Union[str, Any]   	=	tokenizer.encode_plus(lowerCamelCase_				)['input_ids']

    # Get gluon output
    _lowercase :							int   	=	mx.nd.array([input_ids]				)
    _lowercase :							List[str]   	=	original_bort(inputs=lowerCamelCase_							,				token_types=[]				)

    # Get Transformer output (save and reload model again)
    hf_bort_model.save_pretrained(lowerCamelCase_				)
    _lowercase :							Dict   	=	BertModel.from_pretrained(lowerCamelCase_				)
    hf_bort_model.eval()

    _lowercase :							Dict   	=	tokenizer.encode_plus(lowerCamelCase_							,				return_tensors='pt'				)
    _lowercase :							Optional[Any]   	=	hf_bort_model(**lowerCamelCase_				)[0]

    _lowercase :							str   	=	output_gluon[0].asnumpy()
    _lowercase :							str   	=	output_hf[0].detach().numpy()

    _lowercase :							str   	=	np.max(np.abs(hf_layer - gluon_layer				)				).item()
    _lowercase :							Dict   	=	np.allclose(lowerCamelCase_							,				lowerCamelCase_							,				atol=1e-3				)

    if success:
        print('✔️ Both model do output the same tensors'				)
    else:
        print('❌ Both model do **NOT** output the same tensors'				)
        print('Absolute difference is:'							,				lowerCamelCase_				)


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE :   Optional[Any]							      =				argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--bort_checkpoint_path", default=None, type=str, required=True, help="Path the official Bort params file."
 )
 parser.add_argument(
     "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
 )
 SCREAMING_SNAKE_CASE :   Optional[int]							      =				parser.parse_args()
 convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)






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)


