



'''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:   Optional[int]					=		logging.get_logger(__name__)


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

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

# Image classification docstring
lowerCAmelCase:   List[Any]					=		'google/mobilenet_v1_1.0_224'
lowerCAmelCase:   List[str]					=		'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__			(		_A					,     _A					,     _A=None							):
  a		:   Any	  =	{}

  if isinstance(lowerCAmelCase_					,     lowerCAmelCase_							):
    a		:   List[str]	  =	model.mobilenet_va
  else:
    a		:   Any	  =	model

  a		:   Dict	  =	'MobilenetV1/Conv2d_0/'
  a		:   int	  =	backbone.conv_stem.convolution.weight
  a		:   List[Any]	  =	backbone.conv_stem.normalization.bias
  a		:   Dict	  =	backbone.conv_stem.normalization.weight
  a		:   List[str]	  =	backbone.conv_stem.normalization.running_mean
  a		:   int	  =	backbone.conv_stem.normalization.running_var

  for i in range(13							):
    a		:   str	  =	i + 1
    a		:   Optional[Any]	  =	i * 2

    a		:   Optional[Any]	  =	backbone.layer[pt_index]
    a		:   List[Any]	  =	f"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
    a		:   List[str]	  =	pointer.convolution.weight
    a		:   str	  =	pointer.normalization.bias
    a		:   Optional[Any]	  =	pointer.normalization.weight
    a		:   Optional[Any]	  =	pointer.normalization.running_mean
    a		:   List[str]	  =	pointer.normalization.running_var

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

  if isinstance(lowerCAmelCase_					,     lowerCAmelCase_							):
    a		:   List[Any]	  =	'MobilenetV1/Logits/Conv2d_1c_1x1/'
    a		:   List[Any]	  =	model.classifier.weight
    a		:   Tuple	  =	model.classifier.bias

  return tf_to_pt_map
def  lowerCamelCase__			(		_A					,     _A					,     _A							):
  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[Any]	  =	tf.train.list_variables(lowerCAmelCase_							)
  a		:   Dict	  =	{}
  for name, shape in init_vars:
    logger.info(f"""Loading TF weight {name} with shape {shape}"""							)
    a		:   List[Any]	  =	tf.train.load_variable(lowerCAmelCase_					,     lowerCAmelCase_							)
    a		:   List[Any]	  =	array

  # Build TF to PyTorch weights loading map
  a		:   Union[str, Any]	  =	_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

    a		:   List[Any]	  =	tf_weights[name]

    if "depthwise_weights" in name:
      logger.info('Transposing depthwise'							)
      a		:   Any	  =	np.transpose(lowerCAmelCase_					,     (2, 3, 0, 1)							)
    elif "weights" in name:
      logger.info('Transposing'							)
      if len(pointer.shape							) == 2:  # copying into linear layer
        a		:   Union[str, Any]	  =	array.squeeze().transpose()
      else:
        a		:   List[Any]	  =	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}"""							)
    a		:   List[str]	  =	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__			(		_A					,     _A							):
  a  ,      a		:   Tuple	  =	features.shape[-2:]
  a  ,      a		:   Tuple	  =	conv_layer.stride
  a  ,      a		:   Optional[Any]	  =	conv_layer.kernel_size

  if in_height % stride_height == 0:
    a		:   int	  =	max(kernel_height - stride_height					,     0							)
  else:
    a		:   Dict	  =	max(kernel_height - (in_height % stride_height)					,     0							)

  if in_width % stride_width == 0:
    a		:   Union[str, Any]	  =	max(kernel_width - stride_width					,     0							)
  else:
    a		:   Any	  =	max(kernel_width - (in_width % stride_width)					,     0							)

  a		:   List[Any]	  =	pad_along_width // 2
  a		:   Tuple	  =	pad_along_width - pad_left
  a		:   int	  =	pad_along_height // 2
  a		:   Tuple	  =	pad_along_height - pad_top

  a		:   Any	  =	(pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(lowerCAmelCase_					,     lowerCAmelCase_					,     'constant'					,     0.0							)

class 				a__(   nn.Module      ):







    def __init__( self					:    int		,     __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		,     ):
      super().__init__()
      a		:   List[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		:   Optional[int]	  =	0 if config.tf_padding else int((kernel_size - 1) / 2      )

      a		:   int	  =	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:
        a		:   str	  =	nn.BatchNormad(
            num_features=__lowerCamelCase		,     eps=config.layer_norm_eps		,     momentum=0.9997		,     affine=__lowerCamelCase		,     track_running_stats=__lowerCamelCase		,     )
      else:
        a		:   Dict	  =	None

      if use_activation:
        if isinstance(__lowerCamelCase		,     __lowerCamelCase      ):
          a		:   Union[str, Any]	  =	ACTaFN[use_activation]
        elif isinstance(config.hidden_act		,     __lowerCamelCase      ):
          a		:   List[Any]	  =	ACTaFN[config.hidden_act]
        else:
          a		:   Tuple	  =	config.hidden_act
      else:
        a		:   List[Any]	  =	None







    def      lowercase_			( self					:    Optional[int]		,     __snake_case					:    torch.Tensor      ):







      if self.config.tf_padding:
        a		:   Tuple	  =	apply_tf_padding(__lowerCamelCase		,     self.convolution      )
      a		:   Optional[Any]	  =	self.convolution(__lowerCamelCase      )
      if self.normalization is not None:
        a		:   Union[str, Any]	  =	self.normalization(__lowerCamelCase      )
      if self.activation is not None:
        a		:   Union[str, Any]	  =	self.activation(__lowerCamelCase      )
      return features

class 				a__(   __snake_case      ):
    lowercase__					=       MobileNetVaConfig
    lowercase__					=       load_tf_weights_in_mobilenet_va
    lowercase__					=       """mobilenet_v1"""
    lowercase__					=       """pixel_values"""
    lowercase__					=       False







    def      lowercase_			( self					:    List[str]		,     __snake_case					:    Union[nn.Linear, nn.Convad]      ):







      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:   Dict					=		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'

lowerCAmelCase:   Any					=		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 				a__(   __snake_case      ):







    def __init__( self					:    Union[str, Any]		,     __snake_case					:    MobileNetVaConfig		,     __snake_case					:    bool = True      ):
      super().__init__(__lowerCamelCase      )
      a		:   Tuple	  =	config

      a		:   Dict	  =	32
      a		:   Dict	  =	max(int(depth * config.depth_multiplier      )		,     config.min_depth      )

      a		:   str	  =	MobileNetVaConvLayer(
          __lowerCamelCase		,     in_channels=config.num_channels		,     out_channels=__lowerCamelCase		,     kernel_size=3		,     stride=2		,     )

      a		:   Union[str, Any]	  =	[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

      a		:   str	  =	nn.ModuleList()
      for i in range(13      ):
        a		:   int	  =	out_channels

        if strides[i] == 2 or i == 0:
          depth *= 2
          a		:   List[Any]	  =	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		,     )      )

      a		:   Any	  =	nn.AdaptiveAvgPoolad((1, 1)      ) if add_pooling_layer else None

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







    def      lowercase_			( self					:    Tuple		,     __snake_case					:    List[Any]      ):
      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      lowercase_			( self					:    Any		,     __snake_case					:    Optional[torch.Tensor] = None		,     __snake_case					:    Optional[bool] = None		,     __snake_case					:    Optional[bool] = None		,     ):
      a		:   Dict	  =	(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      a		:   Tuple	  =	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		:   Optional[Any]	  =	self.conv_stem(__lowerCamelCase      )

      a		:   Tuple	  =	() if output_hidden_states else None

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

        if output_hidden_states:
          a		:   Optional[int]	  =	all_hidden_states + (hidden_states,)

      a		:   List[Any]	  =	hidden_states

      if self.pooler is not None:
        a		:   str	  =	torch.flatten(self.pooler(__lowerCamelCase      )		,     start_dim=1      )
      else:
        a		:   Tuple	  =	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(
    """
    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 				a__(   __snake_case      ):







    def __init__( self					:    Tuple		,     __snake_case					:    MobileNetVaConfig      ):
      super().__init__(__lowerCamelCase      )

      a		:   str	  =	config.num_labels
      a		:   Union[str, Any]	  =	MobileNetVaModel(__lowerCamelCase      )

      a		:   Dict	  =	self.mobilenet_va.layer[-1].convolution.out_channels

      # Classifier head
      a		:   Optional[Any]	  =	nn.Dropout(config.classifier_dropout_prob		,     inplace=__lowerCamelCase      )
      a		:   int	  =	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      lowercase_			( self					:    Dict		,     __snake_case					:    Optional[torch.Tensor] = None		,     __snake_case					:    Optional[bool] = None		,     __snake_case					:    Optional[torch.Tensor] = None		,     __snake_case					:    Optional[bool] = None		,     ):
      a		:   Optional[int]	  =	return_dict if return_dict is not None else self.config.use_return_dict

      a		:   Any	  =	self.mobilenet_va(__lowerCamelCase		,     output_hidden_states=__lowerCamelCase		,     return_dict=__lowerCamelCase      )

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

      a		:   Union[str, Any]	  =	self.classifier(self.dropout(__lowerCamelCase      )      )

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

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

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

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



from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							['''image_processor''', '''tokenizer''']
      UpperCamelCase										=							'''BridgeTowerImageProcessor'''
      UpperCamelCase										=							('''RobertaTokenizer''', '''RobertaTokenizerFast''')





      def __init__(		self    :       int       ,							__lowerCamelCase    :       Tuple       ,							__lowerCamelCase    :       List[Any]							)     -> Union[str, Any]:






         """simple docstring"""







         super().__init__(__lowerCamelCase       ,							__lowerCamelCase							)





      def __call__(		self    :       Any       ,							__lowerCamelCase    :       Optional[int]       ,							__lowerCamelCase    :       Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None       ,							__lowerCamelCase    :       bool = True       ,							__lowerCamelCase    :       Union[bool, str, PaddingStrategy] = False       ,							__lowerCamelCase    :       Union[bool, str, TruncationStrategy] = None       ,							__lowerCamelCase    :       Optional[int] = None       ,							__lowerCamelCase    :       int = 0       ,							__lowerCamelCase    :       Optional[int] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							__lowerCamelCase    :       bool = False       ,							__lowerCamelCase    :       bool = False       ,							__lowerCamelCase    :       bool = False       ,							__lowerCamelCase    :       bool = False       ,							__lowerCamelCase    :       bool = True       ,							__lowerCamelCase    :       Optional[Union[str, TensorType]] = None       ,							**__lowerCamelCase    :       Dict       ,							)     -> BatchEncoding:






         """simple docstring"""







         UpperCAmelCase      					=  self.tokenizer(
             text=__lowerCamelCase       ,							add_special_tokens=__lowerCamelCase       ,							padding=__lowerCamelCase       ,							truncation=__lowerCamelCase       ,							max_length=__lowerCamelCase       ,							stride=__lowerCamelCase       ,							pad_to_multiple_of=__lowerCamelCase       ,							return_token_type_ids=__lowerCamelCase       ,							return_attention_mask=__lowerCamelCase       ,							return_overflowing_tokens=__lowerCamelCase       ,							return_special_tokens_mask=__lowerCamelCase       ,							return_offsets_mapping=__lowerCamelCase       ,							return_length=__lowerCamelCase       ,							verbose=__lowerCamelCase       ,							return_tensors=__lowerCamelCase       ,							**__lowerCamelCase       ,							)
         # add pixel_values + pixel_mask
         UpperCAmelCase      					=  self.image_processor(
             __lowerCamelCase       ,							return_tensors=__lowerCamelCase       ,							do_normalize=__lowerCamelCase       ,							do_center_crop=__lowerCamelCase       ,							**__lowerCamelCase							)
         encoding.update(__lowerCamelCase							)

         return encoding





      def 							_lowercase					(		self    :       Optional[Any]       ,							*__lowerCamelCase    :       Optional[int]       ,							**__lowerCamelCase    :       List[str]							)     -> str:






         """simple docstring"""







         return self.tokenizer.batch_decode(*__lowerCamelCase       ,							**__lowerCamelCase							)





      def 							_lowercase					(		self    :       Dict       ,							*__lowerCamelCase    :       Any       ,							**__lowerCamelCase    :       List[Any]							)     -> Optional[int]:






         """simple docstring"""







         return self.tokenizer.decode(*__lowerCamelCase       ,							**__lowerCamelCase							)





      @property
      def 							_lowercase					(		self    :       List[Any]							)     -> Optional[int]:






         """simple docstring"""







         UpperCAmelCase      					=  self.tokenizer.model_input_names
         UpperCAmelCase      					=  self.image_processor.model_input_names
         return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names							)							)



