





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      lowerCAmelCase_ (       __a	,    __a	,    __a=None		)     ->		Optional[Any]:







  """simple docstring"""





  lowerCamelCase__:      List[str]			  ={}

  if isinstance(__a	,    __a		):
    lowerCamelCase__:      Tuple			  =model.mobilenet_va
  else:
    lowerCamelCase__:      List[str]			  =model

  lowerCamelCase__:      Union[str, Any]			  ="MobilenetV1/Conv2d_0/"
  lowerCamelCase__:      Tuple			  =backbone.conv_stem.convolution.weight
  lowerCamelCase__:      List[Any]			  =backbone.conv_stem.normalization.bias
  lowerCamelCase__:      Union[str, Any]			  =backbone.conv_stem.normalization.weight
  lowerCamelCase__:      Optional[Any]			  =backbone.conv_stem.normalization.running_mean
  lowerCamelCase__:      Optional[Any]			  =backbone.conv_stem.normalization.running_var

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

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

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

  if isinstance(__a	,    __a		):
    lowerCamelCase__:      Tuple			  ="MobilenetV1/Logits/Conv2d_1c_1x1/"
    lowerCamelCase__:      List[Any]			  =model.classifier.weight
    lowerCamelCase__:      int			  =model.classifier.bias

  return tf_to_pt_map





def      lowerCAmelCase_ (       __a	,    __a	,    __a		)     ->		Union[str, Any]:







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

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

    lowerCamelCase__:      Optional[int]			  =tf_weights[name]

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







  """simple docstring"""





  lowerCamelCase__  ,					lowerCamelCase__:      int			  =features.shape[-2:]
  lowerCamelCase__  ,					lowerCamelCase__:      List[str]			  =conv_layer.stride
  lowerCamelCase__  ,					lowerCamelCase__:      Dict			  =conv_layer.kernel_size

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

  if in_width % stride_width == 0:
    lowerCamelCase__:      int			  =max(kernel_width - stride_width	,    0		)
  else:
    lowerCamelCase__:      str			  =max(kernel_width - (in_width % stride_width)	,    0		)

  lowerCamelCase__:      Tuple			  =pad_along_width // 2
  lowerCamelCase__:      Optional[int]			  =pad_along_width - pad_left
  lowerCamelCase__:      Dict			  =pad_along_height // 2
  lowerCamelCase__:      int			  =pad_along_height - pad_top

  lowerCamelCase__:      List[str]			  =(pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(__a	,    __a	,    "constant"	,    0.0		)



class    _SCREAMING_SNAKE_CASE						(	nn.Module    ):







 '''simple docstring'''

 def __init__(self				:   Optional[int]       , 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:



   '''simple docstring'''



   super().__init__()
   lowerCamelCase__:      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.""")

   lowerCamelCase__:      Optional[int]			  =0 if config.tf_padding else int((kernel_size - 1) / 2)

   lowerCamelCase__:      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:
     lowerCamelCase__:      Optional[Any]			  =nn.BatchNormad(
         num_features=UpperCAmelCase_       , eps=config.layer_norm_eps       , momentum=0.9997       , affine=UpperCAmelCase_       , track_running_stats=UpperCAmelCase_       , )
   else:
     lowerCamelCase__:      Any			  =None

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







 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any]       , UpperCAmelCase_				:   torch.Tensor)       ->torch.Tensor:



   '''simple docstring'''



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



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			MobileNetVaConfig
 lowercase_		=			load_tf_weights_in_mobilenet_va
 lowercase_		=			"mobilenet_v1"
 lowercase_		=			"pixel_values"
 lowercase_		=			False

 def 							SCREAMING_SNAKE_CASE_					(self				:   int       , UpperCAmelCase_				:   Union[nn.Linear, nn.Convad])       ->None:



   '''simple docstring'''



   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)



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

__A									=				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."    ,							__SCREAMING_SNAKE_CASE    ,							)
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''

 def __init__(self				:   int       , UpperCAmelCase_				:   MobileNetVaConfig       , UpperCAmelCase_				:   bool = True)       ->str:



   '''simple docstring'''



   super().__init__(UpperCAmelCase_)
   lowerCamelCase__:      Optional[int]			  =config

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

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

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

   lowerCamelCase__:      Tuple			  =nn.ModuleList()
   for i in range(13):
     lowerCamelCase__:      Dict			  =out_channels

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

   lowerCamelCase__:      str			  =nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None

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

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   int)       ->Any:



   '''simple docstring'''



   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 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any]       , UpperCAmelCase_				:   Optional[torch.Tensor] = None       , UpperCAmelCase_				:   Optional[bool] = None       , UpperCAmelCase_				:   Optional[bool] = None       , )       ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =(
       output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
   )
   lowerCamelCase__:      str			  =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")

   lowerCamelCase__:      str			  =self.conv_stem(UpperCAmelCase_)

   lowerCamelCase__:      str			  =() if output_hidden_states else None

   for i, layer_module in enumerate(self.layer):
     lowerCamelCase__:      int			  =layer_module(UpperCAmelCase_)

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

   lowerCamelCase__:      Tuple			  =hidden_states

   if self.pooler is not None:
     lowerCamelCase__:      List[Any]			  =torch.flatten(self.pooler(UpperCAmelCase_)       , start_dim=1)
   else:
     lowerCamelCase__:      Optional[Any]			  =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(
    "\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "    ,							__SCREAMING_SNAKE_CASE    ,							)
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''

 def __init__(self				:   Optional[Any]       , UpperCAmelCase_				:   MobileNetVaConfig)       ->None:



   '''simple docstring'''



   super().__init__(UpperCAmelCase_)

   lowerCamelCase__:      List[str]			  =config.num_labels
   lowerCamelCase__:      List[Any]			  =MobileNetVaModel(UpperCAmelCase_)

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

   # Classifier head
   lowerCamelCase__:      Any			  =nn.Dropout(config.classifier_dropout_prob       , inplace=UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =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 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   Optional[torch.Tensor] = None       , UpperCAmelCase_				:   Optional[bool] = None       , UpperCAmelCase_				:   Optional[torch.Tensor] = None       , UpperCAmelCase_				:   Optional[bool] = None       , )       ->Union[tuple, ImageClassifierOutputWithNoAttention]:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =return_dict if return_dict is not None else self.config.use_return_dict

   lowerCamelCase__:      Optional[Any]			  =self.mobilenet_va(UpperCAmelCase_       , output_hidden_states=UpperCAmelCase_       , return_dict=UpperCAmelCase_)

   lowerCamelCase__:      Optional[Any]			  =outputs.pooler_output if return_dict else outputs[1]

   lowerCamelCase__:      Optional[int]			  =self.classifier(self.dropout(UpperCAmelCase_))

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

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

   if not return_dict:
     lowerCamelCase__:      List[Any]			  =(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 random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
    import tensorflow as tf
    from tensorflow.python.framework.errors_impl import ResourceExhaustedError

    from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
    import pyanvml.pyanvml as nvml

UpperCAmelCase__     						=  logging.get_logger(__name__)






def 			__UpperCAmelCase    (	lowercase      ,lowercase						):







  """simple docstring"""
  def run_func(lowercase						):
    @wraps(lowercase						)
    def run_in_eager_mode(*lowercase      ,**lowercase						):
      return func(*lowercase      ,**lowercase						)

    @wraps(lowercase						)
    @tf.function(experimental_compile=lowercase						)
    def run_in_graph_mode(*lowercase      ,**lowercase						):
      return func(*lowercase      ,**lowercase						)

    if do_eager_mode is True:
      if use_xla is not False:
        raise ValueError(
            """Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."""						)
      return run_in_eager_mode
    else:
      return run_in_graph_mode

  return run_func






def 			__UpperCAmelCase    (	lowercase      ,lowercase      ,lowercase						):







  """simple docstring"""
  _UpperCAmelCase         =					random.Random()
  _UpperCAmelCase         =					[rng.randint(0      ,vocab_size - 1						) for i in range(batch_size * sequence_length						)]
  return tf.constant(lowercase      ,shape=(batch_size, sequence_length)      ,dtype=tf.intaa						)


class 				a (						lowerCAmelCase_      ):
    _snake_case   :     TensorFlowBenchmarkArguments
    _snake_case   :     PretrainedConfig
    _snake_case   :     str   							=							"TensorFlow"


    @property
    def    lowerCAmelCase_     (    self		:     Union[str, Any]    ):
      return tf.__version__


    def    lowerCAmelCase_     (    self		:     List[str]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      # initialize GPU on separate process
      _UpperCAmelCase         =					self.args.strategy
      if strategy is None:
        raise ValueError("""A device strategy has to be initialized before using TensorFlow."""    )
      _UpperCAmelCase         =					self._prepare_inference_func(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )
      return self._measure_speed(_inference    )


    def    lowerCAmelCase_     (    self		:     Optional[int]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      _UpperCAmelCase         =					self.args.strategy
      if strategy is None:
        raise ValueError("""A device strategy has to be initialized before using TensorFlow."""    )
      _UpperCAmelCase         =					self._prepare_train_func(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )
      return self._measure_speed(_train    )


    def    lowerCAmelCase_     (    self		:     Optional[Any]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      # initialize GPU on separate process
      if self.args.is_gpu:
        tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]      , __lowerCAmelCase    )
      _UpperCAmelCase         =					self.args.strategy
      if strategy is None:
        raise ValueError("""A device strategy has to be initialized before using TensorFlow."""    )
      _UpperCAmelCase         =					self._prepare_inference_func(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )
      return self._measure_memory(_inference    )


    def    lowerCAmelCase_     (    self		:     str      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      if self.args.is_gpu:
        tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]      , __lowerCAmelCase    )
      _UpperCAmelCase         =					self.args.strategy
      if strategy is None:
        raise ValueError("""A device strategy has to be initialized before using TensorFlow."""    )

      _UpperCAmelCase         =					self._prepare_train_func(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )
      return self._measure_memory(_train    )


    def    lowerCAmelCase_     (    self		:     List[Any]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      _UpperCAmelCase         =					self.config_dict[model_name]

      if self.args.fpaa:
        raise NotImplementedError("""Mixed precision is currently not supported."""    )

      _UpperCAmelCase         =					(
          hasattr(__lowerCAmelCase      , """architectures"""    )
          and isinstance(config.architectures      , __lowerCAmelCase    )
          and len(config.architectures    ) > 0
      )
      if not self.args.only_pretrain_model and has_model_class_in_config:
        try:
          _UpperCAmelCase         =					"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
          _UpperCAmelCase         =					__import__("""transformers"""      , fromlist=[model_class]    )
          _UpperCAmelCase         =					getattr(__lowerCAmelCase      , __lowerCAmelCase    )
          _UpperCAmelCase         =					model_cls(__lowerCAmelCase    )
        except ImportError:
          raise ImportError(
              f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
              """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""    )
      else:
        _UpperCAmelCase         =					TF_MODEL_MAPPING[config.__class__](__lowerCAmelCase    )

      # encoder-decoder has vocab size saved differently
      _UpperCAmelCase         =					config.vocab_size if hasattr(__lowerCAmelCase      , """vocab_size"""    ) else config.encoder.vocab_size
      _UpperCAmelCase         =					random_input_ids(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )

      @run_with_tf_optimizations(self.args.eager_mode      , self.args.use_xla    )
      def encoder_decoder_forward():
        return model(__lowerCAmelCase      , decoder_input_ids=__lowerCAmelCase      , training=__lowerCAmelCase    )

      @run_with_tf_optimizations(self.args.eager_mode      , self.args.use_xla    )
      def encoder_forward():
        return model(__lowerCAmelCase      , training=__lowerCAmelCase    )

      _UpperCAmelCase         =					encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

      return _inference


    def    lowerCAmelCase_     (    self		:     List[str]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int    ):
      _UpperCAmelCase         =					self.config_dict[model_name]

      if self.args.eager_mode is not False:
        raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."""    )

      if self.args.fpaa:
        raise NotImplementedError("""Mixed precision is currently not supported."""    )

      _UpperCAmelCase         =					(
          hasattr(__lowerCAmelCase      , """architectures"""    )
          and isinstance(config.architectures      , __lowerCAmelCase    )
          and len(config.architectures    ) > 0
      )
      if not self.args.only_pretrain_model and has_model_class_in_config:
        try:
          _UpperCAmelCase         =					"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
          _UpperCAmelCase         =					__import__("""transformers"""      , fromlist=[model_class]    )
          _UpperCAmelCase         =					getattr(__lowerCAmelCase      , __lowerCAmelCase    )
          _UpperCAmelCase         =					model_cls(__lowerCAmelCase    )
        except ImportError:
          raise ImportError(
              f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
              """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""    )
      else:
        _UpperCAmelCase         =					TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__lowerCAmelCase    )

      # encoder-decoder has vocab size saved differently
      _UpperCAmelCase         =					config.vocab_size if hasattr(__lowerCAmelCase      , """vocab_size"""    ) else config.encoder.vocab_size
      _UpperCAmelCase         =					random_input_ids(__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase    )

      @run_with_tf_optimizations(self.args.eager_mode      , self.args.use_xla    )
      def encoder_decoder_train():
        _UpperCAmelCase         =					model(__lowerCAmelCase      , decoder_input_ids=__lowerCAmelCase      , labels=__lowerCAmelCase      , training=__lowerCAmelCase    )[0]
        _UpperCAmelCase         =					tf.gradients(__lowerCAmelCase      , model.trainable_variables    )
        return gradients

      @run_with_tf_optimizations(self.args.eager_mode      , self.args.use_xla    )
      def encoder_train():
        _UpperCAmelCase         =					model(__lowerCAmelCase      , labels=__lowerCAmelCase      , training=__lowerCAmelCase    )[0]
        _UpperCAmelCase         =					tf.gradients(__lowerCAmelCase      , model.trainable_variables    )
        return gradients

      _UpperCAmelCase         =					encoder_decoder_train if config.is_encoder_decoder else encoder_train

      return _train


    def    lowerCAmelCase_     (    self		:     Union[str, Any]      , __lowerCAmelCase		:     Any    ):
      with self.args.strategy.scope():
        try:
          if self.args.is_tpu or self.args.use_xla:
            # run additional 10 times to stabilize compilation for tpu
            logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation"""    )
            timeit.repeat(__lowerCAmelCase      , repeat=1      , number=5    )

          # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
          _UpperCAmelCase         =					timeit.repeat(
              __lowerCAmelCase      , repeat=self.args.repeat      , number=10      , )

          return min(__lowerCAmelCase    ) / 10.0
        except ResourceExhaustedError as e:
          self.print_fn(f'''Doesn\'t fit on GPU. {e}'''    )


    def    lowerCAmelCase_     (    self		:     List[Any]      , __lowerCAmelCase		:     Callable[[], None]    ):
      logger.info(
          """Note that TensorFlow allocates more memory than """
          """it might need to speed up computation. """
          """The memory reported here corresponds to the memory """
          """reported by `nvidia-smi`, which can vary depending """
          """on total available memory on the GPU that is used."""    )
      with self.args.strategy.scope():
        try:
          if self.args.trace_memory_line_by_line:
            if not self.args.eager_mode:
              raise ValueError(
                  """`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"""
                  """ consumption line by line."""    )
            _UpperCAmelCase         =					start_memory_tracing("""transformers"""    )

          if self.args.is_tpu:
            # tpu
            raise NotImplementedError(
                """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"""
                """ with `args.memory=False`"""    )
          elif self.args.is_gpu:
            # gpu
            if not is_pyanvml_available():
              logger.warning(
                  """py3nvml not installed, we won't log GPU memory usage. """
                  """Install py3nvml (pip install py3nvml) to log information about GPU."""    )
              _UpperCAmelCase         =					"""N/A"""
            else:
              logger.info(
                  """Measuring total GPU usage on GPU device. Make sure to not have additional processes"""
                  """ running on the same GPU."""    )
              # init nvml
              nvml.nvmlInit()
              func()
              _UpperCAmelCase         =					nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx    )
              _UpperCAmelCase         =					nvml.nvmlDeviceGetMemoryInfo(__lowerCAmelCase    )
              _UpperCAmelCase         =					meminfo.used
              _UpperCAmelCase         =					Memory(__lowerCAmelCase    )
              # shutdown nvml
              nvml.nvmlShutdown()
          else:
            # cpu
            if self.args.trace_memory_line_by_line:
              logger.info(
                  """When enabling line by line tracing, the max peak memory for CPU is inaccurate in"""
                  """ TensorFlow."""    )
              _UpperCAmelCase         =					None
            else:
              _UpperCAmelCase         =					measure_peak_memory_cpu(__lowerCAmelCase    )
              _UpperCAmelCase         =					Memory(__lowerCAmelCase    ) if isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) else memory_bytes
          if self.args.trace_memory_line_by_line:
            _UpperCAmelCase         =					stop_memory_tracing(__lowerCAmelCase    )
            if memory is None:
              _UpperCAmelCase         =					summary.total
          else:
            _UpperCAmelCase         =					None

          return memory, summary
        except ResourceExhaustedError as e:
          self.print_fn(f'''Doesn\'t fit on GPU. {e}'''    )
          return "N/A", None
