






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


_snake_case          =   logging.get_logger(__name__)


# General docstring
_snake_case          =   'MobileNetV1Config'

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

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


_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 			lowerCAmelCase__     (     UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__=None				):



  '''simple docstring'''
  _a  :       Optional[int]             =	{}

  if isinstance(UpperCamelCase__     ,   UpperCamelCase__				):
    _a  :       Dict             =	model.mobilenet_va
  else:
    _a  :       Optional[Any]             =	model

  _a  :       int             =	"""MobilenetV1/Conv2d_0/"""
  _a  :       Any             =	backbone.conv_stem.convolution.weight
  _a  :       str             =	backbone.conv_stem.normalization.bias
  _a  :       Any             =	backbone.conv_stem.normalization.weight
  _a  :       Any             =	backbone.conv_stem.normalization.running_mean
  _a  :       int             =	backbone.conv_stem.normalization.running_var

  for i in range(1_3				):
    _a  :       int             =	i + 1
    _a  :       Optional[int]             =	i * 2

    _a  :       Optional[Any]             =	backbone.layer[pt_index]
    _a  :       List[str]             =	F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
    _a  :       Any             =	pointer.convolution.weight
    _a  :       Dict             =	pointer.normalization.bias
    _a  :       Tuple             =	pointer.normalization.weight
    _a  :       Optional[Any]             =	pointer.normalization.running_mean
    _a  :       int             =	pointer.normalization.running_var

    _a  :       Optional[int]             =	backbone.layer[pt_index + 1]
    _a  :       Optional[Any]             =	F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
    _a  :       Optional[int]             =	pointer.convolution.weight
    _a  :       str             =	pointer.normalization.bias
    _a  :       Optional[Any]             =	pointer.normalization.weight
    _a  :       Any             =	pointer.normalization.running_mean
    _a  :       Union[str, Any]             =	pointer.normalization.running_var

  if isinstance(UpperCamelCase__     ,   UpperCamelCase__				):
    _a  :       Optional[int]             =	"""MobilenetV1/Logits/Conv2d_1c_1x1/"""
    _a  :       Any             =	model.classifier.weight
    _a  :       Union[str, Any]             =	model.classifier.bias

  return tf_to_pt_map

def 			lowerCAmelCase__     (     UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__				):



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

  # Build TF to PyTorch weights loading map
  _a  :       Optional[Any]             =	_build_tf_to_pytorch_map(UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__				)

  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

    _a  :       Optional[int]             =	tf_weights[name]

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

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

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

def 			lowerCAmelCase__     (     UpperCamelCase__     ,   UpperCamelCase__				):



  '''simple docstring'''
  _a      ,  _a  :       Optional[Any]             =	features.shape[-2:]
  _a      ,  _a  :       Dict             =	conv_layer.stride
  _a      ,  _a  :       Dict             =	conv_layer.kernel_size

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

  if in_width % stride_width == 0:
    _a  :       Any             =	max(kernel_width - stride_width     ,   0				)
  else:
    _a  :       int             =	max(kernel_width - (in_width % stride_width)     ,   0				)

  _a  :       str             =	pad_along_width // 2
  _a  :       Union[str, Any]             =	pad_along_width - pad_left
  _a  :       Optional[int]             =	pad_along_height // 2
  _a  :       List[Any]             =	pad_along_height - pad_top

  _a  :       Optional[Any]             =	(pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(UpperCamelCase__     ,   UpperCamelCase__     ,   """constant"""     ,   0.0				)






class        UpperCamelCase			(	nn.Module      ):


 def __init__(     self		:						Optional[Any]							,						UpperCAmelCase__		:						MobileNetVaConfig							,						UpperCAmelCase__		:						int							,						UpperCAmelCase__		:						int							,						UpperCAmelCase__		:						int							,						UpperCAmelCase__		:						Optional[int] = 1							,						UpperCAmelCase__		:						Optional[int] = 1							,						UpperCAmelCase__		:						bool = False							,						UpperCAmelCase__		:						Optional[bool] = True							,						UpperCAmelCase__		:						Optional[bool or str] = True							,						)					->       None:
   super().__init__()
   _a  :       Any             =	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."""							)

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

   _a  :       List[Any]             =	nn.Convad(
       in_channels=UpperCAmelCase__							,						out_channels=UpperCAmelCase__							,						kernel_size=UpperCAmelCase__							,						stride=UpperCAmelCase__							,						padding=UpperCAmelCase__							,						groups=UpperCAmelCase__							,						bias=UpperCAmelCase__							,						padding_mode="""zeros"""							,						)

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

   if use_activation:
     if isinstance(UpperCAmelCase__							,						UpperCAmelCase__							):
       _a  :       Optional[int]             =	ACTaFN[use_activation]
     elif isinstance(config.hidden_act							,						UpperCAmelCase__							):
       _a  :       int             =	ACTaFN[config.hidden_act]
     else:
       _a  :       str             =	config.hidden_act
   else:
     _a  :       Union[str, Any]             =	None







 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						torch.Tensor							)					->       torch.Tensor:
   if self.config.tf_padding:
     _a  :       List[str]             =	apply_tf_padding(UpperCAmelCase__							,						self.convolution							)
   _a  :       List[str]             =	self.convolution(UpperCAmelCase__							)
   if self.normalization is not None:
     _a  :       Optional[int]             =	self.normalization(UpperCAmelCase__							)
   if self.activation is not None:
     _a  :       Dict             =	self.activation(UpperCAmelCase__							)
   return features







class        UpperCamelCase			(	snake_case_      ):
 UpperCamelCase					:       Dict			=					MobileNetVaConfig
 UpperCamelCase					:       Optional[Any]			=					load_tf_weights_in_mobilenet_va
 UpperCamelCase					:       Dict			=					'''mobilenet_v1'''
 UpperCamelCase					:       Any			=					'''pixel_values'''
 UpperCamelCase					:       str			=					False


 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						Union[nn.Linear, nn.Convad]							)					->       None:
   if isinstance(UpperCAmelCase__							,						(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(UpperCAmelCase__							,						nn.BatchNormad							):
     module.bias.data.zero_()
     module.weight.data.fill_(1.0							)







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

_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.'''		,     snake_case_		,     )
class        UpperCamelCase			(	snake_case_      ):


 def __init__(     self		:						Any							,						UpperCAmelCase__		:						MobileNetVaConfig							,						UpperCAmelCase__		:						bool = True							)					->       Optional[int]:
   super().__init__(UpperCAmelCase__							)
   _a  :       List[Any]             =	config

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

   _a  :       Optional[Any]             =	MobileNetVaConvLayer(
       UpperCAmelCase__							,						in_channels=config.num_channels							,						out_channels=UpperCAmelCase__							,						kernel_size=3							,						stride=2							,						)

   _a  :       int             =	[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

   _a  :       List[Any]             =	nn.ModuleList()
   for i in range(13							):
     _a  :       List[Any]             =	out_channels

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

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

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

   _a  :       Dict             =	nn.AdaptiveAvgPoolad((1, 1)							) if add_pooling_layer else None

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


 def _lowercase	(     self		:						List[Any]							,						UpperCAmelCase__		:						Dict							)					->       Any:
   raise NotImplementedError







 @add_start_docstrings_to_model_forward(UpperCAmelCase__							)
 @add_code_sample_docstrings(
     checkpoint=_CHECKPOINT_FOR_DOC							,						output_type=UpperCAmelCase__							,						config_class=_CONFIG_FOR_DOC							,						modality="""vision"""							,						expected_output=_EXPECTED_OUTPUT_SHAPE							,						)
 def _lowercase	(     self		:						Any							,						UpperCAmelCase__		:						Optional[torch.Tensor] = None							,						UpperCAmelCase__		:						Optional[bool] = None							,						UpperCAmelCase__		:						Optional[bool] = None							,						)					->       Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
   _a  :       Union[str, Any]             =	(
       output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
   )
   _a  :       Union[str, Any]             =	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"""							)

   _a  :       Tuple             =	self.conv_stem(UpperCAmelCase__							)

   _a  :       Tuple             =	() if output_hidden_states else None

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

     if output_hidden_states:
       _a  :       int             =	all_hidden_states + (hidden_states,)

   _a  :       int             =	hidden_states

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







@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.
    '''		,     snake_case_		,     )
class        UpperCamelCase			(	snake_case_      ):


 def __init__(     self		:						List[Any]							,						UpperCAmelCase__		:						MobileNetVaConfig							)					->       None:
   super().__init__(UpperCAmelCase__							)

   _a  :       int             =	config.num_labels
   _a  :       List[Any]             =	MobileNetVaModel(UpperCAmelCase__							)

   _a  :       Union[str, Any]             =	self.mobilenet_va.layer[-1].convolution.out_channels

   # Classifier head
   _a  :       Optional[int]             =	nn.Dropout(config.classifier_dropout_prob							,						inplace=UpperCAmelCase__							)
   _a  :       Tuple             =	nn.Linear(UpperCAmelCase__							,						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(UpperCAmelCase__							)
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT							,						output_type=UpperCAmelCase__							,						config_class=_CONFIG_FOR_DOC							,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,						)
 def _lowercase	(     self		:						Union[str, Any]							,						UpperCAmelCase__		:						Optional[torch.Tensor] = None							,						UpperCAmelCase__		:						Optional[bool] = None							,						UpperCAmelCase__		:						Optional[torch.Tensor] = None							,						UpperCAmelCase__		:						Optional[bool] = None							,						)					->       Union[tuple, ImageClassifierOutputWithNoAttention]:
   _a  :       Union[str, Any]             =	return_dict if return_dict is not None else self.config.use_return_dict

   _a  :       Any             =	self.mobilenet_va(UpperCAmelCase__							,						output_hidden_states=UpperCAmelCase__							,						return_dict=UpperCAmelCase__							)

   _a  :       Optional[int]             =	outputs.pooler_output if return_dict else outputs[1]

   _a  :       List[Any]             =	self.classifier(self.dropout(UpperCAmelCase__							)							)

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

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

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

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









"""simple docstring"""




import json
import os
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_snake_case          =   logging.get_logger(__name__)

_snake_case          =   {'vocab_file': 'vocab.json'}

_snake_case          =   {
    'vocab_file': {
        'mgp-str': 'https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json',
    }
}

_snake_case          =   {'mgp-str': 27}






class        UpperCamelCase			(	snake_case_      ):
 UpperCamelCase					:       List[str]			=					VOCAB_FILES_NAMES
 UpperCamelCase					:       Union[str, Any]			=					PRETRAINED_VOCAB_FILES_MAP
 UpperCamelCase					:       Optional[int]			=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES


 def __init__(     self		:						Optional[int]							,						UpperCAmelCase__		:						List[str]							,						UpperCAmelCase__		:						List[Any]="[GO]"							,						UpperCAmelCase__		:						Tuple="[GO]"							,						UpperCAmelCase__		:						Optional[int]="[s]"							,						UpperCAmelCase__		:						int="[GO]"							,						**UpperCAmelCase__		:						Dict							)					->       int:
   super().__init__(
       unk_token=UpperCAmelCase__							,						bos_token=UpperCAmelCase__							,						eos_token=UpperCAmelCase__							,						pad_token=UpperCAmelCase__							,						**UpperCAmelCase__							,						)

   with open(UpperCAmelCase__							,						encoding="""utf-8"""							) as vocab_handle:
     _a  :       int             =	json.load(UpperCAmelCase__							)
   _a  :       Optional[int]             =	{v: k for k, v in self.vocab.items()}


 @property
 def _lowercase	(     self		:						Dict							)					->       Union[str, Any]:
   return len(self.vocab							)


 def _lowercase	(     self		:						Union[str, Any]							)					->       str:
   return dict(self.vocab							,						**self.added_tokens_encoder							)


 def _lowercase	(     self		:						Dict							,						UpperCAmelCase__		:						str							)					->       Union[str, Any]:
   _a  :       Tuple             =	[]
   for s in text:
     char_tokens.extend(UpperCAmelCase__							)
   return char_tokens


 def _lowercase	(     self		:						List[Any]							,						UpperCAmelCase__		:						str							)					->       Dict:
   return self.vocab.get(UpperCAmelCase__							,						self.vocab.get(self.unk_token							)							)


 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						Tuple							)					->       List[Any]:
   return self.decoder.get(UpperCAmelCase__							)







 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						str							,						UpperCAmelCase__		:						Optional[str] = None							)					->       Tuple[str]:
   if not os.path.isdir(UpperCAmelCase__							):
     logger.error("""Vocabulary path ({}) should be a directory""".format(UpperCAmelCase__							)							)
     return
   _a  :       Tuple             =	os.path.join(
       UpperCAmelCase__							,						(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]							)

   with open(UpperCAmelCase__							,						"""w"""							,						encoding="""utf-8"""							) as f:
     f.write(json.dumps(self.vocab							,						indent=2							,						sort_keys=UpperCAmelCase__							,						ensure_ascii=UpperCAmelCase__							) + """\n"""							)

   return (vocab_file,)

