






from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


SCREAMING_SNAKE_CASE__   :      Tuple				=		logging.get_logger(__name__)


# General docstring
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		"""MobileNetV1Config"""

# Base docstring
SCREAMING_SNAKE_CASE__   :      int				=		"""google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE__   :      List[Any]				=		[1, 10_24, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE__   :      Tuple				=		"""google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		"""tabby, tabby cat"""


SCREAMING_SNAKE_CASE__   :      Tuple				=		[
    """google/mobilenet_v1_1.0_224""",
    """google/mobilenet_v1_0.75_192""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]

def   __lowercase       (			snake_case,	snake_case,	snake_case=None			):







				"""simple docstring"""






				__magic_name__		:str   =   {}

				if isinstance(snake_case,	snake_case			):
								__magic_name__		:List[str]   =   model.mobilenet_va
				else:
								__magic_name__		:Union[str, Any]   =   model

				__magic_name__		:List[Any]   =   '''MobilenetV1/Conv2d_0/'''
				__magic_name__		:Union[str, Any]   =   backbone.conv_stem.convolution.weight
				__magic_name__		:str   =   backbone.conv_stem.normalization.bias
				__magic_name__		:Tuple   =   backbone.conv_stem.normalization.weight
				__magic_name__		:str   =   backbone.conv_stem.normalization.running_mean
				__magic_name__		:List[Any]   =   backbone.conv_stem.normalization.running_var

				for i in range(1_3			):
								__magic_name__		:List[str]   =   i + 1
								__magic_name__		:int   =   i * 2

								__magic_name__		:Union[str, Any]   =   backbone.layer[pt_index]
								__magic_name__		:Any   =   f'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
								__magic_name__		:Optional[int]   =   pointer.convolution.weight
								__magic_name__		:Union[str, Any]   =   pointer.normalization.bias
								__magic_name__		:Dict   =   pointer.normalization.weight
								__magic_name__		:Dict   =   pointer.normalization.running_mean
								__magic_name__		:List[str]   =   pointer.normalization.running_var

								__magic_name__		:Tuple   =   backbone.layer[pt_index + 1]
								__magic_name__		:Any   =   f'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
								__magic_name__		:Tuple   =   pointer.convolution.weight
								__magic_name__		:int   =   pointer.normalization.bias
								__magic_name__		:int   =   pointer.normalization.weight
								__magic_name__		:Dict   =   pointer.normalization.running_mean
								__magic_name__		:int   =   pointer.normalization.running_var

				if isinstance(snake_case,	snake_case			):
								__magic_name__		:Optional[int]   =   '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
								__magic_name__		:Optional[int]   =   model.classifier.weight
								__magic_name__		:List[Any]   =   model.classifier.bias

				return tf_to_pt_map

def   __lowercase       (			snake_case,	snake_case,	snake_case			):







				"""simple docstring"""






				try:
								import numpy as np
								import tensorflow as tf
				except ImportError:
								logger.error(
								    '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
								    '''https://www.tensorflow.org/install/ for installation instructions.'''			)
								raise

				# Load weights from TF model
				__magic_name__		:Optional[Any]   =   tf.train.list_variables(snake_case			)
				__magic_name__		:Optional[Any]   =   {}
				for name, shape in init_vars:
								logger.info(f'''Loading TF weight {name} with shape {shape}'''			)
								__magic_name__		:Optional[Any]   =   tf.train.load_variable(snake_case,	snake_case			)
								__magic_name__		:str   =   array

				# Build TF to PyTorch weights loading map
				__magic_name__		:Any   =   _build_tf_to_pytorch_map(snake_case,	snake_case,	snake_case			)

				for name, pointer in tf_to_pt_map.items():
								logger.info(f'''Importing {name}'''			)
								if name not in tf_weights:
												logger.info(f'''{name} not in tf pre-trained weights, skipping'''			)
												continue

								__magic_name__		:List[Any]   =   tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('''Transposing depthwise'''			)
												__magic_name__		:Any   =   np.transpose(snake_case,	(2, 3, 0, 1)			)
								elif "weights" in name:
												logger.info('''Transposing'''			)
												if len(pointer.shape			) == 2:  # copying into linear layer
																__magic_name__		:Dict   =   array.squeeze().transpose()
												else:
																__magic_name__		:Optional[Any]   =   np.transpose(snake_case,	(3, 2, 0, 1)			)

								if pointer.shape != array.shape:
												raise ValueError(f'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched'''			)

								logger.info(f'''Initialize PyTorch weight {name} {array.shape}'''			)
								__magic_name__		:List[str]   =   torch.from_numpy(snake_case			)

								tf_weights.pop(snake_case,	snake_case			)
								tf_weights.pop(name + '''/RMSProp''',	snake_case			)
								tf_weights.pop(name + '''/RMSProp_1''',	snake_case			)
								tf_weights.pop(name + '''/ExponentialMovingAverage''',	snake_case			)

				logger.info(f'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys()			)}'''			)
				return model

def   __lowercase       (			snake_case,	snake_case			):







				"""simple docstring"""






				__magic_name__  ,					__magic_name__		:int   =   features.shape[-2:]
				__magic_name__  ,					__magic_name__		:Optional[Any]   =   conv_layer.stride
				__magic_name__  ,					__magic_name__		:Dict   =   conv_layer.kernel_size

				if in_height % stride_height == 0:
								__magic_name__		:Optional[int]   =   max(kernel_height - stride_height,	0			)
				else:
								__magic_name__		:List[Any]   =   max(kernel_height - (in_height % stride_height),	0			)

				if in_width % stride_width == 0:
								__magic_name__		:Any   =   max(kernel_width - stride_width,	0			)
				else:
								__magic_name__		:str   =   max(kernel_width - (in_width % stride_width),	0			)

				__magic_name__		:Tuple   =   pad_along_width // 2
				__magic_name__		:Any   =   pad_along_width - pad_left
				__magic_name__		:Union[str, Any]   =   pad_along_height // 2
				__magic_name__		:str   =   pad_along_height - pad_top

				__magic_name__		:Optional[Any]   =   (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(snake_case,	snake_case,	'''constant''',	0.0			)
class     lowerCamelCase_					(   nn.Module			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase = 1							,       __lowerCAmelCase = 1							,       __lowerCAmelCase = False							,       __lowerCAmelCase = True							,       __lowerCAmelCase = True							,       ):
								"""simple docstring"""
								super().__init__()
								__magic_name__		:List[str]   =   config

								if in_channels % groups != 0:
												raise ValueError(F'''Input channels ({in_channels}) are not divisible by {groups} groups.'''  )
								if out_channels % groups != 0:
												raise ValueError(F'''Output channels ({out_channels}) are not divisible by {groups} groups.'''  )

								__magic_name__		:Union[str, Any]   =   0 if config.tf_padding else int((kernel_size - 1) / 2  )

								__magic_name__		:Union[str, Any]   =   nn.Convad(
								    in_channels=__lowerCAmelCase							,       out_channels=__lowerCAmelCase							,       kernel_size=__lowerCAmelCase							,       stride=__lowerCAmelCase							,       padding=__lowerCAmelCase							,       groups=__lowerCAmelCase							,       bias=__lowerCAmelCase							,       padding_mode='''zeros'''							,       )

								if use_normalization:
												__magic_name__		:Tuple   =   nn.BatchNormad(
												    num_features=__lowerCAmelCase							,       eps=config.layer_norm_eps							,       momentum=0.9997							,       affine=__lowerCAmelCase							,       track_running_stats=__lowerCAmelCase							,       )
								else:
												__magic_name__		:Optional[Any]   =   None

								if use_activation:
												if isinstance(__lowerCAmelCase							,       __lowerCAmelCase  ):
																__magic_name__		:Optional[int]   =   ACTaFN[use_activation]
												elif isinstance(config.hidden_act							,       __lowerCAmelCase  ):
																__magic_name__		:Any   =   ACTaFN[config.hidden_act]
												else:
																__magic_name__		:Union[str, Any]   =   config.hidden_act
								else:
												__magic_name__		:List[Any]   =   None







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								if self.config.tf_padding:
												__magic_name__		:Optional[Any]   =   apply_tf_padding(__lowerCAmelCase							,       self.convolution  )
								__magic_name__		:str   =   self.convolution(__lowerCAmelCase  )
								if self.normalization is not None:
												__magic_name__		:Optional[int]   =   self.normalization(__lowerCAmelCase  )
								if self.activation is not None:
												__magic_name__		:int   =   self.activation(__lowerCAmelCase  )
								return features







class     lowerCamelCase_					(   lowerCamelCase			):
				a__       							=	MobileNetVaConfig
				a__       							=	load_tf_weights_in_mobilenet_va
				a__       							=	'''mobilenet_v1'''
				a__       							=	'''pixel_values'''
				a__       							=	False







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								if isinstance(__lowerCAmelCase							,       (nn.Linear, nn.Convad)  ):
												module.weight.data.normal_(mean=0.0							,       std=self.config.initializer_range  )
												if module.bias is not None:
																module.bias.data.zero_()
								elif isinstance(__lowerCAmelCase							,       nn.BatchNormad  ):
												module.bias.data.zero_()
												module.weight.data.fill_(1.0  )







SCREAMING_SNAKE_CASE__   :      str				=		r"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): 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 [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

SCREAMING_SNAKE_CASE__   :      str				=		r"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`MobileNetV1ImageProcessor.__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 MobileNetV1 model outputting raw hidden-states without any specific head on top.'''      ,					lowerCamelCase      ,					)
class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase = True  ):
								"""simple docstring"""
								super().__init__(__lowerCAmelCase  )
								__magic_name__		:Union[str, Any]   =   config

								__magic_name__		:Optional[Any]   =   3_2
								__magic_name__		:List[Any]   =   max(int(depth * config.depth_multiplier  )							,       config.min_depth  )

								__magic_name__		:List[Any]   =   MobileNetVaConvLayer(
								    __lowerCAmelCase							,       in_channels=config.num_channels							,       out_channels=__lowerCAmelCase							,       kernel_size=3							,       stride=2							,       )

								__magic_name__		:Dict   =   [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								__magic_name__		:Dict   =   nn.ModuleList()
								for i in range(1_3  ):
												__magic_name__		:Optional[int]   =   out_channels

												if strides[i] == 2 or i == 0:
																depth *= 2
																__magic_name__		:Union[str, Any]   =   max(int(depth * config.depth_multiplier  )							,       config.min_depth  )

												self.layer.append(
												    MobileNetVaConvLayer(
												        __lowerCAmelCase							,       in_channels=__lowerCAmelCase							,       out_channels=__lowerCAmelCase							,       kernel_size=3							,       stride=strides[i]							,       groups=__lowerCAmelCase							,       )  )

												self.layer.append(
												    MobileNetVaConvLayer(
												        __lowerCAmelCase							,       in_channels=__lowerCAmelCase							,       out_channels=__lowerCAmelCase							,       kernel_size=1							,       )  )

								__magic_name__		:Optional[Any]   =   nn.AdaptiveAvgPoolad((1, 1)  ) if add_pooling_layer else None

								# Initialize weights and apply final processing
								self.post_init()







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								raise NotImplementedError







				@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       A						(    self							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   (
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								__magic_name__		:Dict   =   return_dict if return_dict is not None else self.config.use_return_dict

								if pixel_values is None:
												raise ValueError('''You have to specify pixel_values'''  )

								__magic_name__		:str   =   self.conv_stem(__lowerCAmelCase  )

								__magic_name__		:Optional[int]   =   () if output_hidden_states else None

								for i, layer_module in enumerate(self.layer  ):
												__magic_name__		:int   =   layer_module(__lowerCAmelCase  )

												if output_hidden_states:
																__magic_name__		:List[str]   =   all_hidden_states + (hidden_states,)

								__magic_name__		:Tuple   =   hidden_states

								if self.pooler is not None:
												__magic_name__		:Optional[int]   =   torch.flatten(self.pooler(__lowerCAmelCase  )							,       start_dim=1  )
								else:
												__magic_name__		:Optional[int]   =   None

								if not return_dict:
												return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None  )

								return BaseModelOutputWithPoolingAndNoAttention(
								    last_hidden_state=__lowerCAmelCase							,       pooler_output=__lowerCAmelCase							,       hidden_states=__lowerCAmelCase							,       )







@add_start_docstrings(
    '''
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''      ,					lowerCamelCase      ,					)
class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								super().__init__(__lowerCAmelCase  )

								__magic_name__		:Optional[Any]   =   config.num_labels
								__magic_name__		:List[str]   =   MobileNetVaModel(__lowerCAmelCase  )

								__magic_name__		:Dict   =   self.mobilenet_va.layer[-1].convolution.out_channels

								# Classifier head
								__magic_name__		:int   =   nn.Dropout(config.classifier_dropout_prob							,       inplace=__lowerCAmelCase  )
								__magic_name__		:Union[str, Any]   =   nn.Linear(__lowerCAmelCase							,       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       A						(    self							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   return_dict if return_dict is not None else self.config.use_return_dict

								__magic_name__		:List[str]   =   self.mobilenet_va(__lowerCAmelCase							,       output_hidden_states=__lowerCAmelCase							,       return_dict=__lowerCAmelCase  )

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

								__magic_name__		:Any   =   self.classifier(self.dropout(__lowerCAmelCase  )  )

								__magic_name__		:Optional[int]   =   None
								if labels is not None:
												if self.config.problem_type is None:
																if self.num_labels == 1:
																				__magic_name__		:List[str]   =   '''regression'''
																elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																				__magic_name__		:Union[str, Any]   =   '''single_label_classification'''
																else:
																				__magic_name__		:Optional[Any]   =   '''multi_label_classification'''

												if self.config.problem_type == "regression":
																__magic_name__		:int   =   MSELoss()
																if self.num_labels == 1:
																				__magic_name__		:Dict   =   loss_fct(logits.squeeze()							,       labels.squeeze()  )
																else:
																				__magic_name__		:str   =   loss_fct(__lowerCAmelCase							,       __lowerCAmelCase  )
												elif self.config.problem_type == "single_label_classification":
																__magic_name__		:Optional[Any]   =   CrossEntropyLoss()
																__magic_name__		:int   =   loss_fct(logits.view(-1							,       self.num_labels  )							,       labels.view(-1  )  )
												elif self.config.problem_type == "multi_label_classification":
																__magic_name__		:Optional[Any]   =   BCEWithLogitsLoss()
																__magic_name__		:Union[str, Any]   =   loss_fct(__lowerCAmelCase							,       __lowerCAmelCase  )

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

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














from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available


SCREAMING_SNAKE_CASE__   :      Optional[int]				=		{"""tokenization_herbert""": ["""HerbertTokenizer"""]}

try:
					if not is_tokenizers_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		["""HerbertTokenizerFast"""]


if TYPE_CHECKING:
					from .tokenization_herbert import HerbertTokenizer

					try:
										if not is_tokenizers_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_herbert_fast import HerbertTokenizerFast

else:
					import sys

					SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






