




"""simple docstring"""


import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


A_      			=       '''bart'''
A_      			=       True


@st.cache(allow_output_mutation=__UpperCamelCase					)
def       UpperCAmelCase__ ():
  """simple docstring"""

  if LOAD_DENSE_INDEX:
    _snake_case							:	Optional[Any]			=						AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased"""					)
    _snake_case							:	Tuple			=						AutoModel.from_pretrained("""yjernite/retribert-base-uncased"""					).to("""cuda:0"""					)
    _snake_case							:	str			=						qar_model.eval()
  else:
    _snake_case	,      _snake_case							:	List[Any]			=						(None, None)
  if MODEL_TYPE == "bart":
    _snake_case							:	Tuple			=						AutoTokenizer.from_pretrained("""yjernite/bart_eli5"""					)
    _snake_case							:	Union[str, Any]			=						AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5"""					).to("""cuda:0"""					)
    _snake_case							:	Dict			=						torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth"""					)
    sas_model.load_state_dict(save_dict["""model"""]					)
    _snake_case							:	Tuple			=						sas_model.eval()
  else:
    _snake_case	,      _snake_case							:	Dict			=						make_qa_sas_model(
        model_name="""t5-small"""	,     from_file="""seq2seq_models/eli5_t5_model_1024_4.pth"""	,     device="""cuda:0"""					)
  return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)


@st.cache(allow_output_mutation=__UpperCamelCase					)
def       UpperCAmelCase__ ():
  """simple docstring"""

  if LOAD_DENSE_INDEX:
    _snake_case							:	Optional[Any]			=						faiss.StandardGpuResources()
    _snake_case							:	List[Any]			=						datasets.load_dataset(path="""wiki_snippets"""	,     name="""wiki40b_en_100_0"""					)["""train"""]
    _snake_case							:	Tuple			=						np.memmap(
        """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"""	,     dtype="""float32"""	,     mode="""r"""	,     shape=(wikiaab_passages.num_rows, 1_28)	,     )
    _snake_case							:	Any			=						faiss.IndexFlatIP(1_28					)
    _snake_case							:	Dict			=						faiss.index_cpu_to_gpu(__UpperCamelCase	,     1	,     __UpperCamelCase					)
    wikiaab_gpu_index_flat.add(__UpperCamelCase					)  # TODO fix for larger GPU
  else:
    _snake_case	,      _snake_case							:	List[Any]			=						(None, None)
  _snake_case							:	Union[str, Any]			=						Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}]					)
  return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)


@st.cache(allow_output_mutation=__UpperCamelCase					)
def       UpperCAmelCase__ ():
  """simple docstring"""

  _snake_case							:	List[Any]			=						datasets.load_dataset("""eli5"""	,     name="""LFQA_reddit"""					)
  _snake_case							:	int			=						elia["""train_eli5"""]
  _snake_case							:	str			=						np.memmap(
      """eli5_questions_reps.dat"""	,     dtype="""float32"""	,     mode="""r"""	,     shape=(elia_train.num_rows, 1_28)					)
  _snake_case							:	List[str]			=						faiss.IndexFlatIP(1_28					)
  eli5_train_q_index.add(__UpperCamelCase					)
  return (elia_train, eli5_train_q_index)


A_			,					A_			,					A_      			=       load_indexes()
A_			,					A_			,					A_			,					A_      			=       load_models()
A_			,					A_      			=       load_train_data()


def       UpperCAmelCase__ (snake_case__							:      Optional[Any]	,     snake_case__							:      str=10					):
  """simple docstring"""

  _snake_case							:	List[Any]			=						embed_questions_for_retrieval([question]	,     __UpperCamelCase	,     __UpperCamelCase					)
  _snake_case	,      _snake_case							:	Any			=						eli5_train_q_index.search(__UpperCamelCase	,     __UpperCamelCase					)
  _snake_case							:	Any			=						[elia_train[int(__UpperCamelCase					)] for i in I[0]]
  return nn_examples


def       UpperCAmelCase__ (snake_case__							:      str	,     snake_case__							:      int="wiki40b"	,     snake_case__							:      List[Any]="dense"	,     snake_case__							:      Dict=10					):
  """simple docstring"""

  if source == "none":
    _snake_case	,      _snake_case							:	Tuple			=						(""" <P> """.join(["""""" for _ in range(11					)]					).strip(), [])
  else:
    if method == "dense":
      _snake_case	,      _snake_case							:	str			=						query_qa_dense_index(
          __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase					)
    else:
      _snake_case	,      _snake_case							:	Dict			=						query_es_index(
          __UpperCamelCase	,     __UpperCamelCase	,     index_name="""english_wiki40b_snippets_100w"""	,     n_results=__UpperCamelCase	,     )
  _snake_case							:	List[Any]			=						[
      (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst
  ]
  _snake_case							:	int			=						"""question: {} context: {}""".format(__UpperCamelCase	,     __UpperCamelCase					)
  return question_doc, support_list


@st.cache(
    hash_funcs={
        torch.Tensor: (lambda snake_case__					: None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda snake_case__					: None),
    }					)
def       UpperCAmelCase__ (snake_case__							:      Any	,     snake_case__							:      Tuple	,     snake_case__							:      Optional[Any]	,     snake_case__							:      str=64	,     snake_case__							:      Union[str, Any]=2_56	,     snake_case__							:      int=False	,     snake_case__							:      List[str]=2	,     snake_case__							:      Dict=0.95	,     snake_case__							:      Dict=0.8					):
  """simple docstring"""

  with torch.no_grad():
    _snake_case							:	Optional[Any]			=						qa_sas_generate(
        __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     num_answers=1	,     num_beams=__UpperCamelCase	,     min_len=__UpperCamelCase	,     max_len=__UpperCamelCase	,     do_sample=__UpperCamelCase	,     temp=__UpperCamelCase	,     top_p=__UpperCamelCase	,     top_k=__UpperCamelCase	,     max_input_length=10_24	,     device="""cuda:0"""	,     )[0]
  return (answer, support_list)


st.title('''Long Form Question Answering with ELI5''')

# Start sidebar
A_      			=       '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'''
A_      			=       '''
<html>
  <head>
    <style>
      .img-container {
        padding-left: 90px;
        padding-right: 90px;
        padding-top: 50px;
        padding-bottom: 50px;
        background-color: #f0f3f9;
      }
    </style>
  </head>
  <body>
    <span class="img-container"> <!-- Inline parent element -->
      %s
    </span>
  </body>
</html>
''' % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
A_      			=       '''
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
'''
st.sidebar.markdown(description, unsafe_allow_html=True)

A_      			=       [
    '''Answer the question''',
    '''View the retrieved document only''',
    '''View the most similar ELI5 question and answer''',
    '''Show me everything, please!''',
]
A_      			=       st.sidebar.checkbox('''Demo options''')
if demo_options:
     A_      			=       st.sidebar.selectbox(
         '''''',
         action_list,
         index=3,
     )
     A_      			=       action_list.index(action_st)
     A_      			=       st.sidebar.selectbox(
         '''''',
         ['''Show full text of passages''', '''Show passage section titles'''],
         index=0,
     )
     A_      			=       show_type == '''Show full text of passages'''
else:
     A_      			=       3
     A_      			=       True

A_      			=       st.sidebar.checkbox('''Retrieval options''')
if retrieval_options:
     A_      			=       '''
    ### Information retriever options

    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
    '''
     st.sidebar.markdown(retriever_info)
     A_      			=       st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none'''])
     A_      			=       st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed'''])
else:
     A_      			=       '''wiki40b'''
     A_      			=       '''dense'''

A_      			=       '''beam'''
A_      			=       2
A_      			=       64
A_      			=       2_56
A_      			=       None
A_      			=       None
A_      			=       st.sidebar.checkbox('''Generation options''')
if generate_options:
     A_      			=       '''
    ### Answer generation options

    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
    **beam** search, or **sample** from the decoder\'s output probabilities.
    '''
     st.sidebar.markdown(generate_info)
     A_      			=       st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled'''])
     A_      			=       st.sidebar.slider(
         '''Minimum generation length''', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None
     )
     A_      			=       st.sidebar.slider(
         '''Maximum generation length''', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None
     )
     if sampled == "beam":
          A_      			=       st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None)
     else:
          A_      			=       st.sidebar.slider(
              '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
          )
          A_      			=       st.sidebar.slider(
              '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
          )
          A_      			=       None

# start main text
A_      			=       [
    '''<MY QUESTION>''',
    '''How do people make chocolate?''',
    '''Why do we get a fever when we are sick?''',
    '''How can different animals perceive different colors?''',
    '''What is natural language processing?''',
    '''What\'s the best way to treat a sunburn?''',
    '''What exactly are vitamins ?''',
    '''How does nuclear energy provide electricity?''',
    '''What\'s the difference between viruses and bacteria?''',
    '''Why are flutes classified as woodwinds when most of them are made out of metal ?''',
    '''Why do people like drinking coffee even though it tastes so bad?''',
    '''What happens when wine ages? How does it make the wine taste better?''',
    '''If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?''',
    '''How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?''',
    '''How does New Zealand have so many large bird predators?''',
]
A_      			=       st.selectbox(
    '''What would you like to ask? ---- select <MY QUESTION> to enter a new query''',
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
     A_      			=       st.text_input('''Enter your question here:''', '''''')
else:
     A_      			=       question_s

if st.button('''Show me!'''):
     if action in [0, 1, 3]:
          if index_type == "mixed":
               A_			,					A_      			=       make_support(question, source=wiki_source, method='''dense''', n_results=10)
               A_			,					A_      			=       make_support(question, source=wiki_source, method='''sparse''', n_results=10)
               A_      			=       []
               for res_d, res_s in zip(support_list_dense, support_list_sparse):
                    if tuple(res_d) not in support_list:
                         support_list += [tuple(res_d)]
                    if tuple(res_s) not in support_list:
                         support_list += [tuple(res_s)]
               A_      			=       support_list[:10]
               A_      			=       '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list])
          else:
               A_			,					A_      			=       make_support(question, source=wiki_source, method=index_type, n_results=10)
     if action in [0, 3]:
          A_			,					A_      			=       answer_question(
              question_doc,
              sas_model,
              sas_tokenizer,
              min_len=min_len,
              max_len=int(max_len),
              sampling=(sampled == '''sampled'''),
              n_beams=n_beams,
              top_p=top_p,
              temp=temp,
          )
          st.markdown('''### The model generated answer is:''')
          st.write(answer)
     if action in [0, 1, 3] and wiki_source != "none":
          st.markdown('''--- \n ### The model is drawing information from the following Wikipedia passages:''')
          for i, res in enumerate(support_list):
               A_      			=       '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_'''))
               A_      			=       res[1].strip()
               if sec_titles == "":
                    A_      			=       '''[{}]({})'''.format(res[0], wiki_url)
               else:
                    A_      			=       sec_titles.split(''' & ''')
                    A_      			=       ''' & '''.join(
                        ['''[{}]({}#{})'''.format(sec.strip(), wiki_url, sec.strip().replace(''' ''', '''_''')) for sec in sec_list]
                    )
               st.markdown(
                   '''{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}'''.format(i + 1, res[0], sections),
                   unsafe_allow_html=True,
               )
               if show_passages:
                    st.write(
                        '''> <span style="font-family:arial; font-size:10pt;">''' + res[-1] + '''</span>''', unsafe_allow_html=True
                    )
     if action in [2, 3]:
          A_      			=       find_nearest_training(question)
          A_      			=       nn_train_list[0]
          st.markdown(
              '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title'''])
          )
          A_      			=       [
              '''{}. {}'''.format(i + 1, '''  \n'''.join([line.strip() for line in ans.split('''\n''') if line.strip() != '''''']))
              for i, (ans, sc) in enumerate(zip(train_exple['''answers''']['''text'''], train_exple['''answers''']['''score''']))
              if i == 0 or sc > 2
          ]
          st.markdown('''##### Its answers were: \n\n {}'''.format('''\n'''.join(answers_st)))


A_      			=       '''
---

**Disclaimer**

*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
'''






st.sidebar.markdown(disclaimer, unsafe_allow_html=True)






"""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       UpperCAmelCase__ (snake_case__							:      bool	,     snake_case__							:      bool					):
  """simple docstring"""

  def run_func(snake_case__							:      Tuple					):
    @wraps(snake_case__					)
    def run_in_eager_mode(*snake_case__							:      str	,     **snake_case__							:      Any					):
      return func(*snake_case__	,     **snake_case__					)

    @wraps(snake_case__					)
    @tf.function(experimental_compile=snake_case__					)
    def run_in_graph_mode(*snake_case__							:      Any	,     **snake_case__							:      Optional[int]					):
      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       UpperCAmelCase__ (snake_case__							:      int	,     snake_case__							:      int	,     snake_case__							:      int					):
  """simple docstring"""

  _snake_case							:	List[str]			=						random.Random()
  _snake_case							:	Optional[int]			=						[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(  __a				):







 '''simple docstring'''





 lowercase__				      =      42
 lowercase__				      =      42
 lowercase__				      =      "TensorFlow"


 @property
 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   return tf.__version__


 def 				UpperCamelCase_     (       self:	List[str],   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						self.args.strategy
   if strategy is None:
     raise ValueError("""A device strategy has to be initialized before using TensorFlow."""	)
   _snake_case							:	Optional[int]			=						self._prepare_inference_func(a_,   a_,   a_	)
   return self._measure_speed(_inference	)


 def 				UpperCamelCase_     (       self:	int,   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						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_train_func(a_,   a_,   a_	)
   return self._measure_speed(_train	)


 def 				UpperCamelCase_     (       self:	Dict,   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



   if self.args.is_gpu:
     tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx],   a_	)
   _snake_case							:	str			=						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_inference_func(a_,   a_,   a_	)
   return self._measure_memory(_inference	)


 def 				UpperCamelCase_     (       self:	Tuple,   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



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

   _snake_case							:	Optional[int]			=						self._prepare_train_func(a_,   a_,   a_	)
   return self._measure_memory(_train	)


 def 				UpperCamelCase_     (       self:	Optional[Any],   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						self.config_dict[model_name]

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

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

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

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

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

   _snake_case							:	Optional[int]			=						encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

   return _inference


 def 				UpperCamelCase_     (       self:	Optional[int],   a_:	str,   a_:	int,   a_:	int	):




   '''simple docstring'''



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

   # encoder-decoder has vocab size saved differently
   _snake_case							:	List[Any]			=						config.vocab_size if hasattr(a_,   """vocab_size"""	) else config.encoder.vocab_size
   _snake_case							:	int			=						random_input_ids(a_,   a_,   a_	)

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

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

   _snake_case							:	int			=						encoder_decoder_train if config.is_encoder_decoder else encoder_train

   return _train


 def 				UpperCamelCase_     (       self:	Union[str, Any],   a_:	str	):




   '''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(a_,   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							:	Dict			=						timeit.repeat(
           a_,   repeat=self.args.repeat,   number=10,   )

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


 def 				UpperCamelCase_     (       self:	Optional[Any],   a_:	Callable[[], None]	):




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

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


