





'''simple docstring'''

from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowercase__		:     Dict			=							logging.get_logger(__name__)

# General docstring
lowercase__		:     Optional[Any]			=							'RegNetConfig'

# Base docstring
lowercase__		:     Optional[int]			=							'facebook/regnet-y-040'
lowercase__		:     Tuple			=							[1, 10_88, 7, 7]

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

lowercase__		:     Dict			=							[
    'facebook/regnet-y-040',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]
class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





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

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			nn.Convad(
                lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=lowerCAmelCase__			,					stride=lowerCAmelCase__			,					padding=kernel_size // 2			,					groups=lowerCAmelCase__			,					bias=lowerCAmelCase__			,					)
            _UpperCamelCase							       =			nn.BatchNormad(lowerCAmelCase__	)
            _UpperCamelCase							       =			ACTaFN[activation] if activation is not None else nn.Identity()







       def snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						Optional[int]	)       ->	List[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.convolution(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.normalization(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.activation(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						List[Any]			,					lowerCAmelCase__  :						RegNetConfig	)       ->	int:

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			RegNetConvLayer(
                config.num_channels			,					config.embedding_size			,					kernel_size=3			,					stride=2			,					activation=config.hidden_act	)
            _UpperCamelCase							       =			config.num_channels







       def snake_case__		(				self  :						Optional[Any]			,					lowerCAmelCase__  :						List[str]	)       ->	Any:

            '''simple docstring'''




            _UpperCamelCase							       =			pixel_values.shape[1]
            if 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.'''	)
            _UpperCamelCase							       =			self.embedder(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						int			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int = 2	)       ->	List[str]:

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			nn.Convad(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1			,					stride=lowerCAmelCase__			,					bias=lowerCAmelCase__	)
            _UpperCamelCase							       =			nn.BatchNormad(lowerCAmelCase__	)







       def snake_case__		(				self  :						Optional[int]			,					lowerCAmelCase__  :						Tensor	)       ->	Tensor:

            '''simple docstring'''




            _UpperCamelCase							       =			self.convolution(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.normalization(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						Dict			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int	)       ->	Tuple:

            '''simple docstring'''




            super().__init__()

            _UpperCamelCase							       =			nn.AdaptiveAvgPoolad((1, 1)	)
            _UpperCamelCase							       =			nn.Sequential(
                nn.Convad(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1	)			,					nn.ReLU()			,					nn.Convad(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1	)			,					nn.Sigmoid()			,					)







       def snake_case__		(				self  :						str			,					lowerCAmelCase__  :						Optional[int]	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.pooler(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.attention(lowerCAmelCase__	)
            _UpperCamelCase							       =			hidden_state * attention
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





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

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			in_channels != out_channels or stride != 1
            _UpperCamelCase							       =			max(1			,					out_channels // config.groups_width	)
            _UpperCamelCase							       =			(
                RegNetShortCut(lowerCAmelCase__			,					lowerCAmelCase__			,					stride=lowerCAmelCase__	) if should_apply_shortcut else nn.Identity()
            )
            _UpperCamelCase							       =			nn.Sequential(
                RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1			,					activation=config.hidden_act	)			,					RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					stride=lowerCAmelCase__			,					groups=lowerCAmelCase__			,					activation=config.hidden_act	)			,					RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1			,					activation=lowerCAmelCase__	)			,					)
            _UpperCamelCase							       =			ACTaFN[config.hidden_act]







       def snake_case__		(				self  :						Optional[int]			,					lowerCAmelCase__  :						List[str]	)       ->	Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			hidden_state
            _UpperCamelCase							       =			self.layer(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.shortcut(lowerCAmelCase__	)
            hidden_state += residual
            _UpperCamelCase							       =			self.activation(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						int			,					lowerCAmelCase__  :						RegNetConfig			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int = 1	)       ->	str:

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			in_channels != out_channels or stride != 1
            _UpperCamelCase							       =			max(1			,					out_channels // config.groups_width	)
            _UpperCamelCase							       =			(
                RegNetShortCut(lowerCAmelCase__			,					lowerCAmelCase__			,					stride=lowerCAmelCase__	) if should_apply_shortcut else nn.Identity()
            )
            _UpperCamelCase							       =			nn.Sequential(
                RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1			,					activation=config.hidden_act	)			,					RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					stride=lowerCAmelCase__			,					groups=lowerCAmelCase__			,					activation=config.hidden_act	)			,					RegNetSELayer(lowerCAmelCase__			,					reduced_channels=int(round(in_channels / 4	)	)	)			,					RegNetConvLayer(lowerCAmelCase__			,					lowerCAmelCase__			,					kernel_size=1			,					activation=lowerCAmelCase__	)			,					)
            _UpperCamelCase							       =			ACTaFN[config.hidden_act]







       def snake_case__		(				self  :						Dict			,					lowerCAmelCase__  :						str	)       ->	List[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			hidden_state
            _UpperCamelCase							       =			self.layer(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.shortcut(lowerCAmelCase__	)
            hidden_state += residual
            _UpperCamelCase							       =			self.activation(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						Union[str, Any]			,					lowerCAmelCase__  :						RegNetConfig			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int = 2			,					lowerCAmelCase__  :						int = 2			,					)       ->	Any:

            '''simple docstring'''




            super().__init__()

            _UpperCamelCase							       =			RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

            _UpperCamelCase							       =			nn.Sequential(
                # downsampling is done in the first layer with stride of 2
                layer(
                    lowerCAmelCase__			,					lowerCAmelCase__			,					lowerCAmelCase__			,					stride=lowerCAmelCase__			,					)			,					*[layer(lowerCAmelCase__			,					lowerCAmelCase__			,					lowerCAmelCase__	) for _ in range(depth - 1	)]			,					)







       def snake_case__		(				self  :						Dict			,					lowerCAmelCase__  :						List[str]	)       ->	List[str]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.layers(lowerCAmelCase__	)
            return hidden_state

class 							__lowerCAmelCase	(       nn.Module					):






       """simple docstring"""





       def __init__(				self  :						Optional[Any]			,					lowerCAmelCase__  :						RegNetConfig	)       ->	Dict:

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			nn.ModuleList([]	)
            # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
            self.stages.append(
                RegNetStage(
                    lowerCAmelCase__			,					config.embedding_size			,					config.hidden_sizes[0]			,					stride=2 if config.downsample_in_first_stage else 1			,					depth=config.depths[0]			,					)	)
            _UpperCamelCase							       =			zip(config.hidden_sizes			,					config.hidden_sizes[1:]	)
            for (in_channels, out_channels), depth in zip(lowerCAmelCase__			,					config.depths[1:]	):
                 self.stages.append(RegNetStage(lowerCAmelCase__			,					lowerCAmelCase__			,					lowerCAmelCase__			,					depth=lowerCAmelCase__	)	)







       def snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						Tensor			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = True	)       ->	BaseModelOutputWithNoAttention:

            '''simple docstring'''




            _UpperCamelCase							       =			() if output_hidden_states else None

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

                 _UpperCamelCase							       =			stage_module(lowerCAmelCase__	)

            if output_hidden_states:
                 _UpperCamelCase							       =			hidden_states + (hidden_state,)

            if not return_dict:
                 return tuple(v for v in [hidden_state, hidden_states] if v is not None	)

            return BaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase__			,					hidden_states=lowerCAmelCase__	)

class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""
       _snake_case      :	Optional[int]									=       RegNetConfig
       _snake_case      :	int									=       'regnet'
       _snake_case      :	Tuple									=       'pixel_values'
       _snake_case      :	List[Any]									=       True





       def snake_case__		(				self  :						str			,					lowerCAmelCase__  :						Tuple	)       ->	Union[str, Any]:

            '''simple docstring'''




            if isinstance(lowerCAmelCase__			,					nn.Convad	):
                 nn.init.kaiming_normal_(module.weight			,					mode='''fan_out'''			,					nonlinearity='''relu'''	)
            elif isinstance(lowerCAmelCase__			,					(nn.BatchNormad, nn.GroupNorm)	):
                 nn.init.constant_(module.weight			,					1	)
                 nn.init.constant_(module.bias			,					0	)







       def snake_case__		(				self  :						Optional[int]			,					lowerCAmelCase__  :						Tuple			,					lowerCAmelCase__  :						Optional[Any]=False	)       ->	Tuple:

            '''simple docstring'''




            if isinstance(lowerCAmelCase__			,					lowerCAmelCase__	):
                 _UpperCamelCase							       =			value

lowercase__		:     Optional[Any]			=							R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\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 [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

lowercase__		:     str			=							R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\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 [`~file_utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'		,		__magic_name__		,		)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""





       def __init__(				self  :						str			,					lowerCAmelCase__  :						Optional[int]	)       ->	int:

            '''simple docstring'''




            super().__init__(lowerCAmelCase__	)
            _UpperCamelCase							       =			config
            _UpperCamelCase							       =			RegNetEmbeddings(lowerCAmelCase__	)
            _UpperCamelCase							       =			RegNetEncoder(lowerCAmelCase__	)
            _UpperCamelCase							       =			nn.AdaptiveAvgPoolad((1, 1)	)
            # Initialize weights and apply final processing
            self.post_init()







       @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 snake_case__		(				self  :						Any			,					lowerCAmelCase__  :						Tensor			,					lowerCAmelCase__  :						Optional[bool] = None			,					lowerCAmelCase__  :						Optional[bool] = None	)       ->	BaseModelOutputWithPoolingAndNoAttention:

            '''simple docstring'''




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

            _UpperCamelCase							       =			self.embedder(lowerCAmelCase__	)

            _UpperCamelCase							       =			self.encoder(
                lowerCAmelCase__			,					output_hidden_states=lowerCAmelCase__			,					return_dict=lowerCAmelCase__	)

            _UpperCamelCase							       =			encoder_outputs[0]

            _UpperCamelCase							       =			self.pooler(lowerCAmelCase__	)

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

            return BaseModelOutputWithPoolingAndNoAttention(
                last_hidden_state=lowerCAmelCase__			,					pooler_output=lowerCAmelCase__			,					hidden_states=encoder_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    '		,		__magic_name__		,		)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""





       def __init__(				self  :						Union[str, Any]			,					lowerCAmelCase__  :						Any	)       ->	Tuple:

            '''simple docstring'''




            super().__init__(lowerCAmelCase__	)
            _UpperCamelCase							       =			config.num_labels
            _UpperCamelCase							       =			RegNetModel(lowerCAmelCase__	)
            # classification head
            _UpperCamelCase							       =			nn.Sequential(
                nn.Flatten()			,					nn.Linear(config.hidden_sizes[-1]			,					config.num_labels	) if config.num_labels > 0 else nn.Identity()			,					)
            # initialize weights and apply final processing
            self.post_init()







       @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 snake_case__		(				self  :						Optional[Any]			,					lowerCAmelCase__  :						Optional[torch.FloatTensor] = None			,					lowerCAmelCase__  :						Optional[torch.LongTensor] = None			,					lowerCAmelCase__  :						Optional[bool] = None			,					lowerCAmelCase__  :						Optional[bool] = None			,					)       ->	ImageClassifierOutputWithNoAttention:

            '''simple docstring'''




            _UpperCamelCase							       =			return_dict if return_dict is not None else self.config.use_return_dict

            _UpperCamelCase							       =			self.regnet(lowerCAmelCase__			,					output_hidden_states=lowerCAmelCase__			,					return_dict=lowerCAmelCase__	)

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

            _UpperCamelCase							       =			self.classifier(lowerCAmelCase__	)

            _UpperCamelCase							       =			None

            if labels is not None:
                 if self.config.problem_type is None:
                      if self.num_labels == 1:
                           _UpperCamelCase							       =			'''regression'''
                      elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                           _UpperCamelCase							       =			'''single_label_classification'''
                      else:
                           _UpperCamelCase							       =			'''multi_label_classification'''
                 if self.config.problem_type == "regression":
                      _UpperCamelCase							       =			MSELoss()
                      if self.num_labels == 1:
                           _UpperCamelCase							       =			loss_fct(logits.squeeze()			,					labels.squeeze()	)
                      else:
                           _UpperCamelCase							       =			loss_fct(lowerCAmelCase__			,					lowerCAmelCase__	)
                 elif self.config.problem_type == "single_label_classification":
                      _UpperCamelCase							       =			CrossEntropyLoss()
                      _UpperCamelCase							       =			loss_fct(logits.view(-1			,					self.num_labels	)			,					labels.view(-1	)	)
                 elif self.config.problem_type == "multi_label_classification":
                      _UpperCamelCase							       =			BCEWithLogitsLoss()
                      _UpperCamelCase							       =			loss_fct(lowerCAmelCase__			,					lowerCAmelCase__	)

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

            return ImageClassifierOutputWithNoAttention(loss=lowerCAmelCase__			,					logits=lowerCAmelCase__			,					hidden_states=outputs.hidden_states	)








"""simple docstring"""

import argparse

import torch

from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging


logging.set_verbosity_info()
def  __snake_case							(	__A      :						Union[str, Any]							,		__A      :						Any							,		__A      :						Dict     )     ->       Tuple:






				'''simple docstring'''
				# Initialise PyTorch model
				SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     BertConfig.from_json_file(__A     )
				print(F"""Building PyTorch model from configuration: {config}"""     )
				SCREAMING_SNAKE_CASE						:							List[Any]							=     BertForPreTraining(__A     )

				# Load weights from tf checkpoint
				load_tf_weights_in_bert(__A							,		__A							,		__A     )

				# Save pytorch-model
				print(F"""Save PyTorch model to {pytorch_dump_path}"""     )
				torch.save(model.state_dict()							,		__A     )


if __name__ == "__main__":
							A_						:    int				=      argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
							)
							parser.add_argument(
							    '--bert_config_file',
							    default=None,
							    type=str,
							    required=True,
							    help=(
							        'The config json file corresponding to the pre-trained BERT model. \n'
							        'This specifies the model architecture.'
							    ),
							)
							parser.add_argument(
							    '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
							)
							A_						:    str				=      parser.parse_args()
							convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)





