






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


_A     :      Optional[Any]   					=logging.get_logger(__name__)


# General docstring
_A     :      int   					='''MobileNetV1Config'''

# Base docstring
_A     :      Dict   					='''google/mobilenet_v1_1.0_224'''
_A     :      Union[str, Any]   					=[1, 1_024, 7, 7]

# Image classification docstring
_A     :      Optional[int]   					='''google/mobilenet_v1_1.0_224'''
_A     :      Any   					='''tabby, tabby cat'''


_A     :      Dict   					=[
    '''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 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase=None				)				->	Optional[Any]:
							lowerCamelCase__ :     Tuple	  =	{}

							if isinstance(UpperCamelCase    ,      UpperCamelCase				):
														lowerCamelCase__ :     Optional[int]	  =	model.mobilenet_va
							else:
														lowerCamelCase__ :     List[Any]	  =	model

							lowerCamelCase__ :     Optional[int]	  =	"""MobilenetV1/Conv2d_0/"""
							lowerCamelCase__ :     Dict	  =	backbone.conv_stem.convolution.weight
							lowerCamelCase__ :     Any	  =	backbone.conv_stem.normalization.bias
							lowerCamelCase__ :     Tuple	  =	backbone.conv_stem.normalization.weight
							lowerCamelCase__ :     Any	  =	backbone.conv_stem.normalization.running_mean
							lowerCamelCase__ :     List[str]	  =	backbone.conv_stem.normalization.running_var

							for i in range(13				):
														lowerCamelCase__ :     Dict	  =	i + 1
														lowerCamelCase__ :     str	  =	i * 2

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

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

							if isinstance(UpperCamelCase    ,      UpperCamelCase				):
														lowerCamelCase__ :     int	  =	"""MobilenetV1/Logits/Conv2d_1c_1x1/"""
														lowerCamelCase__ :     Tuple	  =	model.classifier.weight
														lowerCamelCase__ :     List[str]	  =	model.classifier.bias

							return tf_to_pt_map





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

							# Build TF to PyTorch weights loading map
							lowerCamelCase__ :     Optional[Any]	  =	_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

														lowerCamelCase__ :     str	  =	tf_weights[name]

														if "depthwise_weights" in name:
																					logger.info("""Transposing depthwise"""				)
																					lowerCamelCase__ :     Dict	  =	np.transpose(UpperCamelCase    ,      (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__ :     Dict	  =	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}'''				)
														lowerCamelCase__ :     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 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	torch.Tensor:
							lowerCamelCase__  ,		lowerCamelCase__ :     Union[str, Any]	  =	features.shape[-2:]
							lowerCamelCase__  ,		lowerCamelCase__ :     Optional[int]	  =	conv_layer.stride
							lowerCamelCase__  ,		lowerCamelCase__ :     str	  =	conv_layer.kernel_size

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

							if in_width % stride_width == 0:
														lowerCamelCase__ :     Tuple	  =	max(kernel_width - stride_width    ,      0				)
							else:
														lowerCamelCase__ :     List[str]	  =	max(kernel_width - (in_width % stride_width)    ,      0				)

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

							lowerCamelCase__ :     str	  =	(pad_left, pad_right, pad_top, pad_bottom)
							return nn.functional.pad(UpperCamelCase    ,      UpperCamelCase    ,      """constant"""    ,      0.0				)

class _lowercase     (    nn.Module		):




							def __init__(							self:    Optional[int]      ,							UpperCamelCase__:    MobileNetVaConfig      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    Optional[int] = 1      ,							UpperCamelCase__:    Optional[int] = 1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[bool] = True      ,							UpperCamelCase__:    Optional[bool or str] = True      ,							):
														super().__init__()
														lowerCamelCase__ :     Optional[int]	  =	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__ :     Any	  =	0 if config.tf_padding else int((kernel_size - 1) / 2					)

														lowerCamelCase__ :     Dict	  =	nn.Convad(
														    in_channels=UpperCamelCase__      ,							out_channels=UpperCamelCase__      ,							kernel_size=UpperCamelCase__      ,							stride=UpperCamelCase__      ,							padding=UpperCamelCase__      ,							groups=UpperCamelCase__      ,							bias=UpperCamelCase__      ,							padding_mode="""zeros"""      ,							)

														if use_normalization:
																					lowerCamelCase__ :     Union[str, Any]	  =	nn.BatchNormad(
																					    num_features=UpperCamelCase__      ,							eps=config.layer_norm_eps      ,							momentum=0.9_997      ,							affine=UpperCamelCase__      ,							track_running_stats=UpperCamelCase__      ,							)
														else:
																					lowerCamelCase__ :     Dict	  =	None

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




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    torch.Tensor					):
														if self.config.tf_padding:
																					lowerCamelCase__ :     List[Any]	  =	apply_tf_padding(UpperCamelCase__      ,							self.convolution					)
														lowerCamelCase__ :     Optional[int]	  =	self.convolution(UpperCamelCase__					)
														if self.normalization is not None:
																					lowerCamelCase__ :     Optional[int]	  =	self.normalization(UpperCamelCase__					)
														if self.activation is not None:
																					lowerCamelCase__ :     Any	  =	self.activation(UpperCamelCase__					)
														return features



class _lowercase     (    _lowercase		):
							a    				=	MobileNetVaConfig
							a    				=	load_tf_weights_in_mobilenet_va
							a    				=	"""mobilenet_v1"""
							a    				=	"""pixel_values"""
							a    				=	False




							def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    Union[nn.Linear, nn.Convad]					):
														if isinstance(UpperCamelCase__      ,							(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(UpperCamelCase__      ,							nn.BatchNormad					):
																					module.bias.data.zero_()
																					module.weight.data.fill_(1.0					)



_A     :      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.
'''

_A     :      Union[str, Any]   					=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."""    ,				_lowercase    ,				)
class _lowercase     (    _lowercase		):




							def __init__(							self:    int      ,							UpperCamelCase__:    MobileNetVaConfig      ,							UpperCamelCase__:    bool = True					):
														super().__init__(UpperCamelCase__					)
														lowerCamelCase__ :     Tuple	  =	config

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

														lowerCamelCase__ :     Optional[Any]	  =	MobileNetVaConvLayer(
														    UpperCamelCase__      ,							in_channels=config.num_channels      ,							out_channels=UpperCamelCase__      ,							kernel_size=3      ,							stride=2      ,							)

														lowerCamelCase__ :     List[Any]	  =	[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

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

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

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

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

														lowerCamelCase__ :     Tuple	  =	nn.AdaptiveAvgPoolad((1, 1)					) if add_pooling_layer else None

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




							def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    Any					):
														raise NotImplementedError




							@add_start_docstrings_to_model_forward(UpperCamelCase__					)
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC      ,							output_type=UpperCamelCase__      ,							config_class=_CONFIG_FOR_DOC      ,							modality="""vision"""      ,							expected_output=_EXPECTED_OUTPUT_SHAPE      ,							)
							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    Optional[torch.Tensor] = None      ,							UpperCamelCase__:    Optional[bool] = None      ,							UpperCamelCase__:    Optional[bool] = None      ,							):
														lowerCamelCase__ :     List[Any]	  =	(
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)
														lowerCamelCase__ :     str	  =	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__ :     Dict	  =	self.conv_stem(UpperCamelCase__					)

														lowerCamelCase__ :     Tuple	  =	() if output_hidden_states else None

														for i, layer_module in enumerate(self.layer					):
																					lowerCamelCase__ :     List[str]	  =	layer_module(UpperCamelCase__					)

																					if output_hidden_states:
																												lowerCamelCase__ :     Union[str, Any]	  =	all_hidden_states + (hidden_states,)

														lowerCamelCase__ :     int	  =	hidden_states

														if self.pooler is not None:
																					lowerCamelCase__ :     int	  =	torch.flatten(self.pooler(UpperCamelCase__					)      ,							start_dim=1					)
														else:
																					lowerCamelCase__ :     Dict	  =	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=UpperCamelCase__      ,							pooler_output=UpperCamelCase__      ,							hidden_states=UpperCamelCase__      ,							)



@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:    Dict      ,							UpperCamelCase__:    MobileNetVaConfig					):
														super().__init__(UpperCamelCase__					)

														lowerCamelCase__ :     Dict	  =	config.num_labels
														lowerCamelCase__ :     Optional[Any]	  =	MobileNetVaModel(UpperCamelCase__					)

														lowerCamelCase__ :     Tuple	  =	self.mobilenet_va.layer[-1].convolution.out_channels

														# Classifier head
														lowerCamelCase__ :     Optional[int]	  =	nn.Dropout(config.classifier_dropout_prob      ,							inplace=UpperCamelCase__					)
														lowerCamelCase__ :     str	  =	nn.Linear(UpperCamelCase__      ,							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(UpperCamelCase__					)
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT      ,							output_type=UpperCamelCase__      ,							config_class=_CONFIG_FOR_DOC      ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,							)
							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    Optional[torch.Tensor] = None      ,							UpperCamelCase__:    Optional[bool] = None      ,							UpperCamelCase__:    Optional[torch.Tensor] = None      ,							UpperCamelCase__:    Optional[bool] = None      ,							):
														lowerCamelCase__ :     int	  =	return_dict if return_dict is not None else self.config.use_return_dict

														lowerCamelCase__ :     List[str]	  =	self.mobilenet_va(UpperCamelCase__      ,							output_hidden_states=UpperCamelCase__      ,							return_dict=UpperCamelCase__					)

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

														lowerCamelCase__ :     Union[str, Any]	  =	self.classifier(self.dropout(UpperCamelCase__					)					)

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

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

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

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









'''simple docstring'''







from __future__ import annotations





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	list[str]:
							if nth_term == "":
														return [""]
							lowerCamelCase__ :     str	  =	int(UpperCamelCase				)
							lowerCamelCase__ :     Union[str, Any]	  =	int(UpperCamelCase				)
							lowerCamelCase__ :     list[str]	  =	[]
							for temp in range(int(UpperCamelCase				)				):
														series.append(f'''1 / {pow(temp + 1    ,      int(UpperCamelCase				)				)}''' if series else """1"""				)
							return series


if __name__ == "__main__":
			import doctest

			doctest.testmod()

			_A     :      Optional[Any]   					=int(input('''Enter the last number (nth term) of the P-Series'''))
			_A     :      List[str]   					=int(input('''Enter the power for  P-Series'''))
			print('''Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p''')
			print(p_series(nth_term, power))

