





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					:		Union[str, Any]		=							logging.get_logger(__name__)




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



      def run_func(lowerCAmelCase_	):
            @wraps(lowerCAmelCase_	)
            def run_in_eager_mode(*lowerCAmelCase_			,      **lowerCAmelCase_	):
                  return func(*lowerCAmelCase_			,      **lowerCAmelCase_	)

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

            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    _a    (							lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



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





class lowerCamelCase						(a__					):
  _lowercase  :	TensorFlowBenchmarkArguments
  _lowercase  :	PretrainedConfig
  _lowercase  :	str       					=				"TensorFlow"







  @property
  def 				UpperCAmelCase_				(		self		)		->						Union[str, Any]:






        """simple docstring"""





        return tf.__version__







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						float:






        """simple docstring"""





        _snake_case		:	Optional[Any]					     =     self.args.strategy
        if strategy is None:
              raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''		)
        _snake_case		:	Optional[Any]					     =     self._prepare_inference_func(lowercase__     ,     lowercase__     ,     lowercase__		)
        return self._measure_speed(_inference		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						float:






        """simple docstring"""





        _snake_case		:	Dict					     =     self.args.strategy
        if strategy is None:
              raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''		)
        _snake_case		:	Tuple					     =     self._prepare_train_func(lowercase__     ,     lowercase__     ,     lowercase__		)
        return self._measure_speed(_train		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						[Memory, Optional[MemorySummary]]:






        """simple docstring"""





        if self.args.is_gpu:
              tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]     ,     lowercase__		)
        _snake_case		:	Optional[int]					     =     self.args.strategy
        if strategy is None:
              raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''		)
        _snake_case		:	List[Any]					     =     self._prepare_inference_func(lowercase__     ,     lowercase__     ,     lowercase__		)
        return self._measure_memory(_inference		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						[Memory, Optional[MemorySummary]]:






        """simple docstring"""





        if self.args.is_gpu:
              tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]     ,     lowercase__		)
        _snake_case		:	Union[str, Any]					     =     self.args.strategy
        if strategy is None:
              raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''		)

        _snake_case		:	List[str]					     =     self._prepare_train_func(lowercase__     ,     lowercase__     ,     lowercase__		)
        return self._measure_memory(_train		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						Callable[[], None]:






        """simple docstring"""





        _snake_case		:	Optional[int]					     =     self.config_dict[model_name]

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

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

        # encoder-decoder has vocab size saved differently
        _snake_case		:	Optional[Any]					     =     config.vocab_size if hasattr(lowercase__     ,     '''vocab_size'''		) else config.encoder.vocab_size
        _snake_case		:	List[str]					     =     random_input_ids(lowercase__     ,     lowercase__     ,     lowercase__		)

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

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

        _snake_case		:	List[Any]					     =     encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

        return _inference







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						Callable[[], None]:






        """simple docstring"""





        _snake_case		:	int					     =     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.'''		)

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

        # encoder-decoder has vocab size saved differently
        _snake_case		:	Union[str, Any]					     =     config.vocab_size if hasattr(lowercase__     ,     '''vocab_size'''		) else config.encoder.vocab_size
        _snake_case		:	Any					     =     random_input_ids(lowercase__     ,     lowercase__     ,     lowercase__		)

        @run_with_tf_optimizations(self.args.eager_mode     ,     self.args.use_xla		)
        def encoder_decoder_train():
              _snake_case		:	Optional[int]					     =     model(lowercase__     ,     decoder_input_ids=lowercase__     ,     labels=lowercase__     ,     training=lowercase__		)[0]
              _snake_case		:	List[str]					     =     tf.gradients(lowercase__     ,     model.trainable_variables		)
              return gradients

        @run_with_tf_optimizations(self.args.eager_mode     ,     self.args.use_xla		)
        def encoder_train():
              _snake_case		:	List[str]					     =     model(lowercase__     ,     labels=lowercase__     ,     training=lowercase__		)[0]
              _snake_case		:	Optional[int]					     =     tf.gradients(lowercase__     ,     model.trainable_variables		)
              return gradients

        _snake_case		:	List[Any]					     =     encoder_decoder_train if config.is_encoder_decoder else encoder_train

        return _train







  def 				UpperCAmelCase_				(		self     ,     lowercase__		)		->						float:






        """simple docstring"""





        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(lowercase__     ,     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
                    _snake_case		:	Tuple					     =     timeit.repeat(
                        lowercase__     ,     repeat=self.args.repeat     ,     number=10     ,     )

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







  def 				UpperCAmelCase_				(		self     ,     lowercase__		)		->						[Memory, MemorySummary]:






        """simple docstring"""





        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.'''		)
                          _snake_case		:	List[Any]					     =     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.'''		)
                                _snake_case		:	str					     =     '''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()
                                _snake_case		:	Optional[int]					     =     nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx		)
                                _snake_case		:	Tuple					     =     nvml.nvmlDeviceGetMemoryInfo(lowercase__		)
                                _snake_case		:	Any					     =     meminfo.used
                                _snake_case		:	str					     =     Memory(lowercase__		)
                                # 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.'''		)
                                _snake_case		:	int					     =     None
                          else:
                                _snake_case		:	Optional[int]					     =     measure_peak_memory_cpu(lowercase__		)
                                _snake_case		:	List[str]					     =     Memory(lowercase__		) if isinstance(lowercase__     ,     lowercase__		) else memory_bytes
                    if self.args.trace_memory_line_by_line:
                          _snake_case		:	Optional[int]					     =     stop_memory_tracing(lowercase__		)
                          if memory is None:
                                _snake_case		:	Any					     =     summary.total
                    else:
                          _snake_case		:	Dict					     =     None

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









'''simple docstring'''

from collections.abc import Generator




def    _a    (							):





      """simple docstring"""



      _snake_case     ,							_snake_case		:	Union[str, Any]					     =     0, 1
      while True:
            _snake_case     ,							_snake_case		:	List[str]					     =     b, a + b
            yield b




def    _a    (							lowerCAmelCase_ = 1_000	):





      """simple docstring"""



      _snake_case		:	List[str]					     =     1
      _snake_case		:	Dict					     =     fibonacci_generator()
      while len(str(next(lowerCAmelCase_	)	)	) < n:
            answer += 1
      return answer + 1


if __name__ == "__main__":
   print(solution(int(str(input()).strip())))


