


import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     MODEL_FOR_PRETRAINING_MAPPING,
     AlbertForMaskedLM,
     AlbertForMultipleChoice,
     AlbertForPreTraining,
     AlbertForQuestionAnswering,
     AlbertForSequenceClassification,
     AlbertForTokenClassification,
     AlbertModel,
 )
 from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST





class   __a			:
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__=13				, lowerCAmelCase__=7				, lowerCAmelCase__=True				, lowerCAmelCase__=True				, lowerCAmelCase__=True				, lowerCAmelCase__=True				, lowerCAmelCase__=99				, lowerCAmelCase__=16				, lowerCAmelCase__=36				, lowerCAmelCase__=6				, lowerCAmelCase__=6				, lowerCAmelCase__=6				, lowerCAmelCase__=37				, lowerCAmelCase__="gelu"				, lowerCAmelCase__=0.1				, lowerCAmelCase__=0.1				, lowerCAmelCase__=512				, lowerCAmelCase__=16				, lowerCAmelCase__=2				, lowerCAmelCase__=0.0_2				, lowerCAmelCase__=3				, lowerCAmelCase__=4				, lowerCAmelCase__=None				, )					->				Tuple:




        '''simple docstring'''
        lowercase__:   List[str]  			=   parent
        lowercase__:   List[Any]  			=   batch_size
        lowercase__:   List[str]  			=   seq_length
        lowercase__:   Any  			=   is_training
        lowercase__:   Dict  			=   use_input_mask
        lowercase__:   List[str]  			=   use_token_type_ids
        lowercase__:   str  			=   use_labels
        lowercase__:   int  			=   vocab_size
        lowercase__:   List[str]  			=   embedding_size
        lowercase__:   Dict  			=   hidden_size
        lowercase__:   Any  			=   num_hidden_layers
        lowercase__:   List[str]  			=   num_hidden_groups
        lowercase__:   int  			=   num_attention_heads
        lowercase__:   int  			=   intermediate_size
        lowercase__:   Optional[int]  			=   hidden_act
        lowercase__:   List[Any]  			=   hidden_dropout_prob
        lowercase__:   Dict  			=   attention_probs_dropout_prob
        lowercase__:   Optional[Any]  			=   max_position_embeddings
        lowercase__:   Optional[Any]  			=   type_vocab_size
        lowercase__:   List[Any]  			=   type_sequence_label_size
        lowercase__:   List[str]  			=   initializer_range
        lowercase__:   Any  			=   num_labels
        lowercase__:   Optional[Any]  			=   num_choices
        lowercase__:   str  			=   scope
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        lowercase__:   List[str]  			=   ids_tensor([self.batch_size, self.seq_length]				, self.vocab_size )

        lowercase__:   Tuple  			=   None
        if self.use_input_mask:
               lowercase__:   Dict  			=   random_attention_mask([self.batch_size, self.seq_length] )

        lowercase__:   List[str]  			=   None
        if self.use_token_type_ids:
               lowercase__:   Dict  			=   ids_tensor([self.batch_size, self.seq_length]				, self.type_vocab_size )

        lowercase__:   int  			=   None
        lowercase__:   Union[str, Any]  			=   None
        lowercase__:   str  			=   None
        if self.use_labels:
               lowercase__:   Optional[int]  			=   ids_tensor([self.batch_size]				, self.type_sequence_label_size )
               lowercase__:   List[str]  			=   ids_tensor([self.batch_size, self.seq_length]				, self.num_labels )
               lowercase__:   Dict  			=   ids_tensor([self.batch_size]				, self.num_choices )

        lowercase__:   int  			=   self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        return AlbertConfig(
            vocab_size=self.vocab_size				, hidden_size=self.hidden_size				, num_hidden_layers=self.num_hidden_layers				, num_attention_heads=self.num_attention_heads				, intermediate_size=self.intermediate_size				, hidden_act=self.hidden_act				, hidden_dropout_prob=self.hidden_dropout_prob				, attention_probs_dropout_prob=self.attention_probs_dropout_prob				, max_position_embeddings=self.max_position_embeddings				, type_vocab_size=self.type_vocab_size				, initializer_range=self.initializer_range				, num_hidden_groups=self.num_hidden_groups				, )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   Any  			=   AlbertModel(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   Tuple  			=   model(__lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase )
        lowercase__:   Any  			=   model(__lowerCAmelCase				, token_type_ids=__lowerCAmelCase )
        lowercase__:   List[str]  			=   model(__lowerCAmelCase )
        self.parent.assertEqual(result.last_hidden_state.shape				, (self.batch_size, self.seq_length, self.hidden_size) )
        self.parent.assertEqual(result.pooler_output.shape				, (self.batch_size, self.hidden_size) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Tuple:




        '''simple docstring'''
        lowercase__:   Dict  			=   AlbertForPreTraining(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   Optional[Any]  			=   model(
            __lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, labels=__lowerCAmelCase				, sentence_order_label=__lowerCAmelCase				, )
        self.parent.assertEqual(result.prediction_logits.shape				, (self.batch_size, self.seq_length, self.vocab_size) )
        self.parent.assertEqual(result.sop_logits.shape				, (self.batch_size, config.num_labels) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				str:




        '''simple docstring'''
        lowercase__:   Dict  			=   AlbertForMaskedLM(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   List[Any]  			=   model(__lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, labels=__lowerCAmelCase )
        self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.seq_length, self.vocab_size) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				List[str]:




        '''simple docstring'''
        lowercase__:   Optional[int]  			=   AlbertForQuestionAnswering(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   str  			=   model(
            __lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, start_positions=__lowerCAmelCase				, end_positions=__lowerCAmelCase				, )
        self.parent.assertEqual(result.start_logits.shape				, (self.batch_size, self.seq_length) )
        self.parent.assertEqual(result.end_logits.shape				, (self.batch_size, self.seq_length) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Tuple:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   self.num_labels
        lowercase__:   str  			=   AlbertForSequenceClassification(__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   Optional[Any]  			=   model(__lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, labels=__lowerCAmelCase )
        self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_labels) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   List[str]  			=   self.num_labels
        lowercase__:   Optional[int]  			=   AlbertForTokenClassification(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   str  			=   model(__lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, labels=__lowerCAmelCase )
        self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.seq_length, self.num_labels) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Optional[int]:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   self.num_choices
        lowercase__:   Dict  			=   AlbertForMultipleChoice(config=__lowerCAmelCase )
        model.to(__lowerCAmelCase )
        model.eval()
        lowercase__:   Tuple  			=   input_ids.unsqueeze(1 ).expand(-1				, self.num_choices				, -1 ).contiguous()
        lowercase__:   List[str]  			=   token_type_ids.unsqueeze(1 ).expand(-1				, self.num_choices				, -1 ).contiguous()
        lowercase__:   Optional[Any]  			=   input_mask.unsqueeze(1 ).expand(-1				, self.num_choices				, -1 ).contiguous()
        lowercase__:   Optional[Any]  			=   model(
            __lowerCAmelCase				, attention_mask=__lowerCAmelCase				, token_type_ids=__lowerCAmelCase				, labels=__lowerCAmelCase				, )
        self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_choices) )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   int  			=   self.prepare_config_and_inputs()
        (
            (
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						(
            lowercase__ 
        )			,						 
        ):   Union[str, Any]  			=   config_and_inputs
        lowercase__:   str  			=   {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
        return config, inputs_dict





@require_torch
class   __a			(    lowerCAmelCase_       ,       lowerCAmelCase_       ,       unittest.TestCase      ):
 __lowercase :							str        = (
     (
         AlbertModel,
         AlbertForPreTraining,
         AlbertForMaskedLM,
         AlbertForMultipleChoice,
         AlbertForSequenceClassification,
         AlbertForTokenClassification,
         AlbertForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 __lowercase :							Tuple        = (
     {
         'feature-extraction': AlbertModel,
         'fill-mask': AlbertForMaskedLM,
         'question-answering': AlbertForQuestionAnswering,
         'text-classification': AlbertForSequenceClassification,
         'token-classification': AlbertForTokenClassification,
         'zero-shot': AlbertForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowercase :							Dict        = True
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__=False )					->				int:




        '''simple docstring'''
        lowercase__:   List[str]  			=   super()._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				, return_labels=__lowerCAmelCase )

        if return_labels:
               if model_class in get_values(__lowerCAmelCase ):
                      lowercase__:   Optional[Any]  			=   torch.zeros(
                          (self.model_tester.batch_size, self.model_tester.seq_length)				, dtype=torch.long				, device=__lowerCAmelCase )
                      lowercase__:   List[str]  			=   torch.zeros(
                          self.model_tester.batch_size				, dtype=torch.long				, device=__lowerCAmelCase )
        return inputs_dict
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        lowercase__:   Dict  			=   AlbertModelTester(self )
        lowercase__:   Union[str, Any]  			=   ConfigTester(self				, config_class=__lowerCAmelCase				, hidden_size=37 )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        self.config_tester.run_common_tests()
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[int]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        lowercase__:   Dict  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   Any  			=   self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
               lowercase__:   List[str]  			=   type
               self.model_tester.create_and_check_model(*__lowerCAmelCase )
 @slow
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__:   Tuple  			=   AlbertModel.from_pretrained(__lowerCAmelCase )
               self.assertIsNotNone(__lowerCAmelCase )





@require_torch
class   __a			(    unittest.TestCase      ):
 @slow
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        lowercase__:   Tuple  			=   AlbertModel.from_pretrained('albert-base-v2' )
        lowercase__:   Union[str, Any]  			=   torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
        lowercase__:   str  			=   torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
        with torch.no_grad():
               lowercase__:   Optional[Any]  			=   model(__lowerCAmelCase				, attention_mask=__lowerCAmelCase )[0]
        lowercase__:   List[Any]  			=   torch.Size((1, 11, 768) )
        self.assertEqual(output.shape				, __lowerCAmelCase )
        lowercase__:   Union[str, Any]  			=   torch.tensor(
            [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]] )

        self.assertTrue(torch.allclose(output[:, 1:4, 1:4]				, __lowerCAmelCase				, atol=1E-4 ) )



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