
'''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__      :		List[str]       							=  logging.get_logger(__name__)


# General docstring
UpperCamelCase__      :		Union[str, Any]       							=  "MobileNetV1Config"

# Base docstring
UpperCamelCase__      :		List[Any]       							=  "google/mobilenet_v1_1.0_224"
UpperCamelCase__      :		Union[str, Any]       							=  [1, 1_024, 7, 7]

# Image classification docstring
UpperCamelCase__      :		int       							=  "google/mobilenet_v1_1.0_224"
UpperCamelCase__      :		Optional[Any]       							=  "tabby, tabby cat"


UpperCamelCase__      :		Union[str, 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_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=None						)     ->     Dict:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				{}

   if isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      _SCREAMING_SNAKE_CASE      =				model.mobilenet_va
   else:
      _SCREAMING_SNAKE_CASE      =				model

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

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

      _SCREAMING_SNAKE_CASE      =				backbone.layer[pt_index]
      _SCREAMING_SNAKE_CASE      =				F"MobilenetV1/Conv2d_{tf_index}_depthwise/"
      _SCREAMING_SNAKE_CASE      =				pointer.convolution.weight
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.bias
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.weight
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.running_mean
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.running_var

      _SCREAMING_SNAKE_CASE      =				backbone.layer[pt_index + 1]
      _SCREAMING_SNAKE_CASE      =				F"MobilenetV1/Conv2d_{tf_index}_pointwise/"
      _SCREAMING_SNAKE_CASE      =				pointer.convolution.weight
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.bias
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.weight
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.running_mean
      _SCREAMING_SNAKE_CASE      =				pointer.normalization.running_var

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

   return tf_to_pt_map
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)     ->     int:




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

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

      _SCREAMING_SNAKE_CASE      =				tf_weights[name]

      if "depthwise_weights" in name:
         logger.info("""Transposing depthwise"""						)
         _SCREAMING_SNAKE_CASE      =				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
            _SCREAMING_SNAKE_CASE      =				array.squeeze().transpose()
         else:
            _SCREAMING_SNAKE_CASE      =				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}"						)
      _SCREAMING_SNAKE_CASE      =				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    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)     ->     torch.Tensor:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				features.shape[-2:]
   _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				conv_layer.stride
   _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				conv_layer.kernel_size

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

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

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

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

class    _a				(nn.Module):





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__ = 1       ,							A__ = 1       ,							A__ = False       ,							A__ = True       ,							A__ = True       ,							)    ->			None:
          super().__init__()
          _SCREAMING_SNAKE_CASE      =				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."      )

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

          _SCREAMING_SNAKE_CASE      =				nn.Convad(
              in_channels=A__       ,							out_channels=A__       ,							kernel_size=A__       ,							stride=A__       ,							padding=A__       ,							groups=A__       ,							bias=A__       ,							padding_mode="""zeros"""       ,							)

          if use_normalization:
             _SCREAMING_SNAKE_CASE      =				nn.BatchNormad(
                 num_features=A__       ,							eps=config.layer_norm_eps       ,							momentum=0.9997       ,							affine=A__       ,							track_running_stats=A__       ,							)
          else:
             _SCREAMING_SNAKE_CASE      =				None

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






       def        UpperCamelCase				(							self       ,							A__      )    ->			torch.Tensor:
          if self.config.tf_padding:
             _SCREAMING_SNAKE_CASE      =				apply_tf_padding(A__       ,							self.convolution      )
          _SCREAMING_SNAKE_CASE      =				self.convolution(A__      )
          if self.normalization is not None:
             _SCREAMING_SNAKE_CASE      =				self.normalization(A__      )
          if self.activation is not None:
             _SCREAMING_SNAKE_CASE      =				self.activation(A__      )
          return features






class    _a				(_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  MobileNetVaConfig
       SCREAMING_SNAKE_CASE      =  load_tf_weights_in_mobilenet_va
       SCREAMING_SNAKE_CASE      =  'mobilenet_v1'
       SCREAMING_SNAKE_CASE      =  'pixel_values'
       SCREAMING_SNAKE_CASE      =  False






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






UpperCamelCase__      :		Optional[int]       							=  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__      :		Optional[int]       							=  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.'  ,					_lowerCamelCase  ,					)
class    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__ = True      )    ->			Any:
          super().__init__(A__      )
          _SCREAMING_SNAKE_CASE      =				config

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

          _SCREAMING_SNAKE_CASE      =				MobileNetVaConvLayer(
              A__       ,							in_channels=config.num_channels       ,							out_channels=A__       ,							kernel_size=3       ,							stride=2       ,							)

          _SCREAMING_SNAKE_CASE      =				[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

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

             if strides[i] == 2 or i == 0:
                depth *= 2
                _SCREAMING_SNAKE_CASE      =				max(int(depth * config.depth_multiplier      )       ,							config.min_depth      )

             self.layer.append(
                 MobileNetVaConvLayer(
                     A__       ,							in_channels=A__       ,							out_channels=A__       ,							kernel_size=3       ,							stride=strides[i]       ,							groups=A__       ,							)      )

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

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

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






       def        UpperCamelCase				(							self       ,							A__      )    ->			Optional[int]:
          raise NotImplementedError






       @add_start_docstrings_to_model_forward(A__      )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC       ,							output_type=A__       ,							config_class=_CONFIG_FOR_DOC       ,							modality="""vision"""       ,							expected_output=_EXPECTED_OUTPUT_SHAPE       ,							)
       def        UpperCamelCase				(							self       ,							A__ = None       ,							A__ = None       ,							A__ = None       ,							)    ->			Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
          _SCREAMING_SNAKE_CASE      =				(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          _SCREAMING_SNAKE_CASE      =				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"""      )

          _SCREAMING_SNAKE_CASE      =				self.conv_stem(A__      )

          _SCREAMING_SNAKE_CASE      =				() if output_hidden_states else None

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

             if output_hidden_states:
                _SCREAMING_SNAKE_CASE      =				all_hidden_states + (hidden_states,)

          _SCREAMING_SNAKE_CASE      =				hidden_states

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






@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    _a				(_lowerCamelCase):





       """simple docstring"""




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

          _SCREAMING_SNAKE_CASE      =				config.num_labels
          _SCREAMING_SNAKE_CASE      =				MobileNetVaModel(A__      )

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

          # Classifier head
          _SCREAMING_SNAKE_CASE      =				nn.Dropout(config.classifier_dropout_prob       ,							inplace=A__      )
          _SCREAMING_SNAKE_CASE      =				nn.Linear(A__       ,							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(A__      )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT       ,							output_type=A__       ,							config_class=_CONFIG_FOR_DOC       ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,							)
       def        UpperCamelCase				(							self       ,							A__ = None       ,							A__ = None       ,							A__ = None       ,							A__ = None       ,							)    ->			Union[tuple, ImageClassifierOutputWithNoAttention]:
          _SCREAMING_SNAKE_CASE      =				return_dict if return_dict is not None else self.config.use_return_dict

          _SCREAMING_SNAKE_CASE      =				self.mobilenet_va(A__       ,							output_hidden_states=A__       ,							return_dict=A__      )

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

          _SCREAMING_SNAKE_CASE      =				self.classifier(self.dropout(A__      )      )

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

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

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

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








'''simple docstring'''



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available


UpperCamelCase__      :		int       							=  {"tokenization_herbert": ["HerbertTokenizer"]}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase__      :		Tuple       							=  ["HerbertTokenizerFast"]


if TYPE_CHECKING:
     from .tokenization_herbert import HerbertTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_herbert_fast import HerbertTokenizerFast

else:
     import sys

     UpperCamelCase__      :		Tuple       							=  _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)






