


"""simple docstring"""







import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


__lowercase    =				logging.get_logger(__name__)






@dataclass
class 						_A  :







    """simple docstring"""




    UpperCAmelCase	:							str     =	field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
    UpperCAmelCase	:							str     =	field(
        metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
    UpperCAmelCase	:							int     =	field(
        default=1_2_8   ,metadata={
            """help""": (
                """The maximum total input sequence length after tokenization. Sequences longer """
                """than this will be truncated, sequences shorter will be padded."""
            )
        }   ,)
    UpperCAmelCase	:							bool     =	field(
        default=_a   ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )






    def      __snake_case							( self    :   int):
      a						:		Union[str, Any]											=      self.task_name.lower()






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Union[str, Any]     =	"""train"""
    UpperCAmelCase	:							str     =	"""dev"""
    UpperCAmelCase	:							int     =	"""test"""






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							GlueDataTrainingArguments
    UpperCAmelCase	:							str
    UpperCAmelCase	:							List[InputFeatures]






    def __init__( self    :   Union[str, Any]    ,			__UpperCAmelCase    :   GlueDataTrainingArguments    ,			__UpperCAmelCase    :   PreTrainedTokenizerBase    ,			__UpperCAmelCase    :   Optional[int] = None    ,			__UpperCAmelCase    :   Union[str, Split] = Split.train    ,			__UpperCAmelCase    :   Optional[str] = None    ,			):
      warnings.warn(
          "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
          "library. You can have a look at this example script for pointers: "
          "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"    ,			__UpperCAmelCase    ,			)
      a						:		int											=      args
      a						:		Union[str, Any]											=      glue_processors[args.task_name]()
      a						:		int											=      glue_output_modes[args.task_name]
      if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
        try:
          a						:		Union[str, Any]											=      Split[mode]
        except KeyError:
          raise KeyError("mode is not a valid split name")
        # Load data features from cache or dataset file
      a						:		List[Any]											=      os.path.join(
          cache_dir if cache_dir is not None else args.data_dir    ,			f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'''    ,			)
      a						:		List[Any]											=      self.processor.get_labels()
      if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
          "RobertaTokenizer",
          "RobertaTokenizerFast",
          "XLMRobertaTokenizer",
          "BartTokenizer",
          "BartTokenizerFast",
      ):
        # HACK(label indices are swapped in RoBERTa pretrained model)
        a							,		a						:		List[Any]											=      label_list[2], label_list[1]
      a						:		str											=      label_list

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      a						:		Any											=      cached_features_file + ".lock"
      with FileLock(__UpperCAmelCase):
        if os.path.exists(__UpperCAmelCase) and not args.overwrite_cache:
          a						:		List[Any]											=      time.time()
          a						:		List[str]											=      torch.load(__UpperCAmelCase)
          logger.info(
              f'''Loading features from cached file {cached_features_file} [took %.3f s]'''    ,			time.time() - start)
        else:
          logger.info(f'''Creating features from dataset file at {args.data_dir}''')

          if mode == Split.dev:
            a						:		Dict											=      self.processor.get_dev_examples(args.data_dir)
          elif mode == Split.test:
            a						:		Optional[int]											=      self.processor.get_test_examples(args.data_dir)
          else:
            a						:		int											=      self.processor.get_train_examples(args.data_dir)
          if limit_length is not None:
            a						:		Tuple											=      examples[:limit_length]
          a						:		int											=      glue_convert_examples_to_features(
              __UpperCAmelCase    ,			__UpperCAmelCase    ,			max_length=args.max_seq_length    ,			label_list=__UpperCAmelCase    ,			output_mode=self.output_mode    ,			)
          a						:		Optional[Any]											=      time.time()
          torch.save(self.features    ,			__UpperCAmelCase)
          # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
          logger.info(
              f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''')






    def __len__( self    :   Union[str, Any]):
      return len(self.features)






    def __getitem__( self    :   str    ,			__UpperCAmelCase    :   int):
      return self.features[i]






    def      __snake_case							( self    :   Optional[Any]):
      return self.label_list










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


__lowercase    =				logging.get_logger(__name__)


# General docstring
__lowercase    =				"""MobileNetV1Config"""

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

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


__lowercase    =				[
    """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 					lowercase      (    A_  ,       A_  ,       A_=None	)->				int:
  '''simple docstring'''







  a						:		Union[str, Any]											=      {}

  if isinstance(A_  ,       A_	):
    a						:		Tuple											=      model.mobilenet_va
  else:
    a						:		Optional[int]											=      model

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

  for i in range(13	):
    a						:		Dict											=      i + 1
    a						:		str											=      i * 2

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

    a						:		Dict											=      backbone.layer[pt_index + 1]
    a						:		List[str]											=      F'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
    a						:		Dict											=      pointer.convolution.weight
    a						:		Any											=      pointer.normalization.bias
    a						:		List[Any]											=      pointer.normalization.weight
    a						:		Tuple											=      pointer.normalization.running_mean
    a						:		List[str]											=      pointer.normalization.running_var

  if isinstance(A_  ,       A_	):
    a						:		Dict											=      "MobilenetV1/Logits/Conv2d_1c_1x1/"
    a						:		List[Any]											=      model.classifier.weight
    a						:		Optional[int]											=      model.classifier.bias

  return tf_to_pt_map


def 					lowercase      (    A_  ,       A_  ,       A_	)->				Optional[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
  a						:		List[str]											=      tf.train.list_variables(A_	)
  a						:		Dict											=      {}
  for name, shape in init_vars:
    logger.info(F'''Loading TF weight {name} with shape {shape}'''	)
    a						:		List[str]											=      tf.train.load_variable(A_  ,       A_	)
    a						:		int											=      array

  # Build TF to PyTorch weights loading map
  a						:		int											=      _build_tf_to_pytorch_map(A_  ,       A_  ,       A_	)

  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						:		Tuple											=      tf_weights[name]

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

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

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


def 					lowercase      (    A_  ,       A_	)->				torch.Tensor:
  '''simple docstring'''







  a							,		a						:		str											=      features.shape[-2:]
  a							,		a						:		Tuple											=      conv_layer.stride
  a							,		a						:		Union[str, Any]											=      conv_layer.kernel_size

  if in_height % stride_height == 0:
    a						:		Union[str, Any]											=      max(kernel_height - stride_height  ,       0	)
  else:
    a						:		Tuple											=      max(kernel_height - (in_height % stride_height)  ,       0	)

  if in_width % stride_width == 0:
    a						:		Optional[int]											=      max(kernel_width - stride_width  ,       0	)
  else:
    a						:		int											=      max(kernel_width - (in_width % stride_width)  ,       0	)

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

  a						:		Tuple											=      (pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(A_  ,       A_  ,       "constant"  ,       0.0	)






class 						_A  (  nn.Module  ):







    """simple docstring"""




    def __init__( self    :   Dict    ,			__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    ,			):
      super().__init__()
      a						:		Optional[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[str]											=      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						:		str											=      nn.BatchNormad(
            num_features=__UpperCAmelCase    ,			eps=config.layer_norm_eps    ,			momentum=0.9_997    ,			affine=__UpperCAmelCase    ,			track_running_stats=__UpperCAmelCase    ,			)
      else:
        a						:		List[str]											=      None

      if use_activation:
        if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
          a						:		Optional[int]											=      ACTaFN[use_activation]
        elif isinstance(config.hidden_act    ,			__UpperCAmelCase):
          a						:		Optional[Any]											=      ACTaFN[config.hidden_act]
        else:
          a						:		str											=      config.hidden_act
      else:
        a						:		Dict											=      None






    def      __snake_case							( self    :   Tuple    ,			__UpperCAmelCase    :   torch.Tensor):
      if self.config.tf_padding:
        a						:		Tuple											=      apply_tf_padding(__UpperCAmelCase    ,			self.convolution)
      a						:		Dict											=      self.convolution(__UpperCAmelCase)
      if self.normalization is not None:
        a						:		List[str]											=      self.normalization(__UpperCAmelCase)
      if self.activation is not None:
        a						:		Optional[Any]											=      self.activation(__UpperCAmelCase)
      return features






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Union[str, Any]     =	MobileNetVaConfig
    UpperCAmelCase	:							str     =	load_tf_weights_in_mobilenet_va
    UpperCAmelCase	:							List[str]     =	"""mobilenet_v1"""
    UpperCAmelCase	:							Dict     =	"""pixel_values"""
    UpperCAmelCase	:							str     =	False






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   Union[nn.Linear, nn.Convad]):
      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)






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

__lowercase    =				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."""   ,_a   ,)
class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   Optional[int]    ,			__UpperCAmelCase    :   MobileNetVaConfig    ,			__UpperCAmelCase    :   bool = True):
      super().__init__(__UpperCAmelCase)
      a						:		List[str]											=      config

      a						:		List[Any]											=      32
      a						:		Union[str, Any]											=      max(int(depth * config.depth_multiplier)    ,			config.min_depth)

      a						:		List[str]											=      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						:		Optional[Any]											=      out_channels

        if strides[i] == 2 or i == 0:
          depth *= 2
          a						:		List[str]											=      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						:		Optional[Any]											=      nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None

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






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

      a						:		Tuple											=      () if output_hidden_states else None

      for i, layer_module in enumerate(self.layer):
        a						:		Union[str, Any]											=      layer_module(__UpperCAmelCase)

        if output_hidden_states:
          a						:		str											=      all_hidden_states + (hidden_states,)

      a						:		Dict											=      hidden_states

      if self.pooler is not None:
        a						:		Optional[int]											=      torch.flatten(self.pooler(__UpperCAmelCase)    ,			start_dim=1)
      else:
        a						:		List[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.
    """   ,_a   ,)
class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   int    ,			__UpperCAmelCase    :   MobileNetVaConfig):
      super().__init__(__UpperCAmelCase)

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

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

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

      a						:		Dict											=      self.mobilenet_va(__UpperCAmelCase    ,			output_hidden_states=__UpperCAmelCase    ,			return_dict=__UpperCAmelCase)

      a						:		List[Any]											=      outputs.pooler_output if return_dict else outputs[1]

      a						:		List[Any]											=      self.classifier(self.dropout(__UpperCAmelCase))

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

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

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

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






