




"""simple docstring"""

import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           FocalNetBackbone,
           FocalNetForImageClassification,
           FocalNetForMaskedImageModeling,
           FocalNetModel,
       )
       from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor





class     lowercase_	:



 '''simple docstring'''

 def __init__(			self	:	Any   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	List[str]=13   ,							_UpperCAmelCase	:	Union[str, Any]=32   ,							_UpperCAmelCase	:	List[str]=2   ,							_UpperCAmelCase	:	List[str]=3   ,							_UpperCAmelCase	:	Optional[Any]=16   ,							_UpperCAmelCase	:	Tuple=[32, 64, 128]   ,							_UpperCAmelCase	:	Dict=[1, 2, 1]   ,							_UpperCAmelCase	:	Union[str, Any]=[2, 2, 4]   ,							_UpperCAmelCase	:	Dict=2   ,							_UpperCAmelCase	:	Optional[Any]=2.0   ,							_UpperCAmelCase	:	int=True   ,							_UpperCAmelCase	:	Union[str, Any]=0.0   ,							_UpperCAmelCase	:	Tuple=0.0   ,							_UpperCAmelCase	:	List[Any]=0.1   ,							_UpperCAmelCase	:	Union[str, Any]="gelu"   ,							_UpperCAmelCase	:	Any=False   ,							_UpperCAmelCase	:	Union[str, Any]=True   ,							_UpperCAmelCase	:	Union[str, Any]=0.02   ,							_UpperCAmelCase	:	Any=1E-5   ,							_UpperCAmelCase	:	str=True   ,							_UpperCAmelCase	:	int=None   ,							_UpperCAmelCase	:	Optional[int]=True   ,							_UpperCAmelCase	:	Any=10   ,							_UpperCAmelCase	:	Optional[Any]=8   ,							_UpperCAmelCase	:	Any=["stage1", "stage2"]   ,							_UpperCAmelCase	:	Optional[Any]=[1, 2]   ,							):
       _A        =       parent
       _A        =       batch_size
       _A        =       image_size
       _A        =       patch_size
       _A        =       num_channels
       _A        =       embed_dim
       _A        =       hidden_sizes
       _A        =       depths
       _A        =       num_heads
       _A        =       window_size
       _A        =       mlp_ratio
       _A        =       qkv_bias
       _A        =       hidden_dropout_prob
       _A        =       attention_probs_dropout_prob
       _A        =       drop_path_rate
       _A        =       hidden_act
       _A        =       use_absolute_embeddings
       _A        =       patch_norm
       _A        =       layer_norm_eps
       _A        =       initializer_range
       _A        =       is_training
       _A        =       scope
       _A        =       use_labels
       _A        =       type_sequence_label_size
       _A        =       encoder_stride
       _A        =       out_features
       _A        =       out_indices

 def       lowerCAmelCase_							(			self	:	int		):
       _A        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       _A        =       None
       if self.use_labels:
             _A        =       ids_tensor([self.batch_size]   ,							self.type_sequence_label_size		)

       _A        =       self.get_config()

       return config, pixel_values, labels

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       return FocalNetConfig(
           image_size=self.image_size   ,							patch_size=self.patch_size   ,							num_channels=self.num_channels   ,							embed_dim=self.embed_dim   ,							hidden_sizes=self.hidden_sizes   ,							depths=self.depths   ,							num_heads=self.num_heads   ,							window_size=self.window_size   ,							mlp_ratio=self.mlp_ratio   ,							qkv_bias=self.qkv_bias   ,							hidden_dropout_prob=self.hidden_dropout_prob   ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,							drop_path_rate=self.drop_path_rate   ,							hidden_act=self.hidden_act   ,							use_absolute_embeddings=self.use_absolute_embeddings   ,							path_norm=self.patch_norm   ,							layer_norm_eps=self.layer_norm_eps   ,							initializer_range=self.initializer_range   ,							encoder_stride=self.encoder_stride   ,							out_features=self.out_features   ,							out_indices=self.out_indices   ,							)

 def       lowerCAmelCase_							(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Tuple		):
       _A        =       FocalNetModel(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       _A        =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths		) - 1))
       _A        =       int(config.embed_dim * 2 ** (len(config.depths		) - 1)		)

       self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, expected_seq_len, expected_dim)		)

 def       lowerCAmelCase_							(			self	:	List[str]   ,							_UpperCAmelCase	:	Optional[int]   ,							_UpperCAmelCase	:	Any   ,							_UpperCAmelCase	:	List[str]		):
       _A        =       FocalNetBackbone(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)   ,							len(config.out_features		)		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)   ,							[self.batch_size, self.image_size, 8, 8]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)   ,							len(config.out_features		)		)
       self.parent.assertListEqual(model.channels   ,							config.hidden_sizes[:-1]		)

       # verify backbone works with out_features=None
       _A        =       None
       _A        =       FocalNetBackbone(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)   ,							1		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)   ,							[self.batch_size, self.image_size * 2, 4, 4]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)   ,							1		)
       self.parent.assertListEqual(model.channels   ,							[config.hidden_sizes[-1]]		)

 def       lowerCAmelCase_							(			self	:	Dict   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Dict   ,							_UpperCAmelCase	:	int		):
       _A        =       FocalNetForMaskedImageModeling(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(
           result.reconstruction.shape   ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)		)

       # test greyscale images
       _A        =       1
       _A        =       FocalNetForMaskedImageModeling(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       _A        =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(result.reconstruction.shape   ,							(self.batch_size, 1, self.image_size, self.image_size)		)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	str		):
       _A        =       self.type_sequence_label_size
       _A        =       FocalNetForImageClassification(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase   ,							labels=_UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size)		)

       # test greyscale images
       _A        =       1
       _A        =       FocalNetForImageClassification(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       _A        =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size)		)



 def       lowerCAmelCase_							(			self	:	Tuple		):
       _A        =       self.prepare_config_and_inputs()

       _A       ,   _A       ,   _A        =       config_and_inputs
       _A        =       {'pixel_values': pixel_values}
       return config, inputs_dict





@require_torch
class     lowercase_	(					__lowerCAmelCase      ,     __lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					int				  =     (
     (
         FocalNetModel,
         FocalNetForImageClassification,
         FocalNetForMaskedImageModeling,
         FocalNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase   :					List[Any]				  =     (
     {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
     if is_torch_available()
     else {}
 )
 UpperCAmelCase   :					Optional[int]				  =     False

 UpperCAmelCase   :					Tuple				  =     False
 UpperCAmelCase   :					List[str]				  =     False
 UpperCAmelCase   :					str				  =     False
 UpperCAmelCase   :					Optional[Any]				  =     False

 def       lowerCAmelCase_							(			self	:	Optional[Any]		):
       _A        =       FocalNetModelTester(self		)
       _A        =       ConfigTester(self   ,							config_class=_UpperCAmelCase   ,							embed_dim=37   ,							has_text_modality=_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       return

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)

 @unittest.skip(reason='FocalNet does not use inputs_embeds'		)
 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       pass

 @unittest.skip(reason='FocalNet does not use feedforward chunking'		)
 def       lowerCAmelCase_							(			self	:	int		):
       pass

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes[:-1]:
             _A        =       model_class(_UpperCAmelCase		)
             self.assertIsInstance(model.get_input_embeddings()   ,							(nn.Module)		)
             _A        =       model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_UpperCAmelCase   ,							nn.Linear		)		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes[:-1]:
             _A        =       model_class(_UpperCAmelCase		)
             _A        =       inspect.signature(model.forward		)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             _A        =       [*signature.parameters.keys()]

             _A        =       ['pixel_values']
             self.assertListEqual(arg_names[:1]   ,							_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	Union[str, Any]		):
       _A        =       model_class(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       with torch.no_grad():
             _A        =       model(**self._prepare_for_class(_UpperCAmelCase   ,							_UpperCAmelCase		)		)

       _A        =       outputs.hidden_states

       _A        =       getattr(
           self.model_tester   ,							'expected_num_hidden_layers'   ,							len(self.model_tester.depths		) + 1		)
       self.assertEqual(len(_UpperCAmelCase		)   ,							_UpperCAmelCase		)

       # FocalNet has a different seq_length
       _A        =       (
           config.patch_size
           if isinstance(config.patch_size   ,							collections.abc.Iterable		)
           else (config.patch_size, config.patch_size)
       )

       _A        =       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

       self.assertListEqual(
           list(hidden_states[0].shape[-2:]		)   ,							[num_patches, self.model_tester.embed_dim]   ,							)

       _A        =       outputs.reshaped_hidden_states
       self.assertEqual(len(_UpperCAmelCase		)   ,							_UpperCAmelCase		)

       _A       ,   _A       ,   _A       ,   _A        =       reshaped_hidden_states[0].shape
       _A        =       (
           reshaped_hidden_states[0].view(_UpperCAmelCase   ,							_UpperCAmelCase   ,							height * width		).permute(0   ,							2   ,							1		)
       )
       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:]		)   ,							[num_patches, self.model_tester.embed_dim]   ,							)

 def       lowerCAmelCase_							(			self	:	Tuple		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       _A        =       (
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size   ,							collections.abc.Iterable		)
           else (self.model_tester.image_size, self.model_tester.image_size)
       )

       for model_class in self.all_model_classes[:-1]:
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             _A        =       True

             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()
       _A        =       3

       _A        =       (
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size   ,							collections.abc.Iterable		)
           else (self.model_tester.image_size, self.model_tester.image_size)
       )
       _A        =       (
           config.patch_size
           if isinstance(config.patch_size   ,							collections.abc.Iterable		)
           else (config.patch_size, config.patch_size)
       )

       _A        =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       _A        =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes[:-1]:
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							(padded_height, padded_width)		)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							(padded_height, padded_width)		)

 @slow
 def       lowerCAmelCase_							(			self	:	Tuple		):
       for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A        =       FocalNetModel.from_pretrained(_UpperCAmelCase		)
             self.assertIsNotNone(_UpperCAmelCase		)



 def       lowerCAmelCase_							(			self	:	str		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       _A        =       _config_zero_init(_UpperCAmelCase		)
       for model_class in self.all_model_classes:
             _A        =       model_class(config=_UpperCAmelCase		)
             for name, param in model.named_parameters():
                   if "embeddings" not in name and param.requires_grad:
                         self.assertIn(
                             ((param.data.mean() * 1E9).round() / 1E9).item()   ,							[0.0, 1.0]   ,							msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''   ,							)





@require_vision
@require_torch
class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''

 @cached_property
 def       lowerCAmelCase_							(			self	:	str		):
       # TODO update organization
       return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'		) if is_vision_available() else None



 @slow
 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A        =       FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'		).to(_UpperCAmelCase		)
       _A        =       self.default_image_processor

       _A        =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
       _A        =       image_processor(images=_UpperCAmelCase   ,							return_tensors='pt'		).to(_UpperCAmelCase		)

       # forward pass
       with torch.no_grad():
             _A        =       model(**_UpperCAmelCase		)

       # verify the logits
       _A        =       torch.Size((1, 1_000)		)
       self.assertEqual(outputs.logits.shape   ,							_UpperCAmelCase		)
       _A        =       torch.tensor([0.2166, -0.4368, 0.2191]		).to(_UpperCAmelCase		)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,							_UpperCAmelCase   ,							atol=1E-4		)		)
       self.assertTrue(outputs.logits.argmax(dim=-1		).item()   ,							281		)





@require_torch
class     lowercase_	(					__lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					List[str]				  =     (FocalNetBackbone,) if is_torch_available() else ()
 UpperCAmelCase   :					Union[str, Any]				  =     FocalNetConfig

 UpperCAmelCase   :					Tuple				  =     False

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       FocalNetModelTester(self		)







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

a         =      logging.get_logger(__name__)






def 						_snake_case					( _snake_case							: bool    ,  _snake_case							: bool							)   -> Tuple:






      '''simple docstring'''


      def run_func(_snake_case							: Any							):
            @wraps(_snake_case							)
            def run_in_eager_mode(*_snake_case							: List[str]    ,  **_snake_case							: Tuple							):
                  return func(*_snake_case    ,  **_snake_case							)

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

            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 						_snake_case					( _snake_case							: int    ,  _snake_case							: int    ,  _snake_case							: int							)   -> ["tf.Tensor"]:






      '''simple docstring'''


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







class     lowercase_	(					__lowerCAmelCase							):



 '''simple docstring'''
 UpperCAmelCase   :					TensorFlowBenchmarkArguments
 UpperCAmelCase   :					PretrainedConfig
 UpperCAmelCase   :					str				  =     "TensorFlow"

 @property
 def       lowerCAmelCase_							(			self	:	str		):
       return tf.__version__

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

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

 def       lowerCAmelCase_							(			self	:	Dict   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	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]   ,							_UpperCAmelCase		)
       _A        =       self.args.strategy
       if strategy is None:
             raise ValueError('A device strategy has to be initialized before using TensorFlow.'		)
       _A        =       self._prepare_inference_func(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)
       return self._measure_memory(_inference		)

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

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

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

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

       _A        =       (
           hasattr(_UpperCAmelCase   ,							'architectures'		)
           and isinstance(config.architectures   ,							_UpperCAmelCase		)
           and len(config.architectures		) > 0
       )
       if not self.args.only_pretrain_model and has_model_class_in_config:
             try:
                   _A        =       'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
                   _A        =       __import__('transformers'   ,							fromlist=[model_class]		)
                   _A        =       getattr(_UpperCAmelCase   ,							_UpperCAmelCase		)
                   _A        =       model_cls(_UpperCAmelCase		)
             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:
             _A        =       TF_MODEL_MAPPING[config.__class__](_UpperCAmelCase		)

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

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

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

       _A        =       encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

       return _inference

 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	int		):
       _A        =       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.'		)

       _A        =       (
           hasattr(_UpperCAmelCase   ,							'architectures'		)
           and isinstance(config.architectures   ,							_UpperCAmelCase		)
           and len(config.architectures		) > 0
       )
       if not self.args.only_pretrain_model and has_model_class_in_config:
             try:
                   _A        =       'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
                   _A        =       __import__('transformers'   ,							fromlist=[model_class]		)
                   _A        =       getattr(_UpperCAmelCase   ,							_UpperCAmelCase		)
                   _A        =       model_cls(_UpperCAmelCase		)
             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:
             _A        =       TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_UpperCAmelCase		)

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

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

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

       _A        =       encoder_decoder_train if config.is_encoder_decoder else encoder_train

       return _train

 def       lowerCAmelCase_							(			self	:	Tuple   ,							_UpperCAmelCase	:	int		):
       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(_UpperCAmelCase   ,							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
                   _A        =       timeit.repeat(
                       _UpperCAmelCase   ,							repeat=self.args.repeat   ,							number=10   ,							)

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



 def       lowerCAmelCase_							(			self	:	Optional[int]   ,							_UpperCAmelCase	:	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.'		)
                         _A        =       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.'		)
                               _A        =       '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()
                               _A        =       nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx		)
                               _A        =       nvml.nvmlDeviceGetMemoryInfo(_UpperCAmelCase		)
                               _A        =       meminfo.used
                               _A        =       Memory(_UpperCAmelCase		)
                               # 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.'		)
                               _A        =       None
                         else:
                               _A        =       measure_peak_memory_cpu(_UpperCAmelCase		)
                               _A        =       Memory(_UpperCAmelCase		) if isinstance(_UpperCAmelCase   ,							_UpperCAmelCase		) else memory_bytes
                   if self.args.trace_memory_line_by_line:
                         _A        =       stop_memory_tracing(_UpperCAmelCase		)
                         if memory is None:
                               _A        =       summary.total
                   else:
                         _A        =       None

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

