

from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.openai.modeling_tf_openai import (
        TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFOpenAIGPTDoubleHeadsModel,
        TFOpenAIGPTForSequenceClassification,
        TFOpenAIGPTLMHeadModel,
        TFOpenAIGPTModel,
    )

class 			lowerCamelCase  :


  '''simple docstring'''







  def __init__(self       ,					_lowerCamelCase       ,					):


        """simple docstring"""

        UpperCAmelCase__ :       List[Any]						=						parent
        UpperCAmelCase__ :       Dict						=						13
        UpperCAmelCase__ :       Dict						=						7
        UpperCAmelCase__ :       Dict						=						True
        UpperCAmelCase__ :       List[Any]						=						True
        UpperCAmelCase__ :       str						=						True
        UpperCAmelCase__ :       Union[str, Any]						=						True
        UpperCAmelCase__ :       Optional[Any]						=						True
        UpperCAmelCase__ :       Union[str, Any]						=						99
        UpperCAmelCase__ :       Any						=						32
        UpperCAmelCase__ :       Union[str, Any]						=						2
        UpperCAmelCase__ :       Union[str, Any]						=						4
        UpperCAmelCase__ :       str						=						37
        UpperCAmelCase__ :       int						=						"""gelu"""
        UpperCAmelCase__ :       Optional[Any]						=						0.1
        UpperCAmelCase__ :       List[Any]						=						0.1
        UpperCAmelCase__ :       List[str]						=						512
        UpperCAmelCase__ :       Optional[Any]						=						16
        UpperCAmelCase__ :       str						=						2
        UpperCAmelCase__ :       List[str]						=						0.02
        UpperCAmelCase__ :       Any						=						3
        UpperCAmelCase__ :       str						=						4
        UpperCAmelCase__ :       Any						=						None
        UpperCAmelCase__ :       Any						=						self.vocab_size - 1



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       List[str]						=						ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size  )

        UpperCAmelCase__ :       Tuple						=						None
        if self.use_input_mask:
              UpperCAmelCase__ :       List[str]						=						random_attention_mask([self.batch_size, self.seq_length]  )

        UpperCAmelCase__ :       Optional[int]						=						None
        if self.use_token_type_ids:
              UpperCAmelCase__ :       int						=						ids_tensor([self.batch_size, self.seq_length]       ,					self.type_vocab_size  )

        UpperCAmelCase__ :       int						=						None
        if self.use_mc_token_ids:
              UpperCAmelCase__ :       int						=						ids_tensor([self.batch_size, self.num_choices]       ,					self.seq_length  )

        UpperCAmelCase__ :       str						=						None
        UpperCAmelCase__ :       Dict						=						None
        UpperCAmelCase__ :       Optional[Any]						=						None
        if self.use_labels:
              UpperCAmelCase__ :       Union[str, Any]						=						ids_tensor([self.batch_size]       ,					self.type_sequence_label_size  )
              UpperCAmelCase__ :       Dict						=						ids_tensor([self.batch_size, self.seq_length]       ,					self.num_labels  )
              UpperCAmelCase__ :       str						=						ids_tensor([self.batch_size]       ,					self.num_choices  )

        UpperCAmelCase__ :       Any						=						OpenAIGPTConfig(
            vocab_size=self.vocab_size       ,					n_embd=self.hidden_size       ,					n_layer=self.num_hidden_layers       ,					n_head=self.num_attention_heads       ,					n_positions=self.max_position_embeddings       ,					pad_token_id=self.pad_token_id       ,					)

        UpperCAmelCase__ :       Tuple						=						ids_tensor([self.num_hidden_layers, self.num_attention_heads]       ,					2  )

        return (
            config,
            input_ids,
            input_mask,
            head_mask,
            token_type_ids,
            mc_token_ids,
            sequence_labels,
            token_labels,
            choice_labels,
        )



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


        """simple docstring"""

        UpperCAmelCase__ :       Any						=						TFOpenAIGPTModel(config=_lowerCamelCase  )
        UpperCAmelCase__ :       Any						=						{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
        UpperCAmelCase__ :       Optional[int]						=						model(_lowerCamelCase  )

        UpperCAmelCase__ :       List[str]						=						[input_ids, input_mask]
        UpperCAmelCase__ :       Dict						=						model(_lowerCamelCase  )

        UpperCAmelCase__ :       List[str]						=						model(_lowerCamelCase  )

        self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size)  )



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


        """simple docstring"""

        UpperCAmelCase__ :       Union[str, Any]						=						TFOpenAIGPTLMHeadModel(config=_lowerCamelCase  )
        UpperCAmelCase__ :       Tuple						=						{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
        UpperCAmelCase__ :       str						=						model(_lowerCamelCase  )
        self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.seq_length, self.vocab_size)  )



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


        """simple docstring"""

        UpperCAmelCase__ :       int						=						TFOpenAIGPTDoubleHeadsModel(config=_lowerCamelCase  )

        UpperCAmelCase__ :       Optional[Any]						=						tf.tile(tf.expand_dims(_lowerCamelCase       ,					1  )       ,					(1, self.num_choices, 1)  )
        UpperCAmelCase__ :       Any						=						tf.tile(tf.expand_dims(_lowerCamelCase       ,					1  )       ,					(1, self.num_choices, 1)  )
        UpperCAmelCase__ :       Any						=						tf.tile(tf.expand_dims(_lowerCamelCase       ,					1  )       ,					(1, self.num_choices, 1)  )

        UpperCAmelCase__ :       List[Any]						=						{
            """input_ids""": multiple_choice_inputs_ids,
            """mc_token_ids""": mc_token_ids,
            """attention_mask""": multiple_choice_input_mask,
            """token_type_ids""": multiple_choice_token_type_ids,
        }
        UpperCAmelCase__ :       int						=						model(_lowerCamelCase  )
        self.parent.assertEqual(
            result.logits.shape       ,					(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)  )
        self.parent.assertEqual(result.mc_logits.shape       ,					(self.batch_size, self.num_choices)  )



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


        """simple docstring"""

        UpperCAmelCase__ :       List[Any]						=						self.num_labels
        UpperCAmelCase__ :       int						=						ids_tensor([self.batch_size]       ,					self.type_sequence_label_size  )
        UpperCAmelCase__ :       Any						=						{
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
            """labels""": sequence_labels,
        }
        UpperCAmelCase__ :       Tuple						=						TFOpenAIGPTForSequenceClassification(_lowerCamelCase  )
        UpperCAmelCase__ :       Union[str, Any]						=						model(_lowerCamelCase  )
        self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)  )




  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       int						=						self.prepare_config_and_inputs()

        (
            UpperCAmelCase__		
        ) :       Optional[Any]						=						config_and_inputs

        UpperCAmelCase__ :       Tuple						=						{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
        return config, inputs_dict




@require_tf
class 			lowerCamelCase  (					lowerCAmelCase__				,				lowerCAmelCase__				,				unittest.TestCase      ):


  '''simple docstring'''







  SCREAMING_SNAKE_CASE							=     (
      (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
      if is_tf_available()
      else ()
  )
  SCREAMING_SNAKE_CASE							=     (
      (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
  )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
  SCREAMING_SNAKE_CASE							=     (
      {
          'feature-extraction': TFOpenAIGPTModel,
          'text-classification': TFOpenAIGPTForSequenceClassification,
          'text-generation': TFOpenAIGPTLMHeadModel,
          'zero-shot': TFOpenAIGPTForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  SCREAMING_SNAKE_CASE							=     False
  SCREAMING_SNAKE_CASE							=     False



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


        """simple docstring"""

        if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
              # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
              # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
              # tiny config could not be created.
              return True

        return False



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       List[str]						=						TFOpenAIGPTModelTester(self  )
        UpperCAmelCase__ :       Optional[int]						=						ConfigTester(self       ,					config_class=_lowerCamelCase       ,					n_embd=37  )



  def    _a			(self  ):


        """simple docstring"""

        self.config_tester.run_common_tests()



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Tuple						=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_model(*_lowerCamelCase  )



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Union[str, Any]						=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_lm_head(*_lowerCamelCase  )



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Dict						=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_double_head(*_lowerCamelCase  )



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Optional[int]						=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_lowerCamelCase  )




  @slow
  def    _a			(self  ):


        """simple docstring"""

        for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__ :       int						=						TFOpenAIGPTModel.from_pretrained(_lowerCamelCase  )
              self.assertIsNotNone(_lowerCamelCase  )




@require_tf
class 			lowerCamelCase  (					unittest.TestCase      ):


  '''simple docstring'''







  @slow
  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       int						=						TFOpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""  )
        UpperCAmelCase__ :       Optional[int]						=						tf.convert_to_tensor([[481, 4735, 544]]       ,					dtype=tf.intaa  )  # the president is
        UpperCAmelCase__ :       Union[str, Any]						=						[
            481,
            4735,
            544,
            246,
            963,
            870,
            762,
            239,
            244,
            40477,
            244,
            249,
            719,
            881,
            487,
            544,
            240,
            244,
            603,
            481,
        ]  # the president is a very good man. " \n " i\'m sure he is, " said the

        UpperCAmelCase__ :       Any						=						model.generate(_lowerCamelCase       ,					do_sample=_lowerCamelCase  )
        self.assertListEqual(output_ids[0].numpy().tolist()       ,					_lowerCamelCase  )




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

