


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


__a	 =      logging.get_logger(__name__)


# General docstring
__a	 =      """MobileNetV1Config"""

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

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


__a	 =      [
    """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					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_=None )    ->Optional[int]:
   UpperCAmelCase      					=  {}

   if isinstance(lowerCAmelCase_	,    lowerCAmelCase_ ):
      UpperCAmelCase      					=  model.mobilenet_va
   else:
      UpperCAmelCase      					=  model

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

   for i in range(1_3 ):
      UpperCAmelCase      					=  i + 1
      UpperCAmelCase      					=  i * 2

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

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

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

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

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

      UpperCAmelCase      					=  tf_weights[name]

      if "depthwise_weights" in name:
         logger.info("""Transposing depthwise""" )
         UpperCAmelCase      					=  np.transpose(lowerCAmelCase_	,    (2, 3, 0, 1) )
      elif "weights" in name:
         logger.info("""Transposing""" )
         if len(pointer.shape ) == 2:  # copying into linear layer
            UpperCAmelCase      					=  array.squeeze().transpose()
         else:
            UpperCAmelCase      					=  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}""" )
      UpperCAmelCase      					=  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 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->torch.Tensor:
   UpperCAmelCase					,	UpperCAmelCase      					=  features.shape[-2:]
   UpperCAmelCase					,	UpperCAmelCase      					=  conv_layer.stride
   UpperCAmelCase					,	UpperCAmelCase      					=  conv_layer.kernel_size

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

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

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

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






class 	__lowercase					(	nn.Module	):





      def __init__(		self    :       int       ,							__lowerCamelCase    :       MobileNetVaConfig       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       Optional[int] = 1       ,							__lowerCamelCase    :       Optional[int] = 1       ,							__lowerCamelCase    :       bool = False       ,							__lowerCamelCase    :       Optional[bool] = True       ,							__lowerCamelCase    :       Optional[bool or str] = True       ,							)     -> None:






         """simple docstring"""







         super().__init__()
         UpperCAmelCase      					=  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."""							)

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

         UpperCAmelCase      					=  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:
            UpperCAmelCase      					=  nn.BatchNormad(
                num_features=__lowerCamelCase       ,							eps=config.layer_norm_eps       ,							momentum=0.9_997       ,							affine=__lowerCamelCase       ,							track_running_stats=__lowerCamelCase       ,							)
         else:
            UpperCAmelCase      					=  None

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





      def 							_lowercase					(		self    :       Optional[int]       ,							__lowerCamelCase    :       torch.Tensor							)     -> torch.Tensor:






         """simple docstring"""







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






class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							MobileNetVaConfig
      UpperCamelCase										=							load_tf_weights_in_mobilenet_va
      UpperCamelCase										=							'''mobilenet_v1'''
      UpperCamelCase										=							'''pixel_values'''
      UpperCamelCase										=							False





      def 							_lowercase					(		self    :       List[str]       ,							__lowerCamelCase    :       Union[nn.Linear, nn.Convad]							)     -> None:






         """simple docstring"""







         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							)

__a	 =      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.
"""

__a	 =      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.'''			,       __snake_case			,       )
class 	__lowercase					(	__snake_case	):





      def __init__(		self    :       Union[str, Any]       ,							__lowerCamelCase    :       MobileNetVaConfig       ,							__lowerCamelCase    :       bool = True							)     -> int:






         """simple docstring"""







         super().__init__(__lowerCamelCase							)
         UpperCAmelCase      					=  config

         UpperCAmelCase      					=  3_2
         UpperCAmelCase      					=  max(int(depth * config.depth_multiplier							)       ,							config.min_depth							)

         UpperCAmelCase      					=  MobileNetVaConvLayer(
             __lowerCamelCase       ,							in_channels=config.num_channels       ,							out_channels=__lowerCamelCase       ,							kernel_size=3       ,							stride=2       ,							)

         UpperCAmelCase      					=  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

         UpperCAmelCase      					=  nn.ModuleList()
         for i in range(1_3							):
            UpperCAmelCase      					=  out_channels

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

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

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





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






         """simple docstring"""







         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       ,							__lowerCamelCase    :       Optional[torch.Tensor] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							)     -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:






         """simple docstring"""







         UpperCAmelCase      					=  (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         UpperCAmelCase      					=  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"""							)

         UpperCAmelCase      					=  self.conv_stem(__lowerCamelCase							)

         UpperCAmelCase      					=  () if output_hidden_states else None

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

            if output_hidden_states:
               UpperCAmelCase      					=  all_hidden_states + (hidden_states,)

         UpperCAmelCase      					=  hidden_states

         if self.pooler is not None:
            UpperCAmelCase      					=  torch.flatten(self.pooler(__lowerCamelCase							)       ,							start_dim=1							)
         else:
            UpperCAmelCase      					=  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 	__lowercase					(	__snake_case	):





      def __init__(		self    :       Tuple       ,							__lowerCamelCase    :       MobileNetVaConfig							)     -> None:






         """simple docstring"""







         super().__init__(__lowerCamelCase							)

         UpperCAmelCase      					=  config.num_labels
         UpperCAmelCase      					=  MobileNetVaModel(__lowerCamelCase							)

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

         # Classifier head
         UpperCAmelCase      					=  nn.Dropout(config.classifier_dropout_prob       ,							inplace=__lowerCamelCase							)
         UpperCAmelCase      					=  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       ,							__lowerCamelCase    :       Optional[torch.Tensor] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							__lowerCamelCase    :       Optional[torch.Tensor] = None       ,							__lowerCamelCase    :       Optional[bool] = None       ,							)     -> Union[tuple, ImageClassifierOutputWithNoAttention]:






         """simple docstring"""







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

         UpperCAmelCase      					=  self.mobilenet_va(__lowerCamelCase       ,							output_hidden_states=__lowerCamelCase       ,							return_dict=__lowerCamelCase							)

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

         UpperCAmelCase      					=  self.classifier(self.dropout(__lowerCamelCase							)							)

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

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

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

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







def 	_UpperCamelCase					(    )    ->list[list[int]]:
   return [list(range(1_0_0_0 - i	,    -1_0_0_0 - i	,    -1 ) ) for i in range(1_0_0_0 )]


__a	 =      generate_large_matrix()
__a	 =      (
    [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
    [[3, 2], [1, 0]],
    [[7, 7, 6]],
    [[7, 7, 6], [-1, -2, -3]],
    grid,
)
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->None:
   assert all(row == sorted(lowerCAmelCase_	,    reverse=lowerCAmelCase_ ) for row in grid )
   assert all(list(lowerCAmelCase_ ) == sorted(lowerCAmelCase_	,    reverse=lowerCAmelCase_ ) for col in zip(*lowerCAmelCase_ ) )
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   UpperCAmelCase      					=  0
   UpperCAmelCase      					=  len(lowerCAmelCase_ ) - 1

   # Edge cases such as no values or all numbers are negative.
   if not array or array[0] < 0:
      return 0

   while right + 1 > left:
      UpperCAmelCase      					=  (left + right) // 2
      UpperCAmelCase      					=  array[mid]

      # Num must be negative and the index must be greater than or equal to 0.
      if num < 0 and array[mid - 1] >= 0:
         return mid

      if num >= 0:
         UpperCAmelCase      					=  mid + 1
      else:
         UpperCAmelCase      					=  mid - 1
    # No negative numbers so return the last index of the array + 1 which is the length.
   return len(lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   UpperCAmelCase      					=  0
   UpperCAmelCase      					=  len(grid[0] )

   for i in range(len(lowerCAmelCase_ ) ):
      UpperCAmelCase      					=  find_negative_index(grid[i][:bound] )
      total += bound
   return (len(lowerCAmelCase_ ) * len(grid[0] )) - total
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   return len([number for row in grid for number in row if number < 0] )
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   UpperCAmelCase      					=  0
   for row in grid:
      for i, number in enumerate(lowerCAmelCase_ ):
         if number < 0:
            total += len(lowerCAmelCase_ ) - i
            break
   return total
def 	_UpperCamelCase					(    )    ->None:
   from timeit import timeit

   print("""Running benchmarks""" )
   UpperCAmelCase      					=  (
       """from __main__ import count_negatives_binary_search, """
       """count_negatives_brute_force, count_negatives_brute_force_with_break, grid"""
   )
   for func in (
       "count_negatives_binary_search",  # took 0.7727 seconds
       "count_negatives_brute_force_with_break",  # took 4.6505 seconds
       "count_negatives_brute_force",  # took 12.8160 seconds
   ):
      UpperCAmelCase      					=  timeit(F"""{func}(grid=grid)"""	,    setup=lowerCAmelCase_	,    number=5_0_0 )
      print(F"""{func}() took {time:0.4f} seconds""" )


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 benchmark()



