






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


_SCREAMING_SNAKE_CASE   =  logging.get_logger(__name__)


# General docstring
_SCREAMING_SNAKE_CASE   =  "MobileNetV1Config"

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

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


_SCREAMING_SNAKE_CASE   =  [
    "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        _snake_case   (_snake_case				:       List[str]      ,    _snake_case				:       Tuple      ,    _snake_case				:       Tuple=None)					->	Dict:
   _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        _snake_case   (_snake_case				:       Union[str, Any]      ,    _snake_case				:       Union[str, Any]      ,    _snake_case				:       str)					->	List[str]:
   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        _snake_case   (_snake_case				:       torch.Tensor      ,    _snake_case				:       nn.Convad)					->	torch.Tensor:
   _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 					SCREAMING_SNAKE_CASE_  (       nn.Module ):
       """simple docstring"""


       def __init__(				self	:List[Any],      snake_case	:MobileNetVaConfig,      snake_case	:int,      snake_case	:int,      snake_case	:int,      snake_case	:Optional[int] = 1,      snake_case	:Optional[int] = 1,      snake_case	:bool = False,      snake_case	:Optional[bool] = True,      snake_case	: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=snake_case,      out_channels=snake_case,      kernel_size=snake_case,      stride=snake_case,      padding=snake_case,      groups=snake_case,      bias=snake_case,      padding_mode='zeros',      )

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

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





       def 				UpperCamelCase__						(				self	:Optional[Any],      snake_case	:torch.Tensor):



          """simple docstring"""

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






class 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       __lowerCAmelCase    :		List[Any]					=MobileNetVaConfig
       __lowerCAmelCase    :		List[Any]					=load_tf_weights_in_mobilenet_va
       __lowerCAmelCase    :		Any					='''mobilenet_v1'''
       __lowerCAmelCase    :		Any					='''pixel_values'''
       __lowerCAmelCase    :		Any					=False





       def 				UpperCamelCase__						(				self	:Dict,      snake_case	:Union[nn.Linear, nn.Convad]):



          """simple docstring"""

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

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

_SCREAMING_SNAKE_CASE   =  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 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       def __init__(				self	:Tuple,      snake_case	:MobileNetVaConfig,      snake_case	:bool = True):



          """simple docstring"""

          super().__init__(snake_case)
          _lowercase              =config

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

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

             self.layer.append(
                 MobileNetVaConvLayer(
                     snake_case,      in_channels=snake_case,      out_channels=snake_case,      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	:Dict,      snake_case	:Tuple):



          """simple docstring"""

          raise NotImplementedError





       @add_start_docstrings_to_model_forward(snake_case)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC,      output_type=snake_case,      config_class=_CONFIG_FOR_DOC,      modality='vision',      expected_output=_EXPECTED_OUTPUT_SHAPE,      )
       def 				UpperCamelCase__						(				self	:Union[str, Any],      snake_case	:Optional[torch.Tensor] = None,      snake_case	:Optional[bool] = None,      snake_case	: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(snake_case)

          _lowercase              =() if output_hidden_states else None

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

             if output_hidden_states:
                _lowercase              =all_hidden_states + (hidden_states,)

          _lowercase              =hidden_states

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






@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.
    '''  ,						_a  ,						)
class 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       def __init__(				self	:str,      snake_case	:MobileNetVaConfig):



          """simple docstring"""

          super().__init__(snake_case)

          _lowercase              =config.num_labels
          _lowercase              =MobileNetVaModel(snake_case)

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

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



          """simple docstring"""

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

          _lowercase              =self.mobilenet_va(snake_case,      output_hidden_states=snake_case,      return_dict=snake_case)

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

          _lowercase              =self.classifier(self.dropout(snake_case))

          _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(snake_case,      snake_case)
             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(snake_case,      snake_case)

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

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










# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_SCREAMING_SNAKE_CASE   =  {
    "configuration_xmod": [
        "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "XmodConfig",
        "XmodOnnxConfig",
    ],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _SCREAMING_SNAKE_CASE   =  [
        "XMOD_PRETRAINED_MODEL_ARCHIVE_LIST",
        "XmodForCausalLM",
        "XmodForMaskedLM",
        "XmodForMultipleChoice",
        "XmodForQuestionAnswering",
        "XmodForSequenceClassification",
        "XmodForTokenClassification",
        "XmodModel",
        "XmodPreTrainedModel",
    ]

if TYPE_CHECKING:
    from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_xmod import (
            XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
            XmodForCausalLM,
            XmodForMaskedLM,
            XmodForMultipleChoice,
            XmodForQuestionAnswering,
            XmodForSequenceClassification,
            XmodForTokenClassification,
            XmodModel,
            XmodPreTrainedModel,
        )

else:
    import sys

    _SCREAMING_SNAKE_CASE   =  _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


