



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__    =	logging.get_logger(__name__)


# General docstring
a__    =	"""MobileNetV1Config"""

# Base docstring
a__    =	"""google/mobilenet_v1_1.0_224"""
a__    =	[1, 10_24, 7, 7]

# Image classification docstring
a__    =	"""google/mobilenet_v1_1.0_224"""
a__    =	"""tabby, tabby cat"""


a__    =	[
    """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       (   SCREAMING_SNAKE_CASE__       :	Optional[Any]				,       SCREAMING_SNAKE_CASE__       :	int				,       SCREAMING_SNAKE_CASE__       :	List[Any]=None				)  ->     str:
 _snake_case    :  str					=					{}

 if isinstance(SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__				):
  _snake_case    :  Tuple					=					model.mobilenet_va
 else:
  _snake_case    :  str					=					model

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

 for i in range(13				):
  _snake_case    :  Union[str, Any]					=					i + 1
  _snake_case    :  List[Any]					=					i * 2

  _snake_case    :  Any					=					backbone.layer[pt_index]
  _snake_case    :  Tuple					=					F'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
  _snake_case    :  Optional[Any]					=					pointer.convolution.weight
  _snake_case    :  int					=					pointer.normalization.bias
  _snake_case    :  Tuple					=					pointer.normalization.weight
  _snake_case    :  int					=					pointer.normalization.running_mean
  _snake_case    :  Optional[int]					=					pointer.normalization.running_var

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

 if isinstance(SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__				):
  _snake_case    :  Tuple					=					"""MobilenetV1/Logits/Conv2d_1c_1x1/"""
  _snake_case    :  Dict					=					model.classifier.weight
  _snake_case    :  List[Any]					=					model.classifier.bias

 return tf_to_pt_map



def       lowercase       (   SCREAMING_SNAKE_CASE__       :	Optional[int]				,       SCREAMING_SNAKE_CASE__       :	List[str]				,       SCREAMING_SNAKE_CASE__       :	Union[str, Any]				)  ->     Optional[Any]:
 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
 _snake_case    :  Union[str, Any]					=					tf.train.list_variables(SCREAMING_SNAKE_CASE__				)
 _snake_case    :  str					=					{}
 for name, shape in init_vars:
  logger.info(F'''Loading TF weight {name} with shape {shape}'''				)
  _snake_case    :  Any					=					tf.train.load_variable(SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__				)
  _snake_case    :  int					=					array

 # Build TF to PyTorch weights loading map
 _snake_case    :  str					=					_build_tf_to_pytorch_map(SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__				,       SCREAMING_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

  _snake_case    :  Optional[int]					=					tf_weights[name]

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

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

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



def       lowercase       (   SCREAMING_SNAKE_CASE__       :	torch.Tensor				,       SCREAMING_SNAKE_CASE__       :	nn.Convad				)  ->     torch.Tensor:
 _snake_case	,    _snake_case    :  Optional[int]					=					features.shape[-2:]
 _snake_case	,    _snake_case    :  List[str]					=					conv_layer.stride
 _snake_case	,    _snake_case    :  Optional[Any]					=					conv_layer.kernel_size

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

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

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

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







class 		snake_case						(	nn.Module  ):



   '''simple docstring'''






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

    """simple docstring"""







    super().__init__()
    _snake_case    :  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.''')

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

    _snake_case    :  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:
     _snake_case    :  Tuple					=					nn.BatchNormad(
         num_features=lowerCAmelCase				,		eps=config.layer_norm_eps				,		momentum=0.9_997				,		affine=lowerCAmelCase				,		track_running_stats=lowerCAmelCase				,		)
    else:
     _snake_case    :  Optional[Any]					=					None

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


   def      UpperCamelCase_  (					self							:			Optional[Any]				,		lowerCAmelCase							:			torch.Tensor)				->				torch.Tensor:

    """simple docstring"""







    if self.config.tf_padding:
     _snake_case    :  Dict					=					apply_tf_padding(lowerCAmelCase				,		self.convolution)
    _snake_case    :  List[Any]					=					self.convolution(lowerCAmelCase)
    if self.normalization is not None:
     _snake_case    :  Any					=					self.normalization(lowerCAmelCase)
    if self.activation is not None:
     _snake_case    :  List[str]					=					self.activation(lowerCAmelCase)
    return features







class 		snake_case						(	SCREAMING_SNAKE_CASE_  ):



   '''simple docstring'''






   snake_case_					: Any          =		MobileNetVaConfig
   snake_case_					: List[Any]          =		load_tf_weights_in_mobilenet_va
   snake_case_					: Optional[Any]          =		"""mobilenet_v1"""
   snake_case_					: Optional[int]          =		"""pixel_values"""
   snake_case_					: Tuple          =		False

   def      UpperCamelCase_  (					self							:			Optional[Any]				,		lowerCAmelCase							:			Union[nn.Linear, nn.Convad])				->				None:

    """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)
a__    =	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__    =	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."""					,SCREAMING_SNAKE_CASE_					,)
class 		snake_case						(	SCREAMING_SNAKE_CASE_  ):



   '''simple docstring'''






   def __init__(					self							:			int				,		lowerCAmelCase							:			MobileNetVaConfig				,		lowerCAmelCase							:			bool = True)				->				Optional[int]:

    """simple docstring"""







    super().__init__(lowerCAmelCase)
    _snake_case    :  Tuple					=					config

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

    _snake_case    :  Tuple					=					MobileNetVaConvLayer(
        lowerCAmelCase				,		in_channels=config.num_channels				,		out_channels=lowerCAmelCase				,		kernel_size=3				,		stride=2				,		)

    _snake_case    :  Optional[Any]					=					[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

    _snake_case    :  Any					=					nn.ModuleList()
    for i in range(13):
     _snake_case    :  Any					=					out_channels

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

    _snake_case    :  List[str]					=					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							:			Union[str, Any])				->				int:

    """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[Any]				,		lowerCAmelCase							:			Optional[torch.Tensor] = None				,		lowerCAmelCase							:			Optional[bool] = None				,		lowerCAmelCase							:			Optional[bool] = None				,		)				->				Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:

    """simple docstring"""







    _snake_case    :  Any					=					(
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    _snake_case    :  int					=					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""")

    _snake_case    :  Optional[Any]					=					self.conv_stem(lowerCAmelCase)

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

    for i, layer_module in enumerate(self.layer):
     _snake_case    :  Optional[int]					=					layer_module(lowerCAmelCase)

     if output_hidden_states:
      _snake_case    :  List[Any]					=					all_hidden_states + (hidden_states,)

    _snake_case    :  Union[str, Any]					=					hidden_states

    if self.pooler is not None:
     _snake_case    :  Union[str, Any]					=					torch.flatten(self.pooler(lowerCAmelCase)				,		start_dim=1)
    else:
     _snake_case    :  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.
    """					,SCREAMING_SNAKE_CASE_					,)
class 		snake_case						(	SCREAMING_SNAKE_CASE_  ):



   '''simple docstring'''






   def __init__(					self							:			Optional[Any]				,		lowerCAmelCase							:			MobileNetVaConfig)				->				None:

    """simple docstring"""







    super().__init__(lowerCAmelCase)

    _snake_case    :  Any					=					config.num_labels
    _snake_case    :  List[Any]					=					MobileNetVaModel(lowerCAmelCase)

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

    # Classifier head
    _snake_case    :  int					=					nn.Dropout(config.classifier_dropout_prob				,		inplace=lowerCAmelCase)
    _snake_case    :  str					=					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[str]				,		lowerCAmelCase							:			Optional[torch.Tensor] = None				,		lowerCAmelCase							:			Optional[bool] = None				,		lowerCAmelCase							:			Optional[torch.Tensor] = None				,		lowerCAmelCase							:			Optional[bool] = None				,		)				->				Union[tuple, ImageClassifierOutputWithNoAttention]:

    """simple docstring"""







    _snake_case    :  str					=					return_dict if return_dict is not None else self.config.use_return_dict

    _snake_case    :  Tuple					=					self.mobilenet_va(lowerCAmelCase				,		output_hidden_states=lowerCAmelCase				,		return_dict=lowerCAmelCase)

    _snake_case    :  Optional[Any]					=					outputs.pooler_output if return_dict else outputs[1]

    _snake_case    :  Dict					=					self.classifier(self.dropout(lowerCAmelCase))

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

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

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





from __future__ import annotations

from math import pi

# Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of
# Pi and the function
a__    =	1.0_54_57_18_17E-34  # unit of ℏ : J * s

a__    =	3E8  # unit of c : m * s^-1



def       lowercase       (   SCREAMING_SNAKE_CASE__       :	float				,       SCREAMING_SNAKE_CASE__       :	float				,       SCREAMING_SNAKE_CASE__       :	float				)  ->     dict[str, float]:

 if (force, area, distance).count(0				) != 1:
  raise ValueError("""One and only one argument must be 0"""				)
 if force < 0:
  raise ValueError("""Magnitude of force can not be negative"""				)
 if distance < 0:
  raise ValueError("""Distance can not be negative"""				)
 if area < 0:
  raise ValueError("""Area can not be negative"""				)
 if force == 0:
  _snake_case    :  Union[str, Any]					=					(REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (
      240 * (distance) ** 4
  )
  return {"force": force}
 elif area == 0:
  _snake_case    :  Optional[Any]					=					(240 * force * (distance) ** 4) / (
      REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2
  )
  return {"area": area}
 elif distance == 0:
  _snake_case    :  str					=					(
      (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force)
  ) ** (1 / 4)
  return {"distance": distance}
 raise ValueError("""One and only one argument must be 0"""				)


# Run doctest
if __name__ == "__main__":
  import doctest

  doctest.testmod()
