




import json
import logging
import math
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

from datasets import Dataset, load_dataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_FOR_MASKED_LM_MAPPING,
    AutoConfig,
    AutoModelForMaskedLM,
    AutoTokenizer,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


UpperCamelCase__    			=			logging.getLogger(__name__)
UpperCamelCase__    			=			list(MODEL_FOR_MASKED_LM_MAPPING.keys())
UpperCamelCase__    			=			tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class 			a__    :
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": (
						            """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."""
						        )
						    } ,				)
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(snake_case__      )} ,				)
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": (
						            """Override some existing default config settings when a model is trained from scratch. Example: """
						            """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"""
						        )
						    } ,				)
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} ,				)
						_a							:    bool					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} ,				)
						_a							:    str					=    field(
						    default="""main""" ,				metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} ,				)
						_a							:    bool					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": (
						            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
						            """with private models)."""
						        )
						    } ,				)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
																raise ValueError(
																    "--config_overrides can't be used in combination with --config_name or --model_name_or_path"			)






@dataclass
class 			a__    :
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}      )
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}      )
						_a							:    Optional[str]					=    field(default=snake_case__ ,				metadata={"""help""": """The input training data file (a text file)."""}      )
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} ,				)
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """An optional input train ref data file for whole word masking in Chinese."""} ,				)
						_a							:    Optional[str]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """An optional input validation ref data file for whole word masking in Chinese."""} ,				)
						_a							:    bool					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Overwrite the cached training and evaluation sets"""}      )
						_a							:    Optional[int]					=    field(
						    default=5 ,				metadata={
						        """help""": """The percentage of the train set used as validation set in case there's no validation split"""
						    } ,				)
						_a							:    Optional[int]					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": (
						            """The maximum total input sequence length after tokenization. Sequences longer """
						            """than this will be truncated. Default to the max input length of the model."""
						        )
						    } ,				)
						_a							:    Optional[int]					=    field(
						    default=snake_case__ ,				metadata={"""help""": """The number of processes to use for the preprocessing."""} ,				)
						_a							:    float					=    field(
						    default=0.15 ,				metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""}      )
						_a							:    bool					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": (
						            """Whether to pad all samples to `max_seq_length`. """
						            """If False, will pad the samples dynamically when batching to the maximum length in the batch."""
						        )
						    } ,				)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											if self.train_file is not None:
																__lowerCAmelCase				   =       self.train_file.split("."			)[-1]
																assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
											if self.validation_file is not None:
																__lowerCAmelCase				   =       self.validation_file.split("."			)[-1]
																assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."







def 	_a      (						SCREAMING_SNAKE_CASE_							:				Union[str, Any]      ,      SCREAMING_SNAKE_CASE_							:				Optional[int]     ):
					with open(SCREAMING_SNAKE_CASE_      ,      "r"      ,      encoding="utf-8"     ) as f:
										__lowerCAmelCase				   =       [json.loads(SCREAMING_SNAKE_CASE_     ) for line in f.read().splitlines() if (len(SCREAMING_SNAKE_CASE_     ) > 0 and not line.isspace())]
					assert len(SCREAMING_SNAKE_CASE_     ) == len(SCREAMING_SNAKE_CASE_     )

					__lowerCAmelCase				   =       {c: dataset[c] for c in dataset.column_names}
					__lowerCAmelCase				   =       refs
					return Dataset.from_dict(SCREAMING_SNAKE_CASE_     )







def 	_a      (						):
					# See all possible arguments in src/transformers/training_args.py
					# or by passing the --help flag to this script.
					# We now keep distinct sets of args, for a cleaner separation of concerns.

					__lowerCAmelCase				   =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
					if len(sys.argv     ) == 2 and sys.argv[1].endswith(".json"     ):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__lowerCAmelCase   ,							__lowerCAmelCase   ,							__lowerCAmelCase				   =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
					else:
										__lowerCAmelCase   ,							__lowerCAmelCase   ,							__lowerCAmelCase				   =       parser.parse_args_into_dataclasses()

					# Detecting last checkpoint.
					__lowerCAmelCase				   =       None
					if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
										__lowerCAmelCase				   =       get_last_checkpoint(training_args.output_dir     )
										if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
															raise ValueError(
															    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
															    "Use --overwrite_output_dir to overcome."     )
										elif last_checkpoint is not None:
															logger.info(
															    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
															    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."     )

    # Setup logging
					logging.basicConfig(
					    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"      ,      datefmt="%m/%d/%Y %H:%M:%S"      ,      handlers=[logging.StreamHandler(sys.stdout     )]      ,      )
					logger.setLevel(logging.INFO if is_main_process(training_args.local_rank     ) else logging.WARN     )

					# Log on each process the small summary:
					logger.warning(
					    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
					    + F"""distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}"""     )
					# Set the verbosity to info of the Transformers logger (on main process only):
					if is_main_process(training_args.local_rank     ):
										transformers.utils.logging.set_verbosity_info()
										transformers.utils.logging.enable_default_handler()
										transformers.utils.logging.enable_explicit_format()
					logger.info("Training/evaluation parameters %s"      ,      SCREAMING_SNAKE_CASE_     )

					# Set seed before initializing model.
					set_seed(training_args.seed     )

					# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
					# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
					# (the dataset will be downloaded automatically from the datasets Hub).
					#
					# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
					# 'text' is found. You can easily tweak this behavior (see below).
					#
					# In distributed training, the load_dataset function guarantee that only one local process can concurrently
					# download the dataset.
					if data_args.dataset_name is not None:
										# Downloading and loading a dataset from the hub.
										__lowerCAmelCase				   =       load_dataset(data_args.dataset_name      ,      data_args.dataset_config_name     )
										if "validation" not in datasets.keys():
															__lowerCAmelCase				   =       load_dataset(
															    data_args.dataset_name      ,      data_args.dataset_config_name      ,      split=F"""train[:{data_args.validation_split_percentage}%]"""      ,      )
															__lowerCAmelCase				   =       load_dataset(
															    data_args.dataset_name      ,      data_args.dataset_config_name      ,      split=F"""train[{data_args.validation_split_percentage}%:]"""      ,      )
					else:
										__lowerCAmelCase				   =       {}
										if data_args.train_file is not None:
															__lowerCAmelCase				   =       data_args.train_file
										if data_args.validation_file is not None:
															__lowerCAmelCase				   =       data_args.validation_file
										__lowerCAmelCase				   =       data_args.train_file.split("."     )[-1]
										if extension == "txt":
															__lowerCAmelCase				   =       "text"
										__lowerCAmelCase				   =       load_dataset(SCREAMING_SNAKE_CASE_      ,      data_files=SCREAMING_SNAKE_CASE_     )
					# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
					# https://huggingface.co/docs/datasets/loading_datasets.html.

					# Load pretrained model and tokenizer
					#
					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.
					__lowerCAmelCase				   =       {
					    "cache_dir": model_args.cache_dir,
					    "revision": model_args.model_revision,
					    "use_auth_token": True if model_args.use_auth_token else None,
					}
					if model_args.config_name:
										__lowerCAmelCase				   =       AutoConfig.from_pretrained(model_args.config_name      ,      **SCREAMING_SNAKE_CASE_     )
					elif model_args.model_name_or_path:
										__lowerCAmelCase				   =       AutoConfig.from_pretrained(model_args.model_name_or_path      ,      **SCREAMING_SNAKE_CASE_     )
					else:
										__lowerCAmelCase				   =       CONFIG_MAPPING[model_args.model_type]()
										logger.warning("You are instantiating a new config instance from scratch."     )
										if model_args.config_overrides is not None:
															logger.info(F"""Overriding config: {model_args.config_overrides}"""     )
															config.update_from_string(model_args.config_overrides     )
															logger.info(F"""New config: {config}"""     )

					__lowerCAmelCase				   =       {
					    "cache_dir": model_args.cache_dir,
					    "use_fast": model_args.use_fast_tokenizer,
					    "revision": model_args.model_revision,
					    "use_auth_token": True if model_args.use_auth_token else None,
					}
					if model_args.tokenizer_name:
										__lowerCAmelCase				   =       AutoTokenizer.from_pretrained(model_args.tokenizer_name      ,      **SCREAMING_SNAKE_CASE_     )
					elif model_args.model_name_or_path:
										__lowerCAmelCase				   =       AutoTokenizer.from_pretrained(model_args.model_name_or_path      ,      **SCREAMING_SNAKE_CASE_     )
					else:
										raise ValueError(
										    "You are instantiating a new tokenizer from scratch. This is not supported by this script."
										    "You can do it from another script, save it, and load it from here, using --tokenizer_name."     )

					if model_args.model_name_or_path:
										__lowerCAmelCase				   =       AutoModelForMaskedLM.from_pretrained(
										    model_args.model_name_or_path      ,      from_tf=bool(".ckpt" in model_args.model_name_or_path     )      ,      config=SCREAMING_SNAKE_CASE_      ,      cache_dir=model_args.cache_dir      ,      revision=model_args.model_revision      ,      use_auth_token=True if model_args.use_auth_token else None      ,      )
					else:
										logger.info("Training new model from scratch"     )
										__lowerCAmelCase				   =       AutoModelForMaskedLM.from_config(SCREAMING_SNAKE_CASE_     )

					model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE_     )     )

					# Preprocessing the datasets.
					# First we tokenize all the texts.
					if training_args.do_train:
										__lowerCAmelCase				   =       datasets["train"].column_names
					else:
										__lowerCAmelCase				   =       datasets["validation"].column_names
					__lowerCAmelCase				   =       "text" if "text" in column_names else column_names[0]

					__lowerCAmelCase				   =       "max_length" if data_args.pad_to_max_length else False

					def tokenize_function(SCREAMING_SNAKE_CASE_							:				Union[str, Any]     ):
										# Remove empty lines
										__lowerCAmelCase				   =       [line for line in examples["text"] if len(SCREAMING_SNAKE_CASE_     ) > 0 and not line.isspace()]
										return tokenizer(examples["text"]      ,      padding=SCREAMING_SNAKE_CASE_      ,      truncation=SCREAMING_SNAKE_CASE_      ,      max_length=data_args.max_seq_length     )

					__lowerCAmelCase				   =       datasets.map(
					    SCREAMING_SNAKE_CASE_      ,      batched=SCREAMING_SNAKE_CASE_      ,      num_proc=data_args.preprocessing_num_workers      ,      remove_columns=[text_column_name]      ,      load_from_cache_file=not data_args.overwrite_cache      ,      )

					# Add the chinese references if provided
					if data_args.train_ref_file is not None:
										__lowerCAmelCase				   =       add_chinese_references(tokenized_datasets["train"]      ,      data_args.train_ref_file     )
					if data_args.validation_ref_file is not None:
										__lowerCAmelCase				   =       add_chinese_references(
										    tokenized_datasets["validation"]      ,      data_args.validation_ref_file     )
					# If we have ref files, need to avoid it removed by trainer
					__lowerCAmelCase				   =       data_args.train_ref_file or data_args.validation_ref_file
					if has_ref:
										__lowerCAmelCase				   =       False

					# Data collator
					# This one will take care of randomly masking the tokens.
					__lowerCAmelCase				   =       DataCollatorForWholeWordMask(tokenizer=SCREAMING_SNAKE_CASE_      ,      mlm_probability=data_args.mlm_probability     )

					# Initialize our Trainer
					__lowerCAmelCase				   =       Trainer(
					    model=SCREAMING_SNAKE_CASE_      ,      args=SCREAMING_SNAKE_CASE_      ,      train_dataset=tokenized_datasets["train"] if training_args.do_train else None      ,      eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None      ,      tokenizer=SCREAMING_SNAKE_CASE_      ,      data_collator=SCREAMING_SNAKE_CASE_      ,      )

					# Training
					if training_args.do_train:
										if last_checkpoint is not None:
															__lowerCAmelCase				   =       last_checkpoint
										elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path     ):
															__lowerCAmelCase				   =       model_args.model_name_or_path
										else:
															__lowerCAmelCase				   =       None
										__lowerCAmelCase				   =       trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_     )
										trainer.save_model()  # Saves the tokenizer too for easy upload

										__lowerCAmelCase				   =       os.path.join(training_args.output_dir      ,      "train_results.txt"     )
										if trainer.is_world_process_zero():
															with open(SCREAMING_SNAKE_CASE_      ,      "w"     ) as writer:
																				logger.info("***** Train results *****"     )
																				for key, value in sorted(train_result.metrics.items()     ):
																									logger.info(F"""  {key} = {value}"""     )
																									writer.write(F"""{key} = {value}\n"""     )

            # Need to save the state, since Trainer.save_model saves only the tokenizer with the model
															trainer.state.save_to_json(os.path.join(training_args.output_dir      ,      "trainer_state.json"     )     )

    # Evaluation
					__lowerCAmelCase				   =       {}
					if training_args.do_eval:
										logger.info("*** Evaluate ***"     )

										__lowerCAmelCase				   =       trainer.evaluate()

										__lowerCAmelCase				   =       math.exp(eval_output["eval_loss"]     )
										__lowerCAmelCase				   =       perplexity

										__lowerCAmelCase				   =       os.path.join(training_args.output_dir      ,      "eval_results_mlm_wwm.txt"     )
										if trainer.is_world_process_zero():
															with open(SCREAMING_SNAKE_CASE_      ,      "w"     ) as writer:
																				logger.info("***** Eval results *****"     )
																				for key, value in sorted(results.items()     ):
																									logger.info(F"""  {key} = {value}"""     )
																									writer.write(F"""{key} = {value}\n"""     )

					return results







def 	_a      (						SCREAMING_SNAKE_CASE_							:				Any     ):
					# For xla_spawn (TPUs)
					main()


if __name__ == "__main__":
					main()








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  SCREAMING_SNAKE_CASE__  :
      def __init__(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Tuple=1_3     ,							SCREAMING_SNAKE_CASE__				:       str=7     ,							SCREAMING_SNAKE_CASE__				:       List[str]=True     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=True     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]=True     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=9_9     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=3_2     ,							SCREAMING_SNAKE_CASE__				:       List[str]=5     ,							SCREAMING_SNAKE_CASE__				:       List[Any]=4     ,							SCREAMING_SNAKE_CASE__				:       Tuple=3_7     ,							SCREAMING_SNAKE_CASE__				:       Any="gelu"     ,							SCREAMING_SNAKE_CASE__				:       Dict=0.1     ,							SCREAMING_SNAKE_CASE__				:       Dict=0.1     ,							SCREAMING_SNAKE_CASE__				:       int=5_1_2     ,							SCREAMING_SNAKE_CASE__				:       int=1_6     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]=2     ,							SCREAMING_SNAKE_CASE__				:       Any=0.02     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]=3     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=4     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]=None     ,							)		->			Any:
             a_					:		Tuple							=  parent
             a_					:		int							=  batch_size
             a_					:		Tuple							=  seq_length
             a_					:		List[Any]							=  is_training
             a_					:		List[str]							=  use_token_type_ids
             a_					:		Dict							=  use_labels
             a_					:		Any							=  vocab_size
             a_					:		List[str]							=  hidden_size
             a_					:		Tuple							=  num_hidden_layers
             a_					:		List[Any]							=  num_attention_heads
             a_					:		Dict							=  intermediate_size
             a_					:		Any							=  hidden_act
             a_					:		List[str]							=  hidden_dropout_prob
             a_					:		Tuple							=  attention_probs_dropout_prob
             a_					:		Optional[Any]							=  max_position_embeddings
             a_					:		List[Any]							=  type_vocab_size
             a_					:		int							=  type_sequence_label_size
             a_					:		List[Any]							=  initializer_range
             a_					:		List[str]							=  num_labels
             a_					:		Union[str, Any]							=  num_choices
             a_					:		str							=  scope
             a_					:		Tuple							=  self.vocab_size - 1
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Any:
             a_					:		Optional[int]							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size     )

             a_					:		Any							=  None
             if self.use_token_type_ids:
                    a_					:		Tuple							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.type_vocab_size     )

             a_					:		List[Any]							=  None
             a_					:		Union[str, Any]							=  None
             a_					:		List[Any]							=  None
             if self.use_labels:
                    a_					:		Tuple							=  ids_tensor([self.batch_size]     ,							self.type_sequence_label_size     )
                    a_					:		Any							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.num_labels     )
                    a_					:		List[Any]							=  ids_tensor([self.batch_size]     ,							self.num_choices     )

             a_					:		Union[str, 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_					:		List[str]							=  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        SCREAMING_SNAKE_CASE							(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       List[str]     ,							*SCREAMING_SNAKE_CASE__				:       Tuple     )		->			Union[str, Any]:
             a_					:		Dict							=  OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		str							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							head_mask=SCREAMING_SNAKE_CASE__     )
             a_					:		Dict							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     )
             a_					:		Dict							=  model(SCREAMING_SNAKE_CASE__     )

             self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							*SCREAMING_SNAKE_CASE__				:       Optional[int]     )		->			Any:
             a_					:		str							=  OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		Optional[int]							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							labels=SCREAMING_SNAKE_CASE__     )
             self.parent.assertEqual(result.loss.shape     ,							()     )
             self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       int     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							*SCREAMING_SNAKE_CASE__				:       Union[str, Any]     )		->			Dict:
             a_					:		int							=  OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		str							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							labels=SCREAMING_SNAKE_CASE__     )
             self.parent.assertEqual(result.loss.shape     ,							()     )
             self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       List[Any]     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							*SCREAMING_SNAKE_CASE__				:       str     )		->			List[str]:
             a_					:		Any							=  self.num_labels
             a_					:		Dict							=  OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

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

      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Tuple:
             a_					:		Optional[Any]							=  self.prepare_config_and_inputs()
             (
                 (
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		
             )					:		Optional[Any]							=  config_and_inputs
             a_					:		Optional[int]							=  {
                 'input_ids': input_ids,
                 'token_type_ids': token_type_ids,
                 'head_mask': head_mask,
             }

             return config, inputs_dict
@require_torch
class  SCREAMING_SNAKE_CASE__  (				lowercase__						,    lowercase__						,    lowercase__						,    unittest.TestCase			):
      snake_case__				:     Tuple        =						(
          (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
          if is_torch_available()
          else ()
      )
      snake_case__				:     List[str]        =						(
          (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
      )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
      snake_case__				:     Dict        =						(
          {
              '''feature-extraction''': OpenAIGPTModel,
              '''text-classification''': OpenAIGPTForSequenceClassification,
              '''text-generation''': OpenAIGPTLMHeadModel,
              '''zero-shot''': OpenAIGPTForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       List[str]     )		->			Dict:
             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        SCREAMING_SNAKE_CASE							(       self				:       int     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Any=False     )		->			List[str]:
             a_					:		str							=  super()._prepare_for_class(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							return_labels=SCREAMING_SNAKE_CASE__     )

             if return_labels:
                    if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                           a_					:		Optional[Any]							=  torch.zeros(
                               (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     ,							)
                           a_					:		str							=  inputs_dict['labels']
                           a_					:		Optional[int]							=  inputs_dict['labels']
                           a_					:		Optional[int]							=  torch.zeros(
                               (self.model_tester.batch_size, self.model_tester.num_choices)     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     ,							)
                           a_					:		Union[str, Any]							=  torch.zeros(
                               self.model_tester.batch_size     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     )
             return inputs_dict
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			List[Any]:
             a_					:		str							=  OpenAIGPTModelTester(self     )
             a_					:		int							=  ConfigTester(self     ,							config_class=SCREAMING_SNAKE_CASE__     ,							n_embd=3_7     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			Tuple:
             self.config_tester.run_common_tests()
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			Tuple:
             a_					:		Dict							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     )		->			Tuple:
             a_					:		Any							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			Optional[Any]:
             a_					:		Optional[int]							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			Optional[Any]:
             a_					:		int							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__     )

      @slow
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			str:
             for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    a_					:		str							=  OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__     )
                    self.assertIsNotNone(SCREAMING_SNAKE_CASE__     )
@require_torch
class  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      @slow
      def        SCREAMING_SNAKE_CASE							(       self				:       Dict     )		->			int:
             a_					:		Dict							=  OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'     )
             model.to(SCREAMING_SNAKE_CASE__     )
             a_					:		List[Any]							=  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     )  # the president is
             a_					:		Tuple							=  [
                 4_8_1,
                 4_7_3_5,
                 5_4_4,
                 2_4_6,
                 9_6_3,
                 8_7_0,
                 7_6_2,
                 2_3_9,
                 2_4_4,
                 4_0_4_7_7,
                 2_4_4,
                 2_4_9,
                 7_1_9,
                 8_8_1,
                 4_8_7,
                 5_4_4,
                 2_4_0,
                 2_4_4,
                 6_0_3,
                 4_8_1,
             ]  # the president is a very good man. " \n " i\'m sure he is, " said the

             a_					:		Dict							=  model.generate(SCREAMING_SNAKE_CASE__     ,							do_sample=SCREAMING_SNAKE_CASE__     )
             self.assertListEqual(output_ids[0].tolist()     ,							SCREAMING_SNAKE_CASE__     )


