



'''simple docstring'''
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


snake_case_					:      str    			=    logging.get_logger(__name__)


# General docstring
snake_case_					:      List[Any]    			=    'MobileNetV1Config'

# Base docstring
snake_case_					:      Any    			=    'google/mobilenet_v1_1.0_224'
snake_case_					:      Dict    			=    [1, 1024, 7, 7]

# Image classification docstring
snake_case_					:      List[str]    			=    'google/mobilenet_v1_1.0_224'
snake_case_					:      int    			=    'tabby, tabby cat'


snake_case_					:      Union[str, Any]    			=    [
    '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 A__       (	UpperCAmelCase_    ,    UpperCAmelCase_    ,    UpperCAmelCase_=None				):
						_UpperCamelCase   :						Tuple												=  {}

						if isinstance(UpperCAmelCase_    ,    UpperCAmelCase_				):
												_UpperCamelCase   :						Union[str, Any]												=  model.mobilenet_va
						else:
												_UpperCamelCase   :						int												=  model

						_UpperCamelCase   :						List[Any]												=  'MobilenetV1/Conv2d_0/'
						_UpperCamelCase   :						Any												=  backbone.conv_stem.convolution.weight
						_UpperCamelCase   :						Optional[Any]												=  backbone.conv_stem.normalization.bias
						_UpperCamelCase   :						Any												=  backbone.conv_stem.normalization.weight
						_UpperCamelCase   :						Optional[int]												=  backbone.conv_stem.normalization.running_mean
						_UpperCamelCase   :						Dict												=  backbone.conv_stem.normalization.running_var

						for i in range(1_3				):
												_UpperCamelCase   :						Union[str, Any]												=  i + 1
												_UpperCamelCase   :						str												=  i * 2

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

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

						if isinstance(UpperCAmelCase_    ,    UpperCAmelCase_				):
												_UpperCamelCase   :						int												=  'MobilenetV1/Logits/Conv2d_1c_1x1/'
												_UpperCamelCase   :						Union[str, Any]												=  model.classifier.weight
												_UpperCamelCase   :						Union[str, Any]												=  model.classifier.bias

						return tf_to_pt_map






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

						# Build TF to PyTorch weights loading map
						_UpperCamelCase   :						Optional[int]												=  _build_tf_to_pytorch_map(UpperCAmelCase_    ,    UpperCAmelCase_    ,    UpperCAmelCase_				)

						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

												_UpperCamelCase   :						str												=  tf_weights[name]

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

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

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






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_				):
						_UpperCamelCase							,     _UpperCamelCase   :						List[Any]												=  features.shape[-2:]
						_UpperCamelCase							,     _UpperCamelCase   :						Tuple												=  conv_layer.stride
						_UpperCamelCase							,     _UpperCamelCase   :						Dict												=  conv_layer.kernel_size

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

						if in_width % stride_width == 0:
												_UpperCamelCase   :						Union[str, Any]												=  max(kernel_width - stride_width    ,    0				)
						else:
												_UpperCamelCase   :						Any												=  max(kernel_width - (in_width % stride_width)    ,    0				)

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

						_UpperCamelCase   :						Dict												=  (pad_left, pad_right, pad_top, pad_bottom)
						return nn.functional.pad(UpperCAmelCase_    ,    UpperCAmelCase_    ,    'constant'    ,    0.0				)






class 				lowercase__      (				nn.Module  ):





	def __init__(					self   :							Tuple					,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					,):







							'''simple docstring'''
							super().__init__()
							_UpperCamelCase   :						Any												=  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.'					)

							_UpperCamelCase   :						Tuple												=  0 if config.tf_padding else int((kernel_size - 1) / 2					)

							_UpperCamelCase   :						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:
													_UpperCamelCase   :						Optional[int]												=  nn.BatchNormad(
													    num_features=lowerCamelCase__					,eps=config.layer_norm_eps					,momentum=0.9_9_9_7					,affine=lowerCamelCase__					,track_running_stats=lowerCamelCase__					,)
							else:
													_UpperCamelCase   :						Dict												=  None

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





	def       UpperCamelCase_    (					self   :							str					,lowerCamelCase__   :							torch.Tensor					):







							'''simple docstring'''
							if self.config.tf_padding:
													_UpperCamelCase   :						str												=  apply_tf_padding(lowerCamelCase__					,self.convolution					)
							_UpperCamelCase   :						int												=  self.convolution(lowerCamelCase__					)
							if self.normalization is not None:
													_UpperCamelCase   :						str												=  self.normalization(lowerCamelCase__					)
							if self.activation is not None:
													_UpperCamelCase   :						int												=  self.activation(lowerCamelCase__					)
							return features






class 				lowercase__      (				lowercase  ):
	lowercase__    							=     MobileNetVaConfig
	lowercase__    							=     load_tf_weights_in_mobilenet_va
	lowercase__    							=     """mobilenet_v1"""
	lowercase__    							=     """pixel_values"""
	lowercase__    							=     False





	def       UpperCamelCase_    (					self   :							Tuple					,lowerCamelCase__   :							Union[nn.Linear, nn.Convad]					):







							'''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					)
snake_case_					:      Union[str, 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 ([`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'

snake_case_					:      List[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            [`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."""		,   lowercase		,   )
class 				lowercase__      (				lowercase  ):





	def __init__(					self   :							str					,lowerCamelCase__   :							MobileNetVaConfig					,lowerCamelCase__   :							bool = True					):







							'''simple docstring'''
							super().__init__(lowerCamelCase__					)
							_UpperCamelCase   :						str												=  config

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

							_UpperCamelCase   :						Any												=  MobileNetVaConvLayer(
							    lowerCamelCase__					,in_channels=config.num_channels					,out_channels=lowerCamelCase__					,kernel_size=3					,stride=2					,)

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

							_UpperCamelCase   :						int												=  nn.ModuleList()
							for i in range(13					):
													_UpperCamelCase   :						List[str]												=  out_channels

													if strides[i] == 2 or i == 0:
																			depth *= 2
																			_UpperCamelCase   :						List[str]												=  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					,)					)

							_UpperCamelCase   :						int												=  nn.AdaptiveAvgPoolad((1, 1)					) if add_pooling_layer else None

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





	def       UpperCamelCase_    (					self   :							List[str]					,lowerCamelCase__   :							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   :							Optional[int]					,lowerCamelCase__   :							Optional[torch.Tensor] = None					,lowerCamelCase__   :							Optional[bool] = None					,lowerCamelCase__   :							Optional[bool] = None					,):







							'''simple docstring'''
							_UpperCamelCase   :						Optional[int]												=  (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							_UpperCamelCase   :						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'					)

							_UpperCamelCase   :						Dict												=  self.conv_stem(lowerCamelCase__					)

							_UpperCamelCase   :						Tuple												=  () if output_hidden_states else None

							for i, layer_module in enumerate(self.layer					):
													_UpperCamelCase   :						Union[str, Any]												=  layer_module(lowerCamelCase__					)

													if output_hidden_states:
																			_UpperCamelCase   :						Optional[Any]												=  all_hidden_states + (hidden_states,)

							_UpperCamelCase   :						List[str]												=  hidden_states

							if self.pooler is not None:
													_UpperCamelCase   :						List[Any]												=  torch.flatten(self.pooler(lowerCamelCase__					)					,start_dim=1					)
							else:
													_UpperCamelCase   :						Optional[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(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """		,   lowercase		,   )
class 				lowercase__      (				lowercase  ):





	def __init__(					self   :							Union[str, Any]					,lowerCamelCase__   :							MobileNetVaConfig					):







							'''simple docstring'''
							super().__init__(lowerCamelCase__					)

							_UpperCamelCase   :						List[Any]												=  config.num_labels
							_UpperCamelCase   :						int												=  MobileNetVaModel(lowerCamelCase__					)

							_UpperCamelCase   :						List[Any]												=  self.mobilenet_va.layer[-1].convolution.out_channels

							# Classifier head
							_UpperCamelCase   :						List[Any]												=  nn.Dropout(config.classifier_dropout_prob					,inplace=lowerCamelCase__					)
							_UpperCamelCase   :						Dict												=  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   :							List[Any]					,lowerCamelCase__   :							Optional[torch.Tensor] = None					,lowerCamelCase__   :							Optional[bool] = None					,lowerCamelCase__   :							Optional[torch.Tensor] = None					,lowerCamelCase__   :							Optional[bool] = None					,):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  return_dict if return_dict is not None else self.config.use_return_dict

							_UpperCamelCase   :						Dict												=  self.mobilenet_va(lowerCamelCase__					,output_hidden_states=lowerCamelCase__					,return_dict=lowerCamelCase__					)

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

							_UpperCamelCase   :						Optional[Any]												=  self.classifier(self.dropout(lowerCamelCase__					)					)

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

													if self.config.problem_type == "regression":
																			_UpperCamelCase   :						Tuple												=  MSELoss()
																			if self.num_labels == 1:
																									_UpperCamelCase   :						Dict												=  loss_fct(logits.squeeze()					,labels.squeeze()					)
																			else:
																									_UpperCamelCase   :						Any												=  loss_fct(lowerCamelCase__					,lowerCamelCase__					)
													elif self.config.problem_type == "single_label_classification":
																			_UpperCamelCase   :						int												=  CrossEntropyLoss()
																			_UpperCamelCase   :						List[Any]												=  loss_fct(logits.view(-1					,self.num_labels					)					,labels.view(-1					)					)
													elif self.config.problem_type == "multi_label_classification":
																			_UpperCamelCase   :						Tuple												=  BCEWithLogitsLoss()
																			_UpperCamelCase   :						List[Any]												=  loss_fct(lowerCamelCase__					,lowerCamelCase__					)

							if not return_dict:
													_UpperCamelCase   :						Optional[Any]												=  (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'''
from math import ceil






def A__       (	UpperCAmelCase_ = 1_0_0_1				):
						_UpperCamelCase   :						int												=  1

						for i in range(1    ,    int(ceil(n / 2.0				)				)				):
												_UpperCamelCase   :						Dict												=  2 * i + 1
												_UpperCamelCase   :						Tuple												=  2 * i
												_UpperCamelCase   :						Any												=  total + 4 * odd**2 - 6 * even

						return total


if __name__ == "__main__":
					import sys

					if len(sys.argv) == 1:
										print(solution())
					else:
										try:
															snake_case_					:      Tuple    			=    int(sys.argv[1])
															print(solution(n))
										except ValueError:
															print('Invalid entry - please enter a number')


