



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


lowerCAmelCase	:		Any				=   logging.get_logger(__name__)


# General docstring
lowerCAmelCase	:		Optional[Any]				=   '''MobileNetV1Config'''

# Base docstring
lowerCAmelCase	:		int				=   '''google/mobilenet_v1_1.0_224'''
lowerCAmelCase	:		Dict				=   [1, 1_0_2_4, 7, 7]

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


lowerCAmelCase	:		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   __lowerCAmelCase					(							lowerCamelCase   :						str				,		lowerCamelCase   :						Union[str, Any]				,		lowerCamelCase   :						List[Any]=None					):






 '''simple docstring'''




 __lowerCAmelCase												=  {}

 if isinstance(lowerCamelCase_				,		lowerCamelCase_					):
  __lowerCAmelCase												=  model.mobilenet_va
 else:
  __lowerCAmelCase												=  model

 __lowerCAmelCase												=  "MobilenetV1/Conv2d_0/"
 __lowerCAmelCase												=  backbone.conv_stem.convolution.weight
 __lowerCAmelCase												=  backbone.conv_stem.normalization.bias
 __lowerCAmelCase												=  backbone.conv_stem.normalization.weight
 __lowerCAmelCase												=  backbone.conv_stem.normalization.running_mean
 __lowerCAmelCase												=  backbone.conv_stem.normalization.running_var

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

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

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

 if isinstance(lowerCamelCase_				,		lowerCamelCase_					):
  __lowerCAmelCase												=  "MobilenetV1/Logits/Conv2d_1c_1x1/"
  __lowerCAmelCase												=  model.classifier.weight
  __lowerCAmelCase												=  model.classifier.bias

 return tf_to_pt_map



def   __lowerCAmelCase					(							lowerCamelCase   :						Tuple				,		lowerCamelCase   :						Optional[int]				,		lowerCamelCase   :						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
 __lowerCAmelCase												=  tf.train.list_variables(lowerCamelCase_					)
 __lowerCAmelCase												=  {}
 for name, shape in init_vars:
  logger.info(f'''Loading TF weight {name} with shape {shape}'''					)
  __lowerCAmelCase												=  tf.train.load_variable(lowerCamelCase_				,		lowerCamelCase_					)
  __lowerCAmelCase												=  array

 # Build TF to PyTorch weights loading map
 __lowerCAmelCase												=  _build_tf_to_pytorch_map(lowerCamelCase_				,		lowerCamelCase_				,		lowerCamelCase_					)

 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												=  tf_weights[name]

  if "depthwise_weights" in name:
   logger.info("Transposing depthwise"					)
   __lowerCAmelCase												=  np.transpose(lowerCamelCase_				,		(2, 3, 0, 1)					)
  elif "weights" in name:
   logger.info("Transposing"					)
   if len(pointer.shape					) == 2:  # copying into linear layer
    __lowerCAmelCase												=  array.squeeze().transpose()
   else:
    __lowerCAmelCase												=  np.transpose(lowerCamelCase_				,		(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												=  torch.from_numpy(lowerCamelCase_					)

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

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



def   __lowerCAmelCase					(							lowerCamelCase   :						torch.Tensor				,		lowerCamelCase   :						nn.Convad					):






 '''simple docstring'''




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

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

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

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

 __lowerCAmelCase												=  (pad_left, pad_right, pad_top, pad_bottom)
 return nn.functional.pad(lowerCamelCase_				,		lowerCamelCase_				,		"constant"				,		0.0					)






class 					UpperCAmelCase__	(		nn.Module ):



     def __init__(    self			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase = 1			,				UpperCamelCase = 1			,				UpperCamelCase = False			,				UpperCamelCase = True			,				UpperCamelCase = True			,				)     ->			None:
      super().__init__()
      __lowerCAmelCase												=  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												=  0 if config.tf_padding else int((kernel_size - 1) / 2     )

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

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



     def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			torch.Tensor:





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






class 					UpperCAmelCase__	(		lowerCAmelCase__ ):
     a      :     Optional[int]        =							MobileNetVaConfig
     a      :     Union[str, Any]        =							load_tf_weights_in_mobilenet_va
     a      :     Optional[Any]        =							"mobilenet_v1"
     a      :     int        =							"pixel_values"
     a      :     Union[str, Any]        =							False



     def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			None:





      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     )


lowerCAmelCase	:		Optional[Any]				=   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.
'''

lowerCAmelCase	:		Optional[int]				=   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."""							,       lowerCAmelCase__							,       )
class 					UpperCAmelCase__	(		lowerCAmelCase__ ):



     def __init__(    self			,				UpperCamelCase			,				UpperCamelCase = True     )     ->			str:
      super().__init__(_lowerCamelCase     )
      __lowerCAmelCase												=  config

      __lowerCAmelCase												=  32
      __lowerCAmelCase												=  max(int(depth * config.depth_multiplier     )			,				config.min_depth     )

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

      __lowerCAmelCase												=  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

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

       if strides[i] == 2 or i == 0:
        depth *= 2
        __lowerCAmelCase												=  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												=  nn.AdaptiveAvgPoolad((1, 1)     ) if add_pooling_layer else None

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



     def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			Tuple:
      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			,				UpperCamelCase = None			,				UpperCamelCase = None			,				UpperCamelCase = None			,				)     ->			Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
      __lowerCAmelCase												=  (
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      __lowerCAmelCase												=  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												=  self.conv_stem(_lowerCamelCase     )

      __lowerCAmelCase												=  () if output_hidden_states else None

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

       if output_hidden_states:
        __lowerCAmelCase												=  all_hidden_states + (hidden_states,)

      __lowerCAmelCase												=  hidden_states

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



     def __init__(    self			,				UpperCamelCase     )     ->			None:
      super().__init__(_lowerCamelCase     )

      __lowerCAmelCase												=  config.num_labels
      __lowerCAmelCase												=  MobileNetVaModel(_lowerCamelCase     )

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

      # Classifier head
      __lowerCAmelCase												=  nn.Dropout(config.classifier_dropout_prob			,				inplace=_lowerCamelCase     )
      __lowerCAmelCase												=  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			,				UpperCamelCase = None			,				UpperCamelCase = None			,				UpperCamelCase = None			,				UpperCamelCase = None			,				)     ->			Union[tuple, ImageClassifierOutputWithNoAttention]:
      __lowerCAmelCase												=  return_dict if return_dict is not None else self.config.use_return_dict

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

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

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

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

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

      if not return_dict:
       __lowerCAmelCase												=  (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'''



# flake8: noqa
# Lint as: python3

from typing import Dict, List, Optional, Type

from .. import config
from ..utils import logging
from .formatting import (
    ArrowFormatter,
    CustomFormatter,
    Formatter,
    PandasFormatter,
    PythonFormatter,
    TensorFormatter,
    format_table,
    query_table,
)
from .np_formatter import NumpyFormatter


lowerCAmelCase	:		List[str]				=   logging.get_logger(__name__)

lowerCAmelCase	:		Dict[Optional[str], Type[Formatter]]				=   {}
lowerCAmelCase	:		Dict[Optional[str], str]				=   {}
lowerCAmelCase	:		Dict[Optional[str], Exception]				=   {}



def   __lowerCAmelCase					(							lowerCamelCase   :						type				,		lowerCamelCase   :						Optional[str]				,		lowerCamelCase   :						Optional[List[str]] = None				,		):






	'''simple docstring'''




	__lowerCAmelCase												=  aliases if aliases is not None else []
	if format_type in _FORMAT_TYPES:
		logger.warning(
		    f'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})'''					)
	__lowerCAmelCase												=  formatter_cls
	for alias in set(aliases + [format_type]					):
		if alias in _FORMAT_TYPES_ALIASES:
			logger.warning(
			    f'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})'''					)
		__lowerCAmelCase												=  format_type



def   __lowerCAmelCase					(							lowerCamelCase   :						Exception				,		lowerCamelCase   :						Optional[str]				,		lowerCamelCase   :						Optional[List[str]] = None					):






	'''simple docstring'''




	__lowerCAmelCase												=  aliases if aliases is not None else []
	for alias in set(aliases + [format_type]					):
		__lowerCAmelCase												=  unavailable_error


# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['''python'''])
_register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow'''])
_register_formatter(NumpyFormatter, '''numpy''', aliases=['''np'''])
_register_formatter(PandasFormatter, '''pandas''', aliases=['''pd'''])
_register_formatter(CustomFormatter, '''custom''')

if config.TORCH_AVAILABLE:
	from .torch_formatter import TorchFormatter

	_register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch'''])
else:
	lowerCAmelCase	:		Optional[int]				=   ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''')
	_register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch'''])

if config.TF_AVAILABLE:
	from .tf_formatter import TFFormatter

	_register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf'''])
else:
	lowerCAmelCase	:		str				=   ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''')
	_register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf'''])

if config.JAX_AVAILABLE:
	from .jax_formatter import JaxFormatter

	_register_formatter(JaxFormatter, '''jax''', aliases=[])
else:
	lowerCAmelCase	:		Any				=   ValueError('''JAX needs to be installed to be able to return JAX arrays.''')
	_register_unavailable_formatter(_jax_error, '''jax''', aliases=[])



def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[str]					):






	'''simple docstring'''




	if format_type in _FORMAT_TYPES_ALIASES:
		return _FORMAT_TYPES_ALIASES[format_type]
	else:
		return format_type




def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[str]				,		**lowerCamelCase   :						Tuple					):






	'''simple docstring'''




	__lowerCAmelCase												=  get_format_type_from_alias(lowerCamelCase					)
	if format_type in _FORMAT_TYPES:
		return _FORMAT_TYPES[format_type](**lowerCamelCase					)
	if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
		raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
	else:
		raise ValueError(
		    f'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None					)}, but got \'{format_type}\''''					)