


import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase		       =							logging.get_logger(__name__)

__lowerCAmelCase		       =							{
    '''google/pix2struct-textcaps-base''': (
        '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json'''
    ),
}





class   __a			(    lowerCAmelCase_      ):
 __lowercase :							Optional[int]        = 'pix2struct_text_model'
 __lowercase :							Dict        = ['past_key_values']
 __lowercase :							Union[str, Any]        = {
     'hidden_size': 'hidden_size',
     'num_attention_heads': 'num_heads',
     'num_hidden_layers': 'num_layers',
 }
 def __init__(   self				, lowerCAmelCase__=50_244				, lowerCAmelCase__=768				, lowerCAmelCase__=64				, lowerCAmelCase__=2_048				, lowerCAmelCase__=12				, lowerCAmelCase__=12				, lowerCAmelCase__=32				, lowerCAmelCase__=128				, lowerCAmelCase__=0.1				, lowerCAmelCase__=1E-6				, lowerCAmelCase__=1.0				, lowerCAmelCase__="gelu_new"				, lowerCAmelCase__=0				, lowerCAmelCase__=False				, lowerCAmelCase__=0				, lowerCAmelCase__=1				, lowerCAmelCase__=False				, lowerCAmelCase__=True				, **lowerCAmelCase__				, )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   int  			=   vocab_size
        lowercase__:   Tuple  			=   hidden_size
        lowercase__:   Optional[int]  			=   d_kv
        lowercase__:   Optional[Any]  			=   d_ff
        lowercase__:   Any  			=   num_layers
        lowercase__:   Optional[Any]  			=   num_heads
        lowercase__:   List[str]  			=   relative_attention_num_buckets
        lowercase__:   Optional[Any]  			=   relative_attention_max_distance
        lowercase__:   Tuple  			=   dropout_rate
        lowercase__:   Tuple  			=   layer_norm_epsilon
        lowercase__:   Any  			=   initializer_factor
        lowercase__:   Optional[int]  			=   use_cache

        lowercase__:   Union[str, Any]  			=   eos_token_id
        lowercase__:   Tuple  			=   decoder_start_token_id

        # for backwards compatibility
        lowercase__:   Any  			=   dense_act_fn

        super().__init__(
            pad_token_id=__lowerCAmelCase				, eos_token_id=__lowerCAmelCase				, decoder_start_token_id=__lowerCAmelCase				, tie_word_embeddings=__lowerCAmelCase				, is_decoder=__lowerCAmelCase				, **__lowerCAmelCase				, )
 @classmethod
 def 		SCREAMING_SNAKE_CASE__   (   cls				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				Optional[Any]:




        '''simple docstring'''
        cls._set_token_in_kwargs(__lowerCAmelCase )

        lowercase__			,						lowercase__:   str  			=   cls.get_config_dict(__lowerCAmelCase				, **__lowerCAmelCase )

        # get the text config dict if we are loading from Pix2StructConfig
        if config_dict.get('model_type' ) == "pix2struct":
               lowercase__:   Union[str, Any]  			=   config_dict['text_config']

        if "model_type" in config_dict and hasattr(cls				, 'model_type' ) and config_dict["model_type"] != cls.model_type:
               logger.warning(
                   F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                   F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )

        return cls.from_dict(__lowerCAmelCase				, **__lowerCAmelCase )





class   __a			(    lowerCAmelCase_      ):
 __lowercase :							Tuple        = 'pix2struct_vision_model'
 def __init__(   self				, lowerCAmelCase__=768				, lowerCAmelCase__=768				, lowerCAmelCase__=2_048				, lowerCAmelCase__=64				, lowerCAmelCase__=12				, lowerCAmelCase__=12				, lowerCAmelCase__="gelu_new"				, lowerCAmelCase__=1E-6				, lowerCAmelCase__=0.0				, lowerCAmelCase__=0.0				, lowerCAmelCase__=1E-10				, lowerCAmelCase__=1.0				, lowerCAmelCase__=4_096				, lowerCAmelCase__=32				, lowerCAmelCase__=128				, **lowerCAmelCase__				, )					->				int:




        '''simple docstring'''
        super().__init__(**__lowerCAmelCase )

        lowercase__:   str  			=   hidden_size
        lowercase__:   Tuple  			=   patch_embed_hidden_size
        lowercase__:   Dict  			=   d_ff
        lowercase__:   str  			=   dropout_rate
        lowercase__:   Union[str, Any]  			=   num_hidden_layers
        lowercase__:   str  			=   num_attention_heads
        lowercase__:   Union[str, Any]  			=   initializer_range
        lowercase__:   str  			=   initializer_factor
        lowercase__:   int  			=   attention_dropout
        lowercase__:   Tuple  			=   layer_norm_eps
        lowercase__:   Tuple  			=   dense_act_fn
        lowercase__:   List[str]  			=   seq_len
        lowercase__:   str  			=   relative_attention_num_buckets
        lowercase__:   Union[str, Any]  			=   relative_attention_max_distance
        lowercase__:   List[Any]  			=   d_kv
 @classmethod
 def 		SCREAMING_SNAKE_CASE__   (   cls				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				str:




        '''simple docstring'''
        cls._set_token_in_kwargs(__lowerCAmelCase )

        lowercase__			,						lowercase__:   Optional[Any]  			=   cls.get_config_dict(__lowerCAmelCase				, **__lowerCAmelCase )

        # get the vision config dict if we are loading from Pix2StructConfig
        if config_dict.get('model_type' ) == "pix2struct":
               lowercase__:   Union[str, Any]  			=   config_dict['vision_config']

        if "model_type" in config_dict and hasattr(cls				, 'model_type' ) and config_dict["model_type"] != cls.model_type:
               logger.warning(
                   F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                   F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )

        return cls.from_dict(__lowerCAmelCase				, **__lowerCAmelCase )





class   __a			(    lowerCAmelCase_      ):
 __lowercase :							Any        = 'pix2struct'
 __lowercase :							Any        = True
 def __init__(   self				, lowerCAmelCase__=None				, lowerCAmelCase__=None				, lowerCAmelCase__=1.0				, lowerCAmelCase__=0.0_2				, lowerCAmelCase__=False				, lowerCAmelCase__=False				, lowerCAmelCase__=True				, **lowerCAmelCase__				, )					->				Dict:




        '''simple docstring'''
        super().__init__(tie_word_embeddings=__lowerCAmelCase				, is_encoder_decoder=__lowerCAmelCase				, **__lowerCAmelCase )

        if text_config is None:
               lowercase__:   Optional[Any]  			=   {}
               logger.info('text_config is None. Initializing the Pix2StructTextConfig with default values.' )

        if vision_config is None:
               lowercase__:   Any  			=   {}
               logger.info('vision_config is None. Initializing the Pix2StructVisionConfig with default values.' )

        lowercase__:   List[str]  			=   PixaStructTextConfig(**__lowerCAmelCase )
        lowercase__:   Optional[Any]  			=   PixaStructVisionConfig(**__lowerCAmelCase )

        lowercase__:   int  			=   self.text_config.decoder_start_token_id
        lowercase__:   Union[str, Any]  			=   self.text_config.pad_token_id
        lowercase__:   Optional[Any]  			=   self.text_config.eos_token_id

        lowercase__:   Optional[Any]  			=   initializer_factor
        lowercase__:   List[Any]  			=   initializer_range

        lowercase__:   Union[str, Any]  			=   self.initializer_range
        lowercase__:   str  			=   self.initializer_range

        lowercase__:   List[str]  			=   is_vqa
 @classmethod
 def 		SCREAMING_SNAKE_CASE__   (   cls				, lowerCAmelCase__				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        return cls(text_config=text_config.to_dict()				, vision_config=vision_config.to_dict()				, **__lowerCAmelCase )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   str  			=   copy.deepcopy(self.__dict__ )
        lowercase__:   int  			=   self.text_config.to_dict()
        lowercase__:   Tuple  			=   self.vision_config.to_dict()
        lowercase__:   Optional[int]  			=   self.__class__.model_type
        return output



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