


'''simple docstring'''


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
__magic_name__			=      logging.getLogger(__name__)




def      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]							,						lowerCamelCase  :      Any):
      A_						:  List[Any]          =				np.argmax(lowerCamelCase							,						axis=1)
      return np.sum(outputs == labels)




def      lowerCamelCase					(      lowerCamelCase  :      List[str]):
      with open(lowerCamelCase							,						encoding="""utf_8""") as f:
            A_						:  str          =				csv.reader(lowerCamelCase)
            A_						:  Tuple          =				[]
            next(lowerCamelCase)  # skip the first line
            for line in tqdm(lowerCamelCase):
                  output.append((""" """.join(line[1:5]), line[5], line[6], int(line[-1]) - 1))
      return output




def      lowerCamelCase					(      lowerCamelCase  :      Optional[int]							,						lowerCamelCase  :      Dict							,						lowerCamelCase  :      str							,						lowerCamelCase  :      Any							,						lowerCamelCase  :      Optional[Any]							,						lowerCamelCase  :      Dict):
      A_						:  int          =				[]
      for dataset in encoded_datasets:
            A_						:  int          =				len(lowerCamelCase)
            A_						:  Dict          =				np.zeros((n_batch, 2, input_len)							,						dtype=np.intaa)
            A_						:  List[str]          =				np.zeros((n_batch, 2)							,						dtype=np.intaa)
            A_						:  List[str]          =				np.full((n_batch, 2, input_len)							,						fill_value=-100							,						dtype=np.intaa)
            A_						:  Union[str, Any]          =				np.zeros((n_batch,)							,						dtype=np.intaa)
            for (
                i,
                (story, conta, conta, mc_label),
            ) in enumerate(lowerCamelCase):
                  A_						:  List[Any]          =				[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  A_						:  Union[str, Any]          =				[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  A_						:  Dict          =				with_conta
                  A_						:  Dict          =				with_conta
                  A_						:  str          =				len(lowerCamelCase) - 1
                  A_						:  Any          =				len(lowerCamelCase) - 1
                  A_						:  Optional[Any]          =				with_conta
                  A_						:  Dict          =				with_conta
                  A_						:  Optional[Any]          =				mc_label
            A_						:  List[str]          =				(input_ids, mc_token_ids, lm_labels, mc_labels)
            tensor_datasets.append(tuple(torch.tensor(lowerCamelCase) for t in all_inputs))
      return tensor_datasets




def      lowerCamelCase					(      ):
      A_						:  List[Any]          =				argparse.ArgumentParser()
      parser.add_argument("""--model_name"""							,						type=lowerCamelCase							,						default="""openai-gpt"""							,						help="""pretrained model name""")
      parser.add_argument("""--do_train"""							,						action="""store_true"""							,						help="""Whether to run training.""")
      parser.add_argument("""--do_eval"""							,						action="""store_true"""							,						help="""Whether to run eval on the dev set.""")
      parser.add_argument(
          """--output_dir"""							,						default=lowerCamelCase							,						type=lowerCamelCase							,						required=lowerCamelCase							,						help="""The output directory where the model predictions and checkpoints will be written."""							,						)
      parser.add_argument("""--train_dataset"""							,						type=lowerCamelCase							,						default="""""")
      parser.add_argument("""--eval_dataset"""							,						type=lowerCamelCase							,						default="""""")
      parser.add_argument("""--seed"""							,						type=lowerCamelCase							,						default=42)
      parser.add_argument("""--num_train_epochs"""							,						type=lowerCamelCase							,						default=3)
      parser.add_argument("""--train_batch_size"""							,						type=lowerCamelCase							,						default=8)
      parser.add_argument("""--eval_batch_size"""							,						type=lowerCamelCase							,						default=16)
      parser.add_argument("""--adam_epsilon"""							,						default=1E-8							,						type=lowerCamelCase							,						help="""Epsilon for Adam optimizer.""")
      parser.add_argument("""--max_grad_norm"""							,						type=lowerCamelCase							,						default=1)
      parser.add_argument(
          """--max_steps"""							,						default=-1							,						type=lowerCamelCase							,						help=(
              """If > 0: set total number of training                         steps to perform. Override num_train_epochs."""
          )							,						)
      parser.add_argument(
          """--gradient_accumulation_steps"""							,						type=lowerCamelCase							,						default=1							,						help="""Number of updates steps to accumulate before                        performing a backward/update pass."""							,						)
      parser.add_argument("""--learning_rate"""							,						type=lowerCamelCase							,						default=6.25E-5)
      parser.add_argument("""--warmup_steps"""							,						default=0							,						type=lowerCamelCase							,						help="""Linear warmup over warmup_steps.""")
      parser.add_argument("""--lr_schedule"""							,						type=lowerCamelCase							,						default="""warmup_linear""")
      parser.add_argument("""--weight_decay"""							,						type=lowerCamelCase							,						default=0.01)
      parser.add_argument("""--lm_coef"""							,						type=lowerCamelCase							,						default=0.9)
      parser.add_argument("""--n_valid"""							,						type=lowerCamelCase							,						default=374)

      parser.add_argument("""--server_ip"""							,						type=lowerCamelCase							,						default=""""""							,						help="""Can be used for distant debugging.""")
      parser.add_argument("""--server_port"""							,						type=lowerCamelCase							,						default=""""""							,						help="""Can be used for distant debugging.""")
      A_						:  str          =				parser.parse_args()
      print(lowerCamelCase)

      if args.server_ip and args.server_port:
            # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
            import ptvsd

            print("""Waiting for debugger attach""")
            ptvsd.enable_attach(address=(args.server_ip, args.server_port)							,						redirect_output=lowerCamelCase)
            ptvsd.wait_for_attach()

      random.seed(args.seed)
      np.random.seed(args.seed)
      torch.manual_seed(args.seed)
      torch.cuda.manual_seed_all(args.seed)

      A_						:  Optional[int]          =				torch.device("""cuda""" if torch.cuda.is_available() else """cpu""")
      A_						:  List[str]          =				torch.cuda.device_count()
      logger.info("""device: {}, n_gpu {}""".format(lowerCamelCase							,						lowerCamelCase))

      if not args.do_train and not args.do_eval:
            raise ValueError("""At least one of `do_train` or `do_eval` must be True.""")

      if not os.path.exists(args.output_dir):
            os.makedirs(args.output_dir)

      # Load tokenizer and model
      # This loading functions also add new tokens and embeddings called `special tokens`
      # These new embeddings will be fine-tuned on the RocStories dataset
      A_						:  int          =				["""_start_""", """_delimiter_""", """_classify_"""]
      A_						:  Any          =				OpenAIGPTTokenizer.from_pretrained(args.model_name)
      tokenizer.add_tokens(lowerCamelCase)
      A_						:  Optional[int]          =				tokenizer.convert_tokens_to_ids(lowerCamelCase)
      A_						:  List[str]          =				OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name)
      model.resize_token_embeddings(len(lowerCamelCase))
      model.to(lowerCamelCase)

      # Load and encode the datasets
      def tokenize_and_encode(lowerCamelCase  :      List[Any]):
            if isinstance(lowerCamelCase							,						lowerCamelCase):
                  return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(lowerCamelCase))
            elif isinstance(lowerCamelCase							,						lowerCamelCase):
                  return obj
            return [tokenize_and_encode(lowerCamelCase) for o in obj]

      logger.info("""Encoding dataset...""")
      A_						:  Dict          =				load_rocstories_dataset(args.train_dataset)
      A_						:  Optional[Any]          =				load_rocstories_dataset(args.eval_dataset)
      A_						:  Union[str, Any]          =				(train_dataset, eval_dataset)
      A_						:  Optional[int]          =				tokenize_and_encode(lowerCamelCase)

      # Compute the max input length for the Transformer
      A_						:  int          =				model.config.n_positions // 2 - 2
      A_						:  Union[str, Any]          =				max(
          len(story[:max_length]) + max(len(conta[:max_length])							,						len(conta[:max_length])) + 3
          for dataset in encoded_datasets
          for story, conta, conta, _ in dataset)
      A_						:  Tuple          =				min(lowerCamelCase							,						model.config.n_positions)  # Max size of input for the pre-trained model

      # Prepare inputs tensors and dataloaders
      A_						:  Dict          =				pre_process_datasets(lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase							,						*lowerCamelCase)
      A_						:  Optional[Any]          =				tensor_datasets[0], tensor_datasets[1]

      A_						:  List[Any]          =				TensorDataset(*lowerCamelCase)
      A_						:  Tuple          =				RandomSampler(lowerCamelCase)
      A_						:  Any          =				DataLoader(lowerCamelCase							,						sampler=lowerCamelCase							,						batch_size=args.train_batch_size)

      A_						:  List[Any]          =				TensorDataset(*lowerCamelCase)
      A_						:  Tuple          =				SequentialSampler(lowerCamelCase)
      A_						:  int          =				DataLoader(lowerCamelCase							,						sampler=lowerCamelCase							,						batch_size=args.eval_batch_size)

      # Prepare optimizer
      if args.do_train:
            if args.max_steps > 0:
                  A_						:  str          =				args.max_steps
                  A_						:  Union[str, Any]          =				args.max_steps // (len(lowerCamelCase) // args.gradient_accumulation_steps) + 1
            else:
                  A_						:  List[Any]          =				len(lowerCamelCase) // args.gradient_accumulation_steps * args.num_train_epochs

            A_						:  Union[str, Any]          =				list(model.named_parameters())
            A_						:  Optional[Any]          =				["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""]
            A_						:  List[Any]          =				[
                {
                    """params""": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
                    """weight_decay""": args.weight_decay,
                },
                {"""params""": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], """weight_decay""": 0.0},
            ]
            A_						:  Union[str, Any]          =				AdamW(lowerCamelCase							,						lr=args.learning_rate							,						eps=args.adam_epsilon)
            A_						:  Any          =				get_linear_schedule_with_warmup(
                lowerCamelCase							,						num_warmup_steps=args.warmup_steps							,						num_training_steps=lowerCamelCase)

      if args.do_train:
            A_						:  int          =				0, 0, None
            model.train()
            for _ in trange(int(args.num_train_epochs)							,						desc="""Epoch"""):
                  A_						:  List[str]          =				0
                  A_						:  str          =				0
                  A_						:  Union[str, Any]          =				tqdm(lowerCamelCase							,						desc="""Training""")
                  for step, batch in enumerate(lowerCamelCase):
                        A_						:  Any          =				tuple(t.to(lowerCamelCase) for t in batch)
                        A_						:  List[str]          =				batch
                        A_						:  Any          =				model(lowerCamelCase							,						mc_token_ids=lowerCamelCase							,						lm_labels=lowerCamelCase							,						mc_labels=lowerCamelCase)
                        A_						:  Dict          =				args.lm_coef * losses[0] + losses[1]
                        loss.backward()
                        optimizer.step()
                        scheduler.step()
                        optimizer.zero_grad()
                        tr_loss += loss.item()
                        A_						:  Optional[Any]          =				(
                            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                        )
                        nb_tr_steps += 1
                        A_						:  Any          =				"""Training loss: {:.2e} lr: {:.2e}""".format(lowerCamelCase							,						scheduler.get_lr()[0])

    # Save a trained model
      if args.do_train:
            # Save a trained model, configuration and tokenizer
            A_						:  Optional[int]          =				model.module if hasattr(lowerCamelCase							,						"""module""") else model  # Only save the model itself

            # If we save using the predefined names, we can load using `from_pretrained`
            A_						:  Dict          =				os.path.join(args.output_dir							,						lowerCamelCase)
            A_						:  int          =				os.path.join(args.output_dir							,						lowerCamelCase)

            torch.save(model_to_save.state_dict()							,						lowerCamelCase)
            model_to_save.config.to_json_file(lowerCamelCase)
            tokenizer.save_vocabulary(args.output_dir)

            # Load a trained model and vocabulary that you have fine-tuned
            A_						:  List[str]          =				OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir)
            A_						:  Union[str, Any]          =				OpenAIGPTTokenizer.from_pretrained(args.output_dir)
            model.to(lowerCamelCase)

      if args.do_eval:
            model.eval()
            A_						:  Any          =				0, 0
            A_						:  Any          =				0, 0
            for batch in tqdm(lowerCamelCase							,						desc="""Evaluating"""):
                  A_						:  List[Any]          =				tuple(t.to(lowerCamelCase) for t in batch)
                  A_						:  int          =				batch
                  with torch.no_grad():
                        A_						:  Any          =				model(
                            lowerCamelCase							,						mc_token_ids=lowerCamelCase							,						lm_labels=lowerCamelCase							,						mc_labels=lowerCamelCase)

                  A_						:  Tuple          =				mc_logits.detach().cpu().numpy()
                  A_						:  Union[str, Any]          =				mc_labels.to("""cpu""").numpy()
                  A_						:  Dict          =				accuracy(lowerCamelCase							,						lowerCamelCase)

                  eval_loss += mc_loss.mean().item()
                  eval_accuracy += tmp_eval_accuracy

                  nb_eval_examples += input_ids.size(0)
                  nb_eval_steps += 1

            A_						:  Optional[Any]          =				eval_loss / nb_eval_steps
            A_						:  Union[str, Any]          =				eval_accuracy / nb_eval_examples
            A_						:  Tuple          =				tr_loss / nb_tr_steps if args.do_train else None
            A_						:  str          =				{"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss}

            A_						:  Tuple          =				os.path.join(args.output_dir							,						"""eval_results.txt""")
            with open(lowerCamelCase							,						"""w""") as writer:
                  logger.info("""***** Eval results *****""")
                  for key in sorted(result.keys()):
                        logger.info("""  %s = %s"""							,						lowerCamelCase							,						str(result[key]))
                        writer.write("""%s = %s\n""" % (key, str(result[key])))


if __name__ == "__main__":
     main()




'''simple docstring'''


import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
         OpenAIGPTConfig,
         OpenAIGPTDoubleHeadsModel,
         OpenAIGPTForSequenceClassification,
         OpenAIGPTLMHeadModel,
         OpenAIGPTModel,
     )



class 	__lowerCAmelCase		:


  '''simple docstring'''







  def __init__(							self :       Optional[int]	,_a :       List[Any]	,_a :       Dict=13	,_a :       List[Any]=7	,_a :       Optional[Any]=True	,_a :       Any=True	,_a :       Optional[int]=True	,_a :       Union[str, Any]=99	,_a :       Union[str, Any]=32	,_a :       List[str]=5	,_a :       List[str]=4	,_a :       Dict=37	,_a :       List[Any]="gelu"	,_a :       int=0.1	,_a :       Optional[int]=0.1	,_a :       Tuple=512	,_a :       Union[str, Any]=16	,_a :       Optional[Any]=2	,_a :       Optional[Any]=0.02	,_a :       Optional[int]=3	,_a :       str=4	,_a :       Optional[Any]=None	,):

        '''simple docstring'''




        A_						:  Optional[Any]          =				parent
        A_						:  str          =				batch_size
        A_						:  int          =				seq_length
        A_						:  Union[str, Any]          =				is_training
        A_						:  Optional[Any]          =				use_token_type_ids
        A_						:  int          =				use_labels
        A_						:  Dict          =				vocab_size
        A_						:  List[Any]          =				hidden_size
        A_						:  Tuple          =				num_hidden_layers
        A_						:  Optional[int]          =				num_attention_heads
        A_						:  int          =				intermediate_size
        A_						:  Tuple          =				hidden_act
        A_						:  int          =				hidden_dropout_prob
        A_						:  Dict          =				attention_probs_dropout_prob
        A_						:  Any          =				max_position_embeddings
        A_						:  Optional[Any]          =				type_vocab_size
        A_						:  Tuple          =				type_sequence_label_size
        A_						:  int          =				initializer_range
        A_						:  Optional[Any]          =				num_labels
        A_						:  str          =				num_choices
        A_						:  Optional[Any]          =				scope
        A_						:  List[Any]          =				self.vocab_size - 1






  def        _a							(							self :       Any ):

        '''simple docstring'''




        A_						:  List[Any]          =				ids_tensor([self.batch_size, self.seq_length]	,self.vocab_size )

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

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

        A_						:  List[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	,)

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

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






  def        _a							(							self :       Optional[int]	,_a :       List[str]	,_a :       str	,_a :       int	,_a :       int	,*_a :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  Optional[Any]          =				OpenAIGPTModel(config=_a )
        model.to(_a )
        model.eval()

        A_						:  Optional[int]          =				model(_a	,token_type_ids=_a	,head_mask=_a )
        A_						:  str          =				model(_a	,token_type_ids=_a )
        A_						:  Dict          =				model(_a )

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






  def        _a							(							self :       Dict	,_a :       Optional[int]	,_a :       Union[str, Any]	,_a :       Dict	,_a :       List[str]	,*_a :       str ):

        '''simple docstring'''




        A_						:  str          =				OpenAIGPTLMHeadModel(_a )
        model.to(_a )
        model.eval()

        A_						:  Any          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.loss.shape	,() )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.seq_length, self.vocab_size) )






  def        _a							(							self :       Any	,_a :       Dict	,_a :       List[Any]	,_a :       Dict	,_a :       Union[str, Any]	,*_a :       str ):

        '''simple docstring'''




        A_						:  Any          =				OpenAIGPTDoubleHeadsModel(_a )
        model.to(_a )
        model.eval()

        A_						:  Optional[int]          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.loss.shape	,() )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.seq_length, self.vocab_size) )






  def        _a							(							self :       List[str]	,_a :       str	,_a :       Tuple	,_a :       Dict	,_a :       Tuple	,*_a :       Dict ):

        '''simple docstring'''




        A_						:  List[str]          =				self.num_labels
        A_						:  int          =				OpenAIGPTForSequenceClassification(_a )
        model.to(_a )
        model.eval()

        A_						:  Dict          =				ids_tensor([self.batch_size]	,self.type_sequence_label_size )
        A_						:  Optional[Any]          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels) )






  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        A_						:  Union[str, Any]          =				self.prepare_config_and_inputs()
        (
            (
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					
        )						:  str          =				config_and_inputs
        A_						:  int          =				{
            """input_ids""": input_ids,
            """token_type_ids""": token_type_ids,
            """head_mask""": head_mask,
        }

        return config, inputs_dict







@require_torch
class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE  , unittest.TestCase    ):


  '''simple docstring'''







  a_  					=							(
      (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
      if is_torch_available()
      else ()
  )
  a_  					=							(
      (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
  )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
  a_  					=							(
      {
          """feature-extraction""": OpenAIGPTModel,
          """text-classification""": OpenAIGPTForSequenceClassification,
          """text-generation""": OpenAIGPTLMHeadModel,
          """zero-shot""": OpenAIGPTForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )






  def        _a							(							self :       Tuple	,_a :       Optional[int]	,_a :       str	,_a :       List[str]	,_a :       List[str]	,_a :       Any ):

        '''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 :       Optional[int]	,_a :       str	,_a :       Dict	,_a :       Optional[int]=False ):

        '''simple docstring'''




        A_						:  Any          =				super()._prepare_for_class(_a	,_a	,return_labels=_a )

        if return_labels:
              if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                    A_						:  Union[str, Any]          =				torch.zeros(
                        (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)	,dtype=torch.long	,device=_a	,)
                    A_						:  Any          =				inputs_dict["""labels"""]
                    A_						:  Any          =				inputs_dict["""labels"""]
                    A_						:  Tuple          =				torch.zeros(
                        (self.model_tester.batch_size, self.model_tester.num_choices)	,dtype=torch.long	,device=_a	,)
                    A_						:  int          =				torch.zeros(
                        self.model_tester.batch_size	,dtype=torch.long	,device=_a )
        return inputs_dict






  def        _a							(							self :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  Tuple          =				OpenAIGPTModelTester(self )
        A_						:  Optional[int]          =				ConfigTester(self	,config_class=_a	,n_embd=37 )






  def        _a							(							self :       Any ):

        '''simple docstring'''




        self.config_tester.run_common_tests()






  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        A_						:  int          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_model(*_a )






  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        A_						:  Dict          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_lm_head_model(*_a )






  def        _a							(							self :       List[Any] ):

        '''simple docstring'''




        A_						:  str          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_double_lm_head_model(*_a )






  def        _a							(							self :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  List[Any]          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_a )






  @slow
  def        _a							(							self :       List[Any] ):

        '''simple docstring'''




        for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              A_						:  Union[str, Any]          =				OpenAIGPTModel.from_pretrained(_a )
              self.assertIsNotNone(_a )







@require_torch
class 	__lowerCAmelCase		(							unittest.TestCase    ):


  '''simple docstring'''







  @slow
  def        _a							(							self :       List[str] ):

        '''simple docstring'''




        A_						:  Dict          =				OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" )
        model.to(_a )
        A_						:  Dict          =				torch.tensor([[481, 4735, 544]]	,dtype=torch.long	,device=_a )  # the president is
        A_						:  Dict          =				[
            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

        A_						:  int          =				model.generate(_a	,do_sample=_a )
        self.assertListEqual(output_ids[0].tolist()	,_a )
