


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


_lowercase       		= logging.get_logger(__name__)


# General docstring
_lowercase       		= 'MobileNetV1Config'

# Base docstring
_lowercase       		= 'google/mobilenet_v1_1.0_224'
_lowercase       		= [1, 1024, 7, 7]

# Image classification docstring
_lowercase       		= 'google/mobilenet_v1_1.0_224'
_lowercase       		= 'tabby, tabby cat'


_lowercase       		= [
    '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   UpperCamelCase			(      snake_case__						,  snake_case__						,  snake_case__=None):
						lowerCAmelCase_	:     Optional[Any]          = {}

						if isinstance(A__						,  A__):
												lowerCAmelCase_	:     int          = model.mobilenet_va
						else:
												lowerCAmelCase_	:     Optional[Any]          = model

						lowerCAmelCase_	:     Dict          = "MobilenetV1/Conv2d_0/"
						lowerCAmelCase_	:     Union[str, Any]          = backbone.conv_stem.convolution.weight
						lowerCAmelCase_	:     Union[str, Any]          = backbone.conv_stem.normalization.bias
						lowerCAmelCase_	:     str          = backbone.conv_stem.normalization.weight
						lowerCAmelCase_	:     List[str]          = backbone.conv_stem.normalization.running_mean
						lowerCAmelCase_	:     str          = backbone.conv_stem.normalization.running_var

						for i in range(13):
												lowerCAmelCase_	:     Any          = i + 1
												lowerCAmelCase_	:     Optional[int]          = i * 2

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

												lowerCAmelCase_	:     Any          = backbone.layer[pt_index + 1]
												lowerCAmelCase_	:     List[Any]          = F'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
												lowerCAmelCase_	:     str          = pointer.convolution.weight
												lowerCAmelCase_	:     Tuple          = pointer.normalization.bias
												lowerCAmelCase_	:     List[str]          = pointer.normalization.weight
												lowerCAmelCase_	:     Optional[Any]          = pointer.normalization.running_mean
												lowerCAmelCase_	:     List[str]          = pointer.normalization.running_var

						if isinstance(A__						,  A__):
												lowerCAmelCase_	:     Dict          = "MobilenetV1/Logits/Conv2d_1c_1x1/"
												lowerCAmelCase_	:     Dict          = model.classifier.weight
												lowerCAmelCase_	:     Tuple          = model.classifier.bias

						return tf_to_pt_map

def   UpperCamelCase			(      snake_case__						,  snake_case__						,  snake_case__):
						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
						lowerCAmelCase_	:     Optional[Any]          = tf.train.list_variables(A__)
						lowerCAmelCase_	:     Tuple          = {}
						for name, shape in init_vars:
												logger.info(F'''Loading TF weight {name} with shape {shape}''')
												lowerCAmelCase_	:     Optional[Any]          = tf.train.load_variable(A__						,  A__)
												lowerCAmelCase_	:     List[Any]          = array

						# Build TF to PyTorch weights loading map
						lowerCAmelCase_	:     Union[str, Any]          = _build_tf_to_pytorch_map(A__						,  A__						,  A__)

						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

												lowerCAmelCase_	:     str          = tf_weights[name]

												if "depthwise_weights" in name:
																		logger.info("Transposing depthwise")
																		lowerCAmelCase_	:     List[str]          = np.transpose(A__						,  (2, 3, 0, 1))
												elif "weights" in name:
																		logger.info("Transposing")
																		if len(pointer.shape) == 2:  # copying into linear layer
																								lowerCAmelCase_	:     int          = array.squeeze().transpose()
																		else:
																								lowerCAmelCase_	:     List[str]          = np.transpose(A__						,  (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}''')
												lowerCAmelCase_	:     Any          = torch.from_numpy(A__)

												tf_weights.pop(A__						,  A__)
												tf_weights.pop(name + "/RMSProp"						,  A__)
												tf_weights.pop(name + "/RMSProp_1"						,  A__)
												tf_weights.pop(name + "/ExponentialMovingAverage"						,  A__)

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

def   UpperCamelCase			(      snake_case__						,  snake_case__):
						lowerCAmelCase_    ,					lowerCAmelCase_	:     Any          = features.shape[-2:]
						lowerCAmelCase_    ,					lowerCAmelCase_	:     Dict          = conv_layer.stride
						lowerCAmelCase_    ,					lowerCAmelCase_	:     int          = conv_layer.kernel_size

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

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

						lowerCAmelCase_	:     int          = pad_along_width // 2
						lowerCAmelCase_	:     List[Any]          = pad_along_width - pad_left
						lowerCAmelCase_	:     List[Any]          = pad_along_height // 2
						lowerCAmelCase_	:     Optional[Any]          = pad_along_height - pad_top

						lowerCAmelCase_	:     List[Any]          = (pad_left, pad_right, pad_top, pad_bottom)
						return nn.functional.pad(A__						,  A__						,  "constant"						,  0.0)

class __snake_case		( nn.Module ):





		"""simple docstring"""







		def __init__(							self    :   Any						,lowerCAmelCase__    :   MobileNetVaConfig						,lowerCAmelCase__    :   int						,lowerCAmelCase__    :   int						,lowerCAmelCase__    :   int						,lowerCAmelCase__    :   Optional[int] = 1						,lowerCAmelCase__    :   Optional[int] = 1						,lowerCAmelCase__    :   bool = False						,lowerCAmelCase__    :   Optional[bool] = True						,lowerCAmelCase__    :   Optional[bool or str] = True						,)      ->							Tuple:




								'''simple docstring'''

								super().__init__()
								lowerCAmelCase_	:     Dict          = 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.'''      )

								lowerCAmelCase_	:     Optional[int]          = 0 if config.tf_padding else int((kernel_size - 1) / 2      )

								lowerCAmelCase_	:     List[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:
														lowerCAmelCase_	:     Union[str, Any]          = nn.BatchNormad(
														    num_features=__lowerCamelCase						,eps=config.layer_norm_eps						,momentum=0.9_997						,affine=__lowerCamelCase						,track_running_stats=__lowerCamelCase						,)
								else:
														lowerCAmelCase_	:     Optional[int]          = None

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



		def  UpperCAmelCase_							(							self    :   Dict						,lowerCAmelCase__    :   torch.Tensor      )      ->							Any:




								'''simple docstring'''

								if self.config.tf_padding:
														lowerCAmelCase_	:     Dict          = apply_tf_padding(__lowerCamelCase						,self.convolution      )
								lowerCAmelCase_	:     int          = self.convolution(__lowerCamelCase      )
								if self.normalization is not None:
														lowerCAmelCase_	:     Optional[int]          = self.normalization(__lowerCamelCase      )
								if self.activation is not None:
														lowerCAmelCase_	:     Dict          = self.activation(__lowerCamelCase      )
								return features






class __snake_case		( __snake_case ):





		"""simple docstring"""







		UpperCamelCase_				      =   MobileNetVaConfig
		UpperCamelCase_				      =   load_tf_weights_in_mobilenet_va
		UpperCamelCase_				      =   'mobilenet_v1'
		UpperCamelCase_				      =   'pixel_values'
		UpperCamelCase_				      =   False



		def  UpperCAmelCase_							(							self    :   List[Any]						,lowerCAmelCase__    :   Union[nn.Linear, nn.Convad]      )      ->							Dict:




								'''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      )






_lowercase       		= 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 ([`MobileNetV1Config`]): 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       		= 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            [`MobileNetV1ImageProcessor.__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 MobileNetV1 model outputting raw hidden-states without any specific head on top.'  ,				__snake_case  ,				)
class __snake_case		( __snake_case ):





		"""simple docstring"""







		def __init__(							self    :   str						,lowerCAmelCase__    :   MobileNetVaConfig						,lowerCAmelCase__    :   bool = True      )      ->							str:




								'''simple docstring'''

								super().__init__(__lowerCamelCase      )
								lowerCAmelCase_	:     Any          = config

								lowerCAmelCase_	:     Dict          = 32
								lowerCAmelCase_	:     Optional[int]          = max(int(depth * config.depth_multiplier      )						,config.min_depth      )

								lowerCAmelCase_	:     List[str]          = MobileNetVaConvLayer(
								    __lowerCamelCase						,in_channels=config.num_channels						,out_channels=__lowerCamelCase						,kernel_size=3						,stride=2						,)

								lowerCAmelCase_	:     Union[str, Any]          = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								lowerCAmelCase_	:     Tuple          = nn.ModuleList()
								for i in range(13      ):
														lowerCAmelCase_	:     Dict          = out_channels

														if strides[i] == 2 or i == 0:
																				depth *= 2
																				lowerCAmelCase_	:     Optional[int]          = 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						,)      )

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

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



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




								'''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  UpperCAmelCase_							(							self    :   List[str]						,lowerCAmelCase__    :   Optional[torch.Tensor] = None						,lowerCAmelCase__    :   Optional[bool] = None						,lowerCAmelCase__    :   Optional[bool] = None						,)      ->							Optional[Any]:




								'''simple docstring'''

								lowerCAmelCase_	:     Tuple          = (
								    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

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

								lowerCAmelCase_	:     Union[str, Any]          = self.conv_stem(__lowerCamelCase      )

								lowerCAmelCase_	:     List[str]          = () if output_hidden_states else None

								for i, layer_module in enumerate(self.layer      ):
														lowerCAmelCase_	:     Dict          = layer_module(__lowerCamelCase      )

														if output_hidden_states:
																				lowerCAmelCase_	:     Tuple          = all_hidden_states + (hidden_states,)

								lowerCAmelCase_	:     Optional[int]          = hidden_states

								if self.pooler is not None:
														lowerCAmelCase_	:     Optional[Any]          = torch.flatten(self.pooler(__lowerCamelCase      )						,start_dim=1      )
								else:
														lowerCAmelCase_	:     Union[str, Any]          = 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(
    '\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '  ,				__snake_case  ,				)
class __snake_case		( __snake_case ):





		"""simple docstring"""







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




								'''simple docstring'''

								super().__init__(__lowerCamelCase      )

								lowerCAmelCase_	:     Tuple          = config.num_labels
								lowerCAmelCase_	:     Any          = MobileNetVaModel(__lowerCamelCase      )

								lowerCAmelCase_	:     str          = self.mobilenet_va.layer[-1].convolution.out_channels

								# Classifier head
								lowerCAmelCase_	:     List[Any]          = nn.Dropout(config.classifier_dropout_prob						,inplace=__lowerCamelCase      )
								lowerCAmelCase_	:     int          = 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  UpperCAmelCase_							(							self    :   Optional[int]						,lowerCAmelCase__    :   Optional[torch.Tensor] = None						,lowerCAmelCase__    :   Optional[bool] = None						,lowerCAmelCase__    :   Optional[torch.Tensor] = None						,lowerCAmelCase__    :   Optional[bool] = None						,)      ->							Optional[Any]:




								'''simple docstring'''

								lowerCAmelCase_	:     Union[str, Any]          = return_dict if return_dict is not None else self.config.use_return_dict

								lowerCAmelCase_	:     List[str]          = self.mobilenet_va(__lowerCamelCase						,output_hidden_states=__lowerCamelCase						,return_dict=__lowerCamelCase      )

								lowerCAmelCase_	:     Union[str, Any]          = outputs.pooler_output if return_dict else outputs[1]

								lowerCAmelCase_	:     Union[str, Any]          = self.classifier(self.dropout(__lowerCamelCase      )      )

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

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

								if not return_dict:
														lowerCAmelCase_	:     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						,)





def 	__a     (      A__			:  int       ):
    if not isinstance(A__			,  A__       ):
        raise ValueError("Input must be an integer"       )
    if input_num <= 0:
        raise ValueError("Input must be positive"       )
    return sum(
        divisor for divisor in range(1			,  input_num // 2 + 1       ) if input_num % divisor == 0       )


if __name__ == "__main__":
    import doctest

    doctest.testmod()