

"""simple docstring"""
import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
    import torch

    from ..models.auto.modeling_auto import (
        MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
        MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
    )

if is_tf_available() and is_tensorflow_probability_available():
    import tensorflow as tf
    import tensorflow_probability as tfp

    from ..models.auto.modeling_tf_auto import (
        TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
        TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
    )

class 			lowerCamelCase  (					lowerCAmelCase__      ):


  '''simple docstring'''







  def __call__(self       ,					_lowerCamelCase=None       ,					_lowerCamelCase=None       ,					**_lowerCamelCase  ):


        """simple docstring"""

        requires_backends(self       ,					"""pandas"""  )
        import pandas as pd

        if table is None:
              raise ValueError("""Keyword argument `table` cannot be None."""  )
        elif query is None:
              if isinstance(_lowerCamelCase       ,					_lowerCamelCase  ) and table.get("""query"""  ) is not None and table.get("""table"""  ) is not None:
                    UpperCAmelCase__ :       Any						=						[table]
              elif isinstance(_lowerCamelCase       ,					_lowerCamelCase  ) and len(_lowerCamelCase  ) > 0:
                    if not all(isinstance(_lowerCamelCase       ,					_lowerCamelCase  ) for d in table  ):
                          raise ValueError(
                              F"""Keyword argument `table` should be a list of dict, but is {(type(_lowerCamelCase  ) for d in table)}"""  )

                    if table[0].get("""query"""  ) is not None and table[0].get("""table"""  ) is not None:
                          UpperCAmelCase__ :       Dict						=						table
                    else:
                          raise ValueError(
                              """If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"""
                              F""" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."""  )
              elif Dataset is not None and isinstance(_lowerCamelCase       ,					_lowerCamelCase  ) or isinstance(_lowerCamelCase       ,					types.GeneratorType  ):
                    return table
              else:
                    raise ValueError(
                        """Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but """
                        F"""is {type(_lowerCamelCase  )})"""  )
        else:
              UpperCAmelCase__ :       Union[str, Any]						=						[{"""table""": table, """query""": query}]

        for tqa_pipeline_input in tqa_pipeline_inputs:
              if not isinstance(tqa_pipeline_input["""table"""]       ,					pd.DataFrame  ):
                    if tqa_pipeline_input["table"] is None:
                          raise ValueError("""Table cannot be None."""  )

                    UpperCAmelCase__ :       List[str]						=						pd.DataFrame(tqa_pipeline_input["""table"""]  )

        return tqa_pipeline_inputs




@add_end_docstrings(lowerCAmelCase__      )
class 			lowerCamelCase  (					lowerCAmelCase__      ):


  '''simple docstring'''







  SCREAMING_SNAKE_CASE							=     'table,query'



  def __init__(self       ,					_lowerCamelCase=TableQuestionAnsweringArgumentHandler()       ,					*_lowerCamelCase       ,					**_lowerCamelCase  ):


        """simple docstring"""

        super().__init__(*_lowerCamelCase       ,					**_lowerCamelCase  )
        UpperCAmelCase__ :       int						=						args_parser

        self.check_model_type(
            dict(
                TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
                + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()  )
            if self.framework == """tf"""
            else dict(
                MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()  )  )

        UpperCAmelCase__ :       List[Any]						=						bool(getattr(self.model.config       ,					"""aggregation_labels"""       ,					_lowerCamelCase  )  ) and bool(
            getattr(self.model.config       ,					"""num_aggregation_labels"""       ,					_lowerCamelCase  )  )
        UpperCAmelCase__ :       Union[str, Any]						=						"""tapas""" if hasattr(self.model.config       ,					"""aggregation_labels"""  ) else None



  def    _a			(self       ,					**_lowerCamelCase  ):


        """simple docstring"""

        return self.model(**_lowerCamelCase  )



  def    _a			(self       ,					**_lowerCamelCase  ):


        """simple docstring"""

        if self.framework == "pt":
              UpperCAmelCase__ :       Optional[Any]						=						[]
              UpperCAmelCase__ :       Union[str, Any]						=						[]
              UpperCAmelCase__ :       Union[str, Any]						=						None
              UpperCAmelCase__ :       List[str]						=						inputs["""input_ids"""].shape[0]

              UpperCAmelCase__ :       Optional[Any]						=						inputs["""input_ids"""].to(self.device  )
              UpperCAmelCase__ :       List[Any]						=						inputs["""attention_mask"""].to(self.device  )
              UpperCAmelCase__ :       Dict						=						inputs["""token_type_ids"""].to(self.device  )
              UpperCAmelCase__ :       Optional[int]						=						None

              for index in range(_lowerCamelCase  ):
                    # If sequences have already been processed, the token type IDs will be created according to the previous
                    # answer.
                    if prev_answers is not None:
                          UpperCAmelCase__ :       int						=						token_type_ids_example[:, 3]  # shape (seq_len,)
                          UpperCAmelCase__ :       List[str]						=						np.zeros_like(prev_labels_example.cpu().numpy()  )  # shape (seq_len,)

                          UpperCAmelCase__ :       int						=						token_type_ids[index]  # shape (seq_len, 7)
                          for i in range(model_labels.shape[0]  ):
                                UpperCAmelCase__ :       Optional[Any]						=						token_type_ids_example[:, 0].tolist()[i]
                                UpperCAmelCase__ :       Optional[Any]						=						token_type_ids_example[:, 1].tolist()[i] - 1
                                UpperCAmelCase__ :       str						=						token_type_ids_example[:, 2].tolist()[i] - 1

                                if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                      UpperCAmelCase__ :       Optional[int]						=						int(prev_answers[(col_id, row_id)]  )

                          UpperCAmelCase__ :       List[str]						=						torch.from_numpy(_lowerCamelCase  ).type(torch.long  ).to(self.device  )

                    UpperCAmelCase__ :       Optional[int]						=						input_ids[index]
                    UpperCAmelCase__ :       Any						=						attention_mask[index]  # shape (seq_len,)
                    UpperCAmelCase__ :       str						=						token_type_ids[index]  # shape (seq_len, 7)
                    UpperCAmelCase__ :       Any						=						self.model(
                        input_ids=input_ids_example.unsqueeze(0  )       ,					attention_mask=attention_mask_example.unsqueeze(0  )       ,					token_type_ids=token_type_ids_example.unsqueeze(0  )       ,					)
                    UpperCAmelCase__ :       List[str]						=						outputs.logits

                    if self.aggregate:
                          all_aggregations.append(outputs.logits_aggregation  )

                    all_logits.append(_lowerCamelCase  )

                    UpperCAmelCase__ :       List[Any]						=						torch.distributions.Bernoulli(logits=_lowerCamelCase  )
                    UpperCAmelCase__ :       str						=						dist_per_token.probs * attention_mask_example.type(torch.floataa  ).to(
                        dist_per_token.probs.device  )

                    UpperCAmelCase__ :       List[Any]						=						collections.defaultdict(_lowerCamelCase  )
                    for i, p in enumerate(probabilities.squeeze().tolist()  ):
                          UpperCAmelCase__ :       Optional[Any]						=						token_type_ids_example[:, 0].tolist()[i]
                          UpperCAmelCase__ :       Tuple						=						token_type_ids_example[:, 1].tolist()[i] - 1
                          UpperCAmelCase__ :       List[str]						=						token_type_ids_example[:, 2].tolist()[i] - 1
                          if col >= 0 and row >= 0 and segment_id == 1:
                                coords_to_probs[(col, row)].append(_lowerCamelCase  )

                    UpperCAmelCase__ :       int						=						{key: np.array(coords_to_probs[key]  ).mean() > 0.5 for key in coords_to_probs}

              UpperCAmelCase__ :       Optional[Any]						=						torch.cat(tuple(_lowerCamelCase  )       ,					0  )

              return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(_lowerCamelCase  )       ,					0  ))
        else:
              UpperCAmelCase__ :       Optional[int]						=						[]
              UpperCAmelCase__ :       Tuple						=						[]
              UpperCAmelCase__ :       List[str]						=						None
              UpperCAmelCase__ :       Union[str, Any]						=						inputs["""input_ids"""].shape[0]

              UpperCAmelCase__ :       Dict						=						inputs["""input_ids"""]
              UpperCAmelCase__ :       Tuple						=						inputs["""attention_mask"""]
              UpperCAmelCase__ :       Tuple						=						inputs["""token_type_ids"""].numpy()
              UpperCAmelCase__ :       Dict						=						None

              for index in range(_lowerCamelCase  ):
                    # If sequences have already been processed, the token type IDs will be created according to the previous
                    # answer.
                    if prev_answers is not None:
                          UpperCAmelCase__ :       int						=						token_type_ids_example[:, 3]  # shape (seq_len,)
                          UpperCAmelCase__ :       List[Any]						=						np.zeros_like(_lowerCamelCase       ,					dtype=np.intaa  )  # shape (seq_len,)

                          UpperCAmelCase__ :       Tuple						=						token_type_ids[index]  # shape (seq_len, 7)
                          for i in range(model_labels.shape[0]  ):
                                UpperCAmelCase__ :       Dict						=						token_type_ids_example[:, 0].tolist()[i]
                                UpperCAmelCase__ :       Dict						=						token_type_ids_example[:, 1].tolist()[i] - 1
                                UpperCAmelCase__ :       List[str]						=						token_type_ids_example[:, 2].tolist()[i] - 1

                                if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                      UpperCAmelCase__ :       Optional[Any]						=						int(prev_answers[(col_id, row_id)]  )

                          UpperCAmelCase__ :       Dict						=						model_labels

                    UpperCAmelCase__ :       int						=						input_ids[index]
                    UpperCAmelCase__ :       int						=						attention_mask[index]  # shape (seq_len,)
                    UpperCAmelCase__ :       Any						=						token_type_ids[index]  # shape (seq_len, 7)
                    UpperCAmelCase__ :       Optional[int]						=						self.model(
                        input_ids=np.expand_dims(_lowerCamelCase       ,					axis=0  )       ,					attention_mask=np.expand_dims(_lowerCamelCase       ,					axis=0  )       ,					token_type_ids=np.expand_dims(_lowerCamelCase       ,					axis=0  )       ,					)
                    UpperCAmelCase__ :       Dict						=						outputs.logits

                    if self.aggregate:
                          all_aggregations.append(outputs.logits_aggregation  )

                    all_logits.append(_lowerCamelCase  )

                    UpperCAmelCase__ :       List[str]						=						tfp.distributions.Bernoulli(logits=_lowerCamelCase  )
                    UpperCAmelCase__ :       Dict						=						dist_per_token.probs_parameter() * tf.cast(_lowerCamelCase       ,					tf.floataa  )

                    UpperCAmelCase__ :       int						=						collections.defaultdict(_lowerCamelCase  )
                    UpperCAmelCase__ :       List[Any]						=						token_type_ids_example
                    for i, p in enumerate(tf.squeeze(_lowerCamelCase  ).numpy().tolist()  ):
                          UpperCAmelCase__ :       Optional[int]						=						token_type_ids_example[:, 0].tolist()[i]
                          UpperCAmelCase__ :       Dict						=						token_type_ids_example[:, 1].tolist()[i] - 1
                          UpperCAmelCase__ :       str						=						token_type_ids_example[:, 2].tolist()[i] - 1
                          if col >= 0 and row >= 0 and segment_id == 1:
                                coords_to_probs[(col, row)].append(_lowerCamelCase  )

                    UpperCAmelCase__ :       Dict						=						{key: np.array(coords_to_probs[key]  ).mean() > 0.5 for key in coords_to_probs}

              UpperCAmelCase__ :       Tuple						=						tf.concat(tuple(_lowerCamelCase  )       ,					0  )

              return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(_lowerCamelCase  )       ,					0  ))



  def __call__(self       ,					*_lowerCamelCase       ,					**_lowerCamelCase  ):


        """simple docstring"""

        UpperCAmelCase__ :       str						=						self._args_parser(*_lowerCamelCase       ,					**_lowerCamelCase  )

        UpperCAmelCase__ :       Any						=						super().__call__(_lowerCamelCase       ,					**_lowerCamelCase  )
        if len(_lowerCamelCase  ) == 1:
              return results[0]
        return results



  def    _a			(self       ,					_lowerCamelCase=None       ,					_lowerCamelCase=None       ,					_lowerCamelCase=None       ,					**_lowerCamelCase  ):


        """simple docstring"""

        UpperCAmelCase__ :       Optional[Any]						=						{}
        if padding is not None:
              UpperCAmelCase__ :       Optional[Any]						=						padding
        if truncation is not None:
              UpperCAmelCase__ :       Optional[Any]						=						truncation

        UpperCAmelCase__ :       List[str]						=						{}
        if sequential is not None:
              UpperCAmelCase__ :       str						=						sequential
        return preprocess_params, forward_params, {}



  def    _a			(self       ,					_lowerCamelCase       ,					_lowerCamelCase=None       ,					_lowerCamelCase=True       ,					_lowerCamelCase=None  ):


        """simple docstring"""

        if truncation is None:
              if self.type == "tapas":
                    UpperCAmelCase__ :       Dict						=						"""drop_rows_to_fit"""
              else:
                    UpperCAmelCase__ :       Optional[int]						=						"""do_not_truncate"""

        UpperCAmelCase__				,		UpperCAmelCase__ :       Optional[int]						=						pipeline_input["""table"""], pipeline_input["""query"""]
        if table.empty:
              raise ValueError("""table is empty"""  )
        if query is None or query == "":
              raise ValueError("""query is empty"""  )
        UpperCAmelCase__ :       Optional[Any]						=						self.tokenizer(_lowerCamelCase       ,					_lowerCamelCase       ,					return_tensors=self.framework       ,					truncation=_lowerCamelCase       ,					padding=_lowerCamelCase  )
        UpperCAmelCase__ :       Optional[int]						=						table
        return inputs



  def    _a			(self       ,					_lowerCamelCase       ,					_lowerCamelCase=False  ):


        """simple docstring"""

        UpperCAmelCase__ :       Tuple						=						model_inputs.pop("""table"""  )

        if self.type == "tapas":
              if sequential:
                    UpperCAmelCase__ :       Dict						=						self.sequential_inference(**_lowerCamelCase  )
              else:
                    UpperCAmelCase__ :       Tuple						=						self.batch_inference(**_lowerCamelCase  )
        else:
              UpperCAmelCase__ :       Optional[Any]						=						self.model.generate(**_lowerCamelCase  )
        UpperCAmelCase__ :       int						=						{"""model_inputs""": model_inputs, """table""": table, """outputs""": outputs}
        return model_outputs




  def    _a			(self       ,					_lowerCamelCase  ):


        """simple docstring"""

        UpperCAmelCase__ :       str						=						model_outputs["""model_inputs"""]
        UpperCAmelCase__ :       Optional[Any]						=						model_outputs["""table"""]
        UpperCAmelCase__ :       Any						=						model_outputs["""outputs"""]
        if self.type == "tapas":
              if self.aggregate:
                    UpperCAmelCase__				,		UpperCAmelCase__ :       Optional[Any]						=						outputs[:2]
                    UpperCAmelCase__ :       List[str]						=						self.tokenizer.convert_logits_to_predictions(_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase  )
                    UpperCAmelCase__				,		UpperCAmelCase__ :       Optional[int]						=						predictions
                    UpperCAmelCase__ :       int						=						{i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(_lowerCamelCase  )}

                    UpperCAmelCase__ :       Tuple						=						self.model.config.no_aggregation_label_index
                    UpperCAmelCase__ :       Tuple						=						{
                        i: aggregators[i] + """ > """ for i, pred in enumerate(_lowerCamelCase  ) if pred != no_agg_label_index
                    }
              else:
                    UpperCAmelCase__ :       int						=						outputs[0]
                    UpperCAmelCase__ :       Optional[int]						=						self.tokenizer.convert_logits_to_predictions(_lowerCamelCase       ,					_lowerCamelCase  )
                    UpperCAmelCase__ :       int						=						predictions[0]
                    UpperCAmelCase__ :       Dict						=						{}
                    UpperCAmelCase__ :       Dict						=						{}
              UpperCAmelCase__ :       Dict						=						[]
              for index, coordinates in enumerate(_lowerCamelCase  ):
                    UpperCAmelCase__ :       Any						=						[table.iat[coordinate] for coordinate in coordinates]
                    UpperCAmelCase__ :       Optional[Any]						=						aggregators.get(_lowerCamelCase       ,					""""""  )
                    UpperCAmelCase__ :       Union[str, Any]						=						aggregators_prefix.get(_lowerCamelCase       ,					""""""  )
                    UpperCAmelCase__ :       Any						=						{
                        """answer""": aggregator_prefix + """, """.join(_lowerCamelCase  ),
                        """coordinates""": coordinates,
                        """cells""": [table.iat[coordinate] for coordinate in coordinates],
                    }
                    if aggregator:
                          UpperCAmelCase__ :       int						=						aggregator

                    answers.append(_lowerCamelCase  )
              if len(_lowerCamelCase  ) == 0:
                    raise PipelineException("""Empty answer"""  )
        else:
              UpperCAmelCase__ :       Optional[int]						=						[{"""answer""": answer} for answer in self.tokenizer.batch_decode(_lowerCamelCase       ,					skip_special_tokens=_lowerCamelCase  )]

        return answers if len(_lowerCamelCase  ) > 1 else answers[0]




"""simple docstring"""
import argparse
import time

import torch
import transformers
from measures_util import end_measure, log_measures, start_measure
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoTokenizer

from accelerate.utils import compute_module_sizes


_A						=     {
    """gpt-j-6b""": {"""is_causal""": True, """model""": """sgugger/sharded-gpt-j-6B""", """tokenizer""": """EleutherAI/gpt-j-6B"""},
    """gpt-neox""": {"""is_causal""": True, """model""": """EleutherAI/gpt-neox-20b"""},
    """opt""": {"""is_causal""": True, """model""": """facebook/opt-30b"""},
    """T0pp""": {"""is_causal""": False, """model""": """bigscience/T0pp""", """model_revision""": """sharded"""},
}

_A						=     [
    """Hello, my name is""",
    """Are unicorns real? Unicorns are""",
    """For the first time in several years,""",
    """My name is Julien and I am""",
    """The goal of life is""",
    """Whenever I'm sad, I like to""",
]




def 				a__	(	)  ->   Optional[Any]:
      UpperCAmelCase__ :       int						=						argparse.ArgumentParser(description="""Run and time generations on a big model using Accelerate."""						)
      parser.add_argument("""model_name""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The name of the model to try."""						)
      parser.add_argument(
          """--tokenizer_name""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The name of the tokenizer (if different from the model."""						)
      parser.add_argument("""--is_causal""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""Whether or not the model is causal."""						)
      parser.add_argument(
          """--model_revision""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The revision to use for the model checkpoint."""						)
      parser.add_argument("""--torch_dtype""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The dtype for the model."""						)
      parser.add_argument("""--disk_offload""" ,  action="""store_true"""						)

      UpperCAmelCase__ :       Union[str, Any]						=						parser.parse_args()

      # Sanitize args
      if args.model_name in DEFAULT_MODELS:
            UpperCAmelCase__ :       Any						=						DEFAULT_MODELS[args.model_name]
            UpperCAmelCase__ :       Tuple						=						defaults["""model"""]
            if args.tokenizer_name is None:
                  UpperCAmelCase__ :       Optional[Any]						=						defaults.get("""tokenizer""" ,  args.model_name						)
            if args.is_causal is None:
                  UpperCAmelCase__ :       List[Any]						=						defaults["""is_causal"""]
            if args.model_revision is None:
                  UpperCAmelCase__ :       Optional[int]						=						defaults.get("""model_revision""" ,  """main"""						)

      if args.is_causal is None:
            raise ValueError("""Could not infer the default for `--is_causal`, pass either True or False for it."""						)
      if args.tokenizer_name is None:
            UpperCAmelCase__ :       str						=						args.model_name
      if args.model_revision is None:
            UpperCAmelCase__ :       List[str]						=						"""main"""

      return args




def 				a__	(	)  ->   List[Any]:
      transformers.utils.logging.set_verbosity_error()
      UpperCAmelCase__ :       Optional[int]						=						parse_args()

      if args.torch_dtype is None:
            UpperCAmelCase__ :       List[str]						=						AutoConfig.from_pretrained(args.model_name						)
            UpperCAmelCase__ :       Optional[Any]						=						getattr(lowerCAmelCase ,  """torch_dtype""" ,  torch.floataa						)
      else:
            UpperCAmelCase__ :       Union[str, Any]						=						getattr(lowerCAmelCase ,  args.torch_dtype						)
      UpperCAmelCase__ :       List[Any]						=						AutoModelForCausalLM if args.is_causal else AutoModelForSeqaSeqLM
      UpperCAmelCase__ :       List[str]						=						{
          """torch_dtype""": torch_dtype,
          """revision""": args.model_revision,
      }
      if args.disk_offload:
            UpperCAmelCase__ :       List[str]						=						"""tmp_offload"""
            UpperCAmelCase__ :       int						=						True

      UpperCAmelCase__ :       Any						=						start_measure()
      UpperCAmelCase__ :       Optional[int]						=						model_cls.from_pretrained(args.model_name ,  device_map="""auto""" ,  **lowerCAmelCase						)
      UpperCAmelCase__ :       Any						=						end_measure(lowerCAmelCase						)
      log_measures(lowerCAmelCase ,  """Model loading"""						)

      UpperCAmelCase__ :       List[str]						=						compute_module_sizes(lowerCAmelCase						)
      UpperCAmelCase__ :       Dict						=						{v: 0 for v in model.hf_device_map.values()}
      for module, device in model.hf_device_map.items():
            device_size[device] += module_sizes[module]
      UpperCAmelCase__ :       Optional[Any]						=						"""\n""".join([F"""- {device}: {size // 2**20}MiB""" for device, size in device_size.items()]						)
      print(F"""\nTheoretical use:\n{message}"""						)

      UpperCAmelCase__ :       Tuple						=						AutoTokenizer.from_pretrained(args.tokenizer_name						)

      UpperCAmelCase__ :       List[str]						=						start_measure()
      UpperCAmelCase__ :       List[Any]						=						[]
      UpperCAmelCase__ :       Tuple						=						[]
      UpperCAmelCase__ :       Optional[Any]						=						[]
      for prompt in PROMPTS:
            UpperCAmelCase__ :       Any						=						tokenizer(lowerCAmelCase ,  return_tensors="""pt"""						).to(0						)
            UpperCAmelCase__ :       List[str]						=						inputs["""input_ids"""][0].tolist()
            UpperCAmelCase__ :       Dict						=						time.time()
            UpperCAmelCase__ :       List[str]						=						model.generate(inputs["""input_ids"""]						)
            UpperCAmelCase__ :       str						=						time.time()
            UpperCAmelCase__ :       str						=						outputs[0].tolist()
            UpperCAmelCase__ :       Optional[Any]						=						len(lowerCAmelCase						) if outputs[: len(lowerCAmelCase						)] != tokens else len(lowerCAmelCase						) - len(lowerCAmelCase						)
            UpperCAmelCase__ :       Tuple						=						after_generate - before_generate

            UpperCAmelCase__ :       Optional[Any]						=						tokenizer.decode(lowerCAmelCase ,  skip_special_tokens=lowerCAmelCase						)
            texts_outs.append(lowerCAmelCase						)
            generation_times.append(lowerCAmelCase						)
            gen_tokens.append(lowerCAmelCase						)
            print(F"""Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n"""						)

      UpperCAmelCase__ :       int						=						end_measure(lowerCAmelCase						)
      log_measures(lowerCAmelCase ,  """Model generation"""						)

      UpperCAmelCase__ :       Any						=						[gen / tok for gen, tok in zip(lowerCAmelCase ,  lowerCAmelCase						)]
      UpperCAmelCase__ :       List[Any]						=						sum(lowerCAmelCase						) / len(lowerCAmelCase						)
      print(F"""Average time of generation per token: {avg_gen:.2f}s"""						)
      print(F"""First generation (avg time per token): {generation_times_per_token[0]:.2f}s"""						)
      UpperCAmelCase__ :       Any						=						sum(generation_times_per_token[1:]						) / (len(lowerCAmelCase						) - 1)
      print(F"""Average time of generation per token (excluding the first): {avg_gen:.2f}s"""						)


if __name__ == "__main__":
    main()

