






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


_UpperCamelCase		:  str						=		logging.get_logger(__name__)


# General docstring
_UpperCamelCase		:  Union[str, Any]						=		'MobileNetV1Config'

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

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


_UpperCamelCase		:  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 						_SCREAMING_SNAKE_CASE (    __snake_case			:  List[str]		,					__snake_case			:  Dict		,					__snake_case			:  Optional[int]=None    ):





  '''simple docstring'''





  lowercase							    =       {}

  if isinstance(__snake_case		,					__snake_case    ):
    lowercase							    =       model.mobilenet_va
  else:
    lowercase							    =       model

  lowercase							    =       'MobilenetV1/Conv2d_0/'
  lowercase							    =       backbone.conv_stem.convolution.weight
  lowercase							    =       backbone.conv_stem.normalization.bias
  lowercase							    =       backbone.conv_stem.normalization.weight
  lowercase							    =       backbone.conv_stem.normalization.running_mean
  lowercase							    =       backbone.conv_stem.normalization.running_var

  for i in range(13    ):
    lowercase							    =       i + 1
    lowercase							    =       i * 2

    lowercase							    =       backbone.layer[pt_index]
    lowercase							    =       f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
    lowercase							    =       pointer.convolution.weight
    lowercase							    =       pointer.normalization.bias
    lowercase							    =       pointer.normalization.weight
    lowercase							    =       pointer.normalization.running_mean
    lowercase							    =       pointer.normalization.running_var

    lowercase							    =       backbone.layer[pt_index + 1]
    lowercase							    =       f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
    lowercase							    =       pointer.convolution.weight
    lowercase							    =       pointer.normalization.bias
    lowercase							    =       pointer.normalization.weight
    lowercase							    =       pointer.normalization.running_mean
    lowercase							    =       pointer.normalization.running_var

  if isinstance(__snake_case		,					__snake_case    ):
    lowercase							    =       'MobilenetV1/Logits/Conv2d_1c_1x1/'
    lowercase							    =       model.classifier.weight
    lowercase							    =       model.classifier.bias

  return tf_to_pt_map
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[int]		,					__snake_case			:  str		,					__snake_case			:  Tuple    ):





  '''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
  lowercase							    =       tf.train.list_variables(__snake_case    )
  lowercase							    =       {}
  for name, shape in init_vars:
    logger.info(f'Loading TF weight {name} with shape {shape}'    )
    lowercase							    =       tf.train.load_variable(__snake_case		,					__snake_case    )
    lowercase							    =       array

  # Build TF to PyTorch weights loading map
  lowercase							    =       _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

    lowercase							    =       tf_weights[name]

    if "depthwise_weights" in name:
      logger.info('Transposing depthwise'    )
      lowercase							    =       np.transpose(__snake_case		,					(2, 3, 0, 1)    )
    elif "weights" in name:
      logger.info('Transposing'    )
      if len(pointer.shape    ) == 2:  # copying into linear layer
        lowercase							    =       array.squeeze().transpose()
      else:
        lowercase							    =       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}'    )
    lowercase							    =       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 						_SCREAMING_SNAKE_CASE (    __snake_case			:  torch.Tensor		,					__snake_case			:  nn.Convad    ):





  '''simple docstring'''





  lowercase    ,     lowercase							    =       features.shape[-2:]
  lowercase    ,     lowercase							    =       conv_layer.stride
  lowercase    ,     lowercase							    =       conv_layer.kernel_size

  if in_height % stride_height == 0:
    lowercase							    =       max(kernel_height - stride_height		,					0    )
  else:
    lowercase							    =       max(kernel_height - (in_height % stride_height)		,					0    )

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

  lowercase							    =       pad_along_width // 2
  lowercase							    =       pad_along_width - pad_left
  lowercase							    =       pad_along_height // 2
  lowercase							    =       pad_along_height - pad_top

  lowercase							    =       (pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(__snake_case		,					__snake_case		,					'constant'		,					0.0    )

class        a     (   nn.Module	):







    def __init__(			self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase = 1							,		_lowerCamelCase = 1							,		_lowerCamelCase = False							,		_lowerCamelCase = True							,		_lowerCamelCase = True							,		):
      super().__init__()
      lowercase							    =       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.'       )

      lowercase							    =       0 if config.tf_padding else int((kernel_size - 1) / 2       )

      lowercase							    =       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:
        lowercase							    =       nn.BatchNormad(
            num_features=_lowerCamelCase							,		eps=config.layer_norm_eps							,		momentum=0.9_9_9_7							,		affine=_lowerCamelCase							,		track_running_stats=_lowerCamelCase							,		)
      else:
        lowercase							    =       None

      if use_activation:
        if isinstance(_lowerCamelCase							,		_lowerCamelCase       ):
          lowercase							    =       ACTaFN[use_activation]
        elif isinstance(config.hidden_act							,		_lowerCamelCase       ):
          lowercase							    =       ACTaFN[config.hidden_act]
        else:
          lowercase							    =       config.hidden_act
      else:
        lowercase							    =       None







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      if self.config.tf_padding:
        lowercase							    =       apply_tf_padding(_lowerCamelCase							,		self.convolution       )
      lowercase							    =       self.convolution(_lowerCamelCase       )
      if self.normalization is not None:
        lowercase							    =       self.normalization(_lowerCamelCase       )
      if self.activation is not None:
        lowercase							    =       self.activation(_lowerCamelCase       )
      return features


class        a     (   a_	):
    UpperCAmelCase_ :     List[str]	     =MobileNetVaConfig
    UpperCAmelCase_ :     Optional[Any]	     =load_tf_weights_in_mobilenet_va
    UpperCAmelCase_ :     Optional[Any]	     ="mobilenet_v1"
    UpperCAmelCase_ :     Tuple	     ="pixel_values"
    UpperCAmelCase_ :     Dict	     =False







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      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       )


_UpperCamelCase		:  Dict						=		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'

_UpperCamelCase		:  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.",				a_,				)
class        a     (   a_	):







    def __init__(			self							,		_lowerCamelCase							,		_lowerCamelCase = True       ):
      super().__init__(_lowerCamelCase       )
      lowercase							    =       config

      lowercase							    =       3_2
      lowercase							    =       max(int(depth * config.depth_multiplier       )							,		config.min_depth       )

      lowercase							    =       MobileNetVaConvLayer(
          _lowerCamelCase							,		in_channels=config.num_channels							,		out_channels=_lowerCamelCase							,		kernel_size=3							,		stride=2							,		)

      lowercase							    =       [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

      lowercase							    =       nn.ModuleList()
      for i in range(1_3       ):
        lowercase							    =       out_channels

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

      lowercase							    =       nn.AdaptiveAvgPoolad((1, 1)       ) if add_pooling_layer else None

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







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      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							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		):
      lowercase							    =       (
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      lowercase							    =       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'       )

      lowercase							    =       self.conv_stem(_lowerCamelCase       )

      lowercase							    =       () if output_hidden_states else None

      for i, layer_module in enumerate(self.layer       ):
        lowercase							    =       layer_module(_lowerCamelCase       )

        if output_hidden_states:
          lowercase							    =       all_hidden_states + (hidden_states,)

      lowercase							    =       hidden_states

      if self.pooler is not None:
        lowercase							    =       torch.flatten(self.pooler(_lowerCamelCase       )							,		start_dim=1       )
      else:
        lowercase							    =       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    ",				a_,				)
class        a     (   a_	):







    def __init__(			self							,		_lowerCamelCase       ):
      super().__init__(_lowerCamelCase       )

      lowercase							    =       config.num_labels
      lowercase							    =       MobileNetVaModel(_lowerCamelCase       )

      lowercase							    =       self.mobilenet_va.layer[-1].convolution.out_channels

      # Classifier head
      lowercase							    =       nn.Dropout(config.classifier_dropout_prob							,		inplace=_lowerCamelCase       )
      lowercase							    =       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							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		):
      lowercase							    =       return_dict if return_dict is not None else self.config.use_return_dict

      lowercase							    =       self.mobilenet_va(_lowerCamelCase							,		output_hidden_states=_lowerCamelCase							,		return_dict=_lowerCamelCase       )

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

      lowercase							    =       self.classifier(self.dropout(_lowerCamelCase       )       )

      lowercase							    =       None
      if labels is not None:
        if self.config.problem_type is None:
          if self.num_labels == 1:
            lowercase							    =       'regression'
          elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
            lowercase							    =       'single_label_classification'
          else:
            lowercase							    =       'multi_label_classification'

        if self.config.problem_type == "regression":
          lowercase							    =       MSELoss()
          if self.num_labels == 1:
            lowercase							    =       loss_fct(logits.squeeze()							,		labels.squeeze()       )
          else:
            lowercase							    =       loss_fct(_lowerCamelCase							,		_lowerCamelCase       )
        elif self.config.problem_type == "single_label_classification":
          lowercase							    =       CrossEntropyLoss()
          lowercase							    =       loss_fct(logits.view(-1							,		self.num_labels       )							,		labels.view(-1       )       )
        elif self.config.problem_type == "multi_label_classification":
          lowercase							    =       BCEWithLogitsLoss()
          lowercase							    =       loss_fct(_lowerCamelCase							,		_lowerCamelCase       )

      if not return_dict:
        lowercase							    =       (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"""



def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  int    ):





  '''simple docstring'''





  return sum(i for i in range(1		,					number // 2 + 1    ) if number % i == 0    ) == number


if __name__ == "__main__":
    print('Program to check whether a number is a Perfect number or not...')
    _UpperCamelCase		:  Tuple						=		int(input('Enter number: ').strip())
    print(F'''{number} is {'' if perfect(number) else 'not '}a Perfect Number.''')


