

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


# General docstring
UpperCAmelCase       =     '''MobileNetV1Config'''

# Base docstring
UpperCAmelCase       =     '''google/mobilenet_v1_1.0_224'''
UpperCAmelCase       =     [1, 1024, 7, 7]

# Image classification docstring
UpperCAmelCase       =     '''google/mobilenet_v1_1.0_224'''
UpperCAmelCase       =     '''tabby, tabby cat'''


UpperCAmelCase       =     [
    '''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  __UpperCamelCase							(		lowercase__  :     List[str],    lowercase__  :     Union[str, Any],    lowercase__  :     Dict=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  __UpperCamelCase							(		lowercase__  :     Optional[int],    lowercase__  :     int,    lowercase__  :     Dict       ):






     '''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  __UpperCamelCase							(		lowercase__  :     torch.Tensor,    lowercase__  :     nn.Convad       ):






     '''simple docstring'''





     __lowercase							=features.shape[-2:]
     __lowercase							=conv_layer.stride
     __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      lowerCAmelCase   (					nn.Module      ):







       def __init__(							self	:       List[Any]  ,					__lowercase	:       MobileNetVaConfig  ,					__lowercase	:       int  ,					__lowercase	:       int  ,					__lowercase	:       int  ,					__lowercase	:       Optional[int] = 1  ,					__lowercase	:       Optional[int] = 1  ,					__lowercase	:       bool = False  ,					__lowercase	:       Optional[bool] = True  ,					__lowercase	:       Optional[bool or str] = True  ,					):







            """simple docstring"""







            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=__lowercase  ,					out_channels=__lowercase  ,					kernel_size=__lowercase  ,					stride=__lowercase  ,					padding=__lowercase  ,					groups=__lowercase  ,					bias=__lowercase  ,					padding_mode='zeros'  ,					)

            if use_normalization:
                 __lowercase							=nn.BatchNormad(
                     num_features=__lowercase  ,					eps=config.layer_norm_eps  ,					momentum=0.9_9_9_7  ,					affine=__lowercase  ,					track_running_stats=__lowercase  ,					)
            else:
                 __lowercase							=None

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







       def 	snake_case      (							self	:       str  ,					__lowercase	:       torch.Tensor					):







            """simple docstring"""







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






class      lowerCAmelCase   (					_A      ):
       lowerCAmelCase_				=       MobileNetVaConfig
       lowerCAmelCase_				=       load_tf_weights_in_mobilenet_va
       lowerCAmelCase_				=       "mobilenet_v1"
       lowerCAmelCase_				=       "pixel_values"
       lowerCAmelCase_				=       False







       def 	snake_case      (							self	:       Any  ,					__lowercase	:       Union[nn.Linear, nn.Convad]					):







            """simple docstring"""







            if isinstance(__lowercase  ,					(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(__lowercase  ,					nn.BatchNormad					):
                 module.bias.data.zero_()
                 module.weight.data.fill_(1.0					)






UpperCAmelCase       =     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.
'''

UpperCAmelCase       =     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."      ,	_A      ,	)
class      lowerCAmelCase   (					_A      ):







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







            """simple docstring"""







            super().__init__(__lowercase					)
            __lowercase							=config

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

            __lowercase							=MobileNetVaConvLayer(
                __lowercase  ,					in_channels=config.num_channels  ,					out_channels=__lowercase  ,					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(13					):
                 __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(
                         __lowercase  ,					in_channels=__lowercase  ,					out_channels=__lowercase  ,					kernel_size=3  ,					stride=strides[i]  ,					groups=__lowercase  ,					)					)

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

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

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







       def 	snake_case      (							self	:       Any  ,					__lowercase	:       Optional[Any]					):







            """simple docstring"""







            raise NotImplementedError







       @add_start_docstrings_to_model_forward(__lowercase					)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC  ,					output_type=__lowercase  ,					config_class=_CONFIG_FOR_DOC  ,					modality='vision'  ,					expected_output=_EXPECTED_OUTPUT_SHAPE  ,					)
       def 	snake_case      (							self	:       List[Any]  ,					__lowercase	:       Optional[torch.Tensor] = None  ,					__lowercase	:       Optional[bool] = None  ,					__lowercase	:       Optional[bool] = None  ,					):







            """simple docstring"""







            __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(__lowercase					)

            __lowercase							=() if output_hidden_states else None

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

                 if output_hidden_states:
                      __lowercase							=all_hidden_states + (hidden_states,)

            __lowercase							=hidden_states

            if self.pooler is not None:
                 __lowercase							=torch.flatten(self.pooler(__lowercase					)  ,					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=__lowercase  ,					pooler_output=__lowercase  ,					hidden_states=__lowercase  ,					)






@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      lowerCAmelCase   (					_A      ):







       def __init__(							self	:       List[str]  ,					__lowercase	:       MobileNetVaConfig					):







            """simple docstring"""







            super().__init__(__lowercase					)

            __lowercase							=config.num_labels
            __lowercase							=MobileNetVaModel(__lowercase					)

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

            # Classifier head
            __lowercase							=nn.Dropout(config.classifier_dropout_prob  ,					inplace=__lowercase					)
            __lowercase							=nn.Linear(__lowercase  ,					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(__lowercase					)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT  ,					output_type=__lowercase  ,					config_class=_CONFIG_FOR_DOC  ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT  ,					)
       def 	snake_case      (							self	:       Optional[Any]  ,					__lowercase	:       Optional[torch.Tensor] = None  ,					__lowercase	:       Optional[bool] = None  ,					__lowercase	:       Optional[torch.Tensor] = None  ,					__lowercase	:       Optional[bool] = None  ,					):







            """simple docstring"""







            __lowercase							=return_dict if return_dict is not None else self.config.use_return_dict

            __lowercase							=self.mobilenet_va(__lowercase  ,					output_hidden_states=__lowercase  ,					return_dict=__lowercase					)

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

            __lowercase							=self.classifier(self.dropout(__lowercase					)					)

            __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(__lowercase  ,					__lowercase					)
                 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(__lowercase  ,					__lowercase					)

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

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










"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__A		:       List[str]  				=		{
    '''configuration_mobilenet_v2''': [
        '''MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''MobileNetV2Config''',
        '''MobileNetV2OnnxConfig''',
    ],
}

try:
						if not is_vision_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__A		:       Dict  				=		['''MobileNetV2FeatureExtractor''']
						__A		:       Optional[int]  				=		['''MobileNetV2ImageProcessor''']


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__A		:       Optional[Any]  				=		[
						    '''MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''MobileNetV2ForImageClassification''',
						    '''MobileNetV2ForSemanticSegmentation''',
						    '''MobileNetV2Model''',
						    '''MobileNetV2PreTrainedModel''',
						    '''load_tf_weights_in_mobilenet_v2''',
						]


if TYPE_CHECKING:
						from .configuration_mobilenet_va import (
						    MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
						    MobileNetVaConfig,
						    MobileNetVaOnnxConfig,
						)

						try:
												if not is_vision_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
												from .image_processing_mobilenet_va import MobileNetVaImageProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_mobilenet_va import (
												    MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
												    MobileNetVaForImageClassification,
												    MobileNetVaForSemanticSegmentation,
												    MobileNetVaModel,
												    MobileNetVaPreTrainedModel,
												    load_tf_weights_in_mobilenet_va,
												)


else:
						import sys

						__A		:       List[Any]  				=		_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



