





import os
import tempfile
import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
					    DistilBertForMaskedLM,
					    DistilBertForMultipleChoice,
					    DistilBertForQuestionAnswering,
					    DistilBertForSequenceClassification,
					    DistilBertForTokenClassification,
					    DistilBertModel,
					)


class   A			(SCREAMING_SNAKE_CASE    ):
			'''simple docstring'''




			def __init__(			self   :    Dict							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Optional[Any]=13							,	__lowerCAmelCase   :    Any=7							,	__lowerCAmelCase   :    Dict=True							,	__lowerCAmelCase   :    Any=True							,	__lowerCAmelCase   :    str=False							,	__lowerCAmelCase   :    Dict=True							,	__lowerCAmelCase   :    List[Any]=99							,	__lowerCAmelCase   :    Optional[int]=32							,	__lowerCAmelCase   :    int=5							,	__lowerCAmelCase   :    Optional[Any]=4							,	__lowerCAmelCase   :    List[str]=37							,	__lowerCAmelCase   :    Any="gelu"							,	__lowerCAmelCase   :    Tuple=0.1							,	__lowerCAmelCase   :    Optional[Any]=0.1							,	__lowerCAmelCase   :    Optional[int]=5_12							,	__lowerCAmelCase   :    List[str]=16							,	__lowerCAmelCase   :    Tuple=2							,	__lowerCAmelCase   :    Tuple=0.0_2							,	__lowerCAmelCase   :    str=3							,	__lowerCAmelCase   :    Dict=4							,	__lowerCAmelCase   :    str=None							,	)	->	Any:







					"""simple docstring"""






					A__        =   parent
					A__        =   batch_size
					A__        =   seq_length
					A__        =   is_training
					A__        =   use_input_mask
					A__        =   use_token_type_ids
					A__        =   use_labels
					A__        =   vocab_size
					A__        =   hidden_size
					A__        =   num_hidden_layers
					A__        =   num_attention_heads
					A__        =   intermediate_size
					A__        =   hidden_act
					A__        =   hidden_dropout_prob
					A__        =   attention_probs_dropout_prob
					A__        =   max_position_embeddings
					A__        =   type_vocab_size
					A__        =   type_sequence_label_size
					A__        =   initializer_range
					A__        =   num_labels
					A__        =   num_choices
					A__        =   scope






			def    a_       (			self   :    int   )	->	Tuple:







					"""simple docstring"""






					A__        =   ids_tensor([self.batch_size, self.seq_length]							,	self.vocab_size   )

					A__        =   None
					if self.use_input_mask:
							A__        =   random_attention_mask([self.batch_size, self.seq_length]   )

					A__        =   None
					A__        =   None
					A__        =   None
					if self.use_labels:
							A__        =   ids_tensor([self.batch_size]							,	self.type_sequence_label_size   )
							A__        =   ids_tensor([self.batch_size, self.seq_length]							,	self.num_labels   )
							A__        =   ids_tensor([self.batch_size]							,	self.num_choices   )

					A__        =   self.get_config()

					return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






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







					"""simple docstring"""






					return DistilBertConfig(
					    vocab_size=self.vocab_size							,	dim=self.hidden_size							,	n_layers=self.num_hidden_layers							,	n_heads=self.num_attention_heads							,	hidden_dim=self.intermediate_size							,	hidden_act=self.hidden_act							,	dropout=self.hidden_dropout_prob							,	attention_dropout=self.attention_probs_dropout_prob							,	max_position_embeddings=self.max_position_embeddings							,	initializer_range=self.initializer_range							,	)






			def    a_       (			self   :    Union[str, Any]							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Dict							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    List[str]							,	__lowerCAmelCase   :    str							,	__lowerCAmelCase   :    List[Any]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   DistilBertModel(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase							,	__lowerCAmelCase   )
					A__        =   model(__lowerCAmelCase   )
					self.parent.assertEqual(result.last_hidden_state.shape							,	(self.batch_size, self.seq_length, self.hidden_size)   )






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    str							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    Optional[int]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   DistilBertForMaskedLM(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase							,	attention_mask=__lowerCAmelCase							,	labels=__lowerCAmelCase   )
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.seq_length, self.vocab_size)   )






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Optional[Any]							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Tuple   )	->	List[Any]:







					"""simple docstring"""






					A__        =   DistilBertForQuestionAnswering(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(
					    __lowerCAmelCase							,	attention_mask=__lowerCAmelCase							,	start_positions=__lowerCAmelCase							,	end_positions=__lowerCAmelCase   )
					self.parent.assertEqual(result.start_logits.shape							,	(self.batch_size, self.seq_length)   )
					self.parent.assertEqual(result.end_logits.shape							,	(self.batch_size, self.seq_length)   )






			def    a_       (			self   :    Dict							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    List[Any]							,	__lowerCAmelCase   :    List[Any]							,	__lowerCAmelCase   :    Dict							,	__lowerCAmelCase   :    List[str]							,	__lowerCAmelCase   :    List[str]   )	->	Any:







					"""simple docstring"""






					A__        =   self.num_labels
					A__        =   DistilBertForSequenceClassification(__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase							,	attention_mask=__lowerCAmelCase							,	labels=__lowerCAmelCase   )
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_labels)   )






			def    a_       (			self   :    Union[str, Any]							,	__lowerCAmelCase   :    List[str]							,	__lowerCAmelCase   :    Optional[int]							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Optional[int]   )	->	Dict:







					"""simple docstring"""






					A__        =   self.num_labels
					A__        =   DistilBertForTokenClassification(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()

					A__        =   model(__lowerCAmelCase							,	attention_mask=__lowerCAmelCase							,	labels=__lowerCAmelCase   )
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.seq_length, self.num_labels)   )






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    Dict							,	__lowerCAmelCase   :    Optional[Any]							,	__lowerCAmelCase   :    Dict							,	__lowerCAmelCase   :    Any							,	__lowerCAmelCase   :    List[Any]							,	__lowerCAmelCase   :    List[Any]   )	->	List[str]:







					"""simple docstring"""






					A__        =   self.num_choices
					A__        =   DistilBertForMultipleChoice(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   input_ids.unsqueeze(1   ).expand(-1							,	self.num_choices							,	-1   ).contiguous()
					A__        =   input_mask.unsqueeze(1   ).expand(-1							,	self.num_choices							,	-1   ).contiguous()
					A__        =   model(
					    __lowerCAmelCase							,	attention_mask=__lowerCAmelCase							,	labels=__lowerCAmelCase							,	)
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_choices)   )







			def    a_       (			self   :    List[Any]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   self.prepare_config_and_inputs()
					((A__)      ,			(A__)      ,			(A__)      ,			(A__)      ,			(A__)      ,			(A__))        =   config_and_inputs
					A__        =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
					return config, inputs_dict


@require_torch
class   A			(SCREAMING_SNAKE_CASE   ,     SCREAMING_SNAKE_CASE   ,     unittest.TestCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       Optional[int]							=    (
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			__lowerCamelCase	:       Tuple							=    (
			    {
			        '''feature-extraction''': DistilBertModel,
			        '''fill-mask''': DistilBertForMaskedLM,
			        '''question-answering''': DistilBertForQuestionAnswering,
			        '''text-classification''': DistilBertForSequenceClassification,
			        '''token-classification''': DistilBertForTokenClassification,
			        '''zero-shot''': DistilBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			__lowerCamelCase	:       List[str]							=    True
			__lowerCamelCase	:       str							=    True
			__lowerCamelCase	:       int							=    True
			__lowerCamelCase	:       Optional[int]							=    True






			def    a_       (			self   :    List[Any]   )	->	Tuple:







					"""simple docstring"""






					A__        =   DistilBertModelTester(self   )
					A__        =   ConfigTester(self							,	config_class=__lowerCAmelCase							,	dim=37   )






			def    a_       (			self   :    List[str]   )	->	List[str]:







					"""simple docstring"""






					self.config_tester.run_common_tests()






			def    a_       (			self   :    str   )	->	int:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_model(*__lowerCAmelCase   )






			def    a_       (			self   :    Tuple   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_for_masked_lm(*__lowerCAmelCase   )






			def    a_       (			self   :    Union[str, Any]   )	->	List[Any]:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_for_question_answering(*__lowerCAmelCase   )






			def    a_       (			self   :    Any   )	->	List[str]:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_for_sequence_classification(*__lowerCAmelCase   )






			def    a_       (			self   :    List[str]   )	->	Tuple:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_for_token_classification(*__lowerCAmelCase   )






			def    a_       (			self   :    int   )	->	str:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_distilbert_for_multiple_choice(*__lowerCAmelCase   )






			@slow
			def    a_       (			self   :    List[Any]   )	->	Tuple:







					"""simple docstring"""






					for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__        =   DistilBertModel.from_pretrained(__lowerCAmelCase   )
							self.assertIsNotNone(__lowerCAmelCase   )







			@slow
			@require_torch_gpu
			def    a_       (			self   :    str   )	->	List[str]:







					"""simple docstring"""






					A__      ,			A__        =   self.model_tester.prepare_config_and_inputs_for_common()
					for model_class in self.all_model_classes:
							# BertForMultipleChoice behaves incorrectly in JIT environments.
							if model_class == DistilBertForMultipleChoice:
									return

							A__        =   True
							A__        =   model_class(config=__lowerCAmelCase   )

							A__        =   self._prepare_for_class(__lowerCAmelCase							,	__lowerCAmelCase   )
							A__        =   torch.jit.trace(
							    __lowerCAmelCase							,	(inputs_dict["""input_ids"""].to("""cpu"""   ), inputs_dict["""attention_mask"""].to("""cpu"""   ))   )

							with tempfile.TemporaryDirectory() as tmp:
									torch.jit.save(__lowerCAmelCase							,	os.path.join(__lowerCAmelCase							,	"""traced_model.pt"""   )   )
									A__        =   torch.jit.load(os.path.join(__lowerCAmelCase							,	"""traced_model.pt"""   )							,	map_location=__lowerCAmelCase   )
									loaded(inputs_dict["""input_ids"""].to(__lowerCAmelCase   )							,	inputs_dict["""attention_mask"""].to(__lowerCAmelCase   )   )


@require_torch
class   A			(unittest.TestCase    ):
			'''simple docstring'''




			@slow
			def    a_       (			self   :    Optional[int]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   DistilBertModel.from_pretrained("""distilbert-base-uncased"""   )
					A__        =   torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]   )
					A__        =   torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]   )
					with torch.no_grad():
							A__        =   model(__lowerCAmelCase							,	attention_mask=__lowerCAmelCase   )[0]
					A__        =   torch.Size((1, 11, 7_68)   )
					self.assertEqual(output.shape							,	__lowerCAmelCase   )
					A__        =   torch.tensor(
					    [[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]]   )

					self.assertTrue(torch.allclose(output[:, 1:4, 1:4]							,	__lowerCAmelCase							,	atol=1e-4   )   )










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
)
A    :					Tuple =      logging.getLogger(__name__)







def    __lowerCamelCase					(							__a   :Optional[int]    ,     __a   :List[str]    )		->				Tuple:






		"""simple docstring"""

		A__        =   np.argmax(__a    ,     axis=1    )
		return np.sum(outputs == labels    )







def    __lowerCamelCase					(							__a   :Tuple    )		->				Dict:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :Optional[int]    ,     __a   :List[Any]    ,     __a   :Dict    ,     __a   :Optional[Any]    ,     __a   :Optional[Any]    ,     __a   :int    )		->				Union[str, Any]:






		"""simple docstring"""

		A__        =   []
		for dataset in encoded_datasets:
				A__        =   len(__a    )
				A__        =   np.zeros((n_batch, 2, input_len)    ,     dtype=np.intaa    )
				A__        =   np.zeros((n_batch, 2)    ,     dtype=np.intaa    )
				A__        =   np.full((n_batch, 2, input_len)    ,     fill_value=-1_0_0    ,     dtype=np.intaa    )
				A__        =   np.zeros((n_batch,)    ,     dtype=np.intaa    )
				for (
				    i,
				    (story, conta, conta, mc_label),
				) in enumerate(__a    ):
						A__        =   [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
						A__        =   [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
						A__        =   with_conta
						A__        =   with_conta
						A__        =   len(__a    ) - 1
						A__        =   len(__a    ) - 1
						A__        =   with_conta
						A__        =   with_conta
						A__        =   mc_label
				A__        =   (input_ids, mc_token_ids, lm_labels, mc_labels)
				tensor_datasets.append(tuple(torch.tensor(__a    ) for t in all_inputs    )    )
		return tensor_datasets







def    __lowerCamelCase					(							)		->				Union[str, Any]:






		"""simple docstring"""

		A__        =   argparse.ArgumentParser()
		parser.add_argument("""--model_name"""    ,     type=__a    ,     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=__a    ,     type=__a    ,     required=__a    ,     help="""The output directory where the model predictions and checkpoints will be written."""    ,     )
		parser.add_argument("""--train_dataset"""    ,     type=__a    ,     default=""""""    )
		parser.add_argument("""--eval_dataset"""    ,     type=__a    ,     default=""""""    )
		parser.add_argument("""--seed"""    ,     type=__a    ,     default=4_2    )
		parser.add_argument("""--num_train_epochs"""    ,     type=__a    ,     default=3    )
		parser.add_argument("""--train_batch_size"""    ,     type=__a    ,     default=8    )
		parser.add_argument("""--eval_batch_size"""    ,     type=__a    ,     default=1_6    )
		parser.add_argument("""--adam_epsilon"""    ,     default=1E-8    ,     type=__a    ,     help="""Epsilon for Adam optimizer."""    )
		parser.add_argument("""--max_grad_norm"""    ,     type=__a    ,     default=1    )
		parser.add_argument(
		    """--max_steps"""    ,     default=-1    ,     type=__a    ,     help=(
		        """If > 0: set total number of training                         steps to perform. Override num_train_epochs."""
		    )    ,     )
		parser.add_argument(
		    """--gradient_accumulation_steps"""    ,     type=__a    ,     default=1    ,     help="""Number of updates steps to accumulate before                        performing a backward/update pass."""    ,     )
		parser.add_argument("""--learning_rate"""    ,     type=__a    ,     default=6.25E-5    )
		parser.add_argument("""--warmup_steps"""    ,     default=0    ,     type=__a    ,     help="""Linear warmup over warmup_steps."""    )
		parser.add_argument("""--lr_schedule"""    ,     type=__a    ,     default="""warmup_linear"""    )
		parser.add_argument("""--weight_decay"""    ,     type=__a    ,     default=0.01    )
		parser.add_argument("""--lm_coef"""    ,     type=__a    ,     default=0.9    )
		parser.add_argument("""--n_valid"""    ,     type=__a    ,     default=3_7_4    )

		parser.add_argument("""--server_ip"""    ,     type=__a    ,     default=""""""    ,     help="""Can be used for distant debugging."""    )
		parser.add_argument("""--server_port"""    ,     type=__a    ,     default=""""""    ,     help="""Can be used for distant debugging."""    )
		A__        =   parser.parse_args()
		print(__a    )

		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=__a    )
				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__        =   torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""    )
		A__        =   torch.cuda.device_count()
		logger.info("""device: {}, n_gpu {}""".format(__a    ,     __a    )    )

		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__        =   ["""_start_""", """_delimiter_""", """_classify_"""]
		A__        =   OpenAIGPTTokenizer.from_pretrained(args.model_name    )
		tokenizer.add_tokens(__a    )
		A__        =   tokenizer.convert_tokens_to_ids(__a    )
		A__        =   OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name    )
		model.resize_token_embeddings(len(__a    )    )
		model.to(__a    )

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

		logger.info("""Encoding dataset..."""    )
		A__        =   load_rocstories_dataset(args.train_dataset    )
		A__        =   load_rocstories_dataset(args.eval_dataset    )
		A__        =   (train_dataset, eval_dataset)
		A__        =   tokenize_and_encode(__a    )

		# Compute the max input length for the Transformer
		A__        =   model.config.n_positions // 2 - 2
		A__        =   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__        =   min(__a    ,     model.config.n_positions    )  # Max size of input for the pre-trained model

		# Prepare inputs tensors and dataloaders
		A__        =   pre_process_datasets(__a    ,     __a    ,     __a    ,     *__a    )
		A__      ,			A__        =   tensor_datasets[0], tensor_datasets[1]

		A__        =   TensorDataset(*__a    )
		A__        =   RandomSampler(__a    )
		A__        =   DataLoader(__a    ,     sampler=__a    ,     batch_size=args.train_batch_size    )

		A__        =   TensorDataset(*__a    )
		A__        =   SequentialSampler(__a    )
		A__        =   DataLoader(__a    ,     sampler=__a    ,     batch_size=args.eval_batch_size    )

		# Prepare optimizer
		if args.do_train:
				if args.max_steps > 0:
						A__        =   args.max_steps
						A__        =   args.max_steps // (len(__a    ) // args.gradient_accumulation_steps) + 1
				else:
						A__        =   len(__a    ) // args.gradient_accumulation_steps * args.num_train_epochs

				A__        =   list(model.named_parameters()    )
				A__        =   ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""]
				A__        =   [
				    {
				        """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__        =   AdamW(__a    ,     lr=args.learning_rate    ,     eps=args.adam_epsilon    )
				A__        =   get_linear_schedule_with_warmup(
				    __a    ,     num_warmup_steps=args.warmup_steps    ,     num_training_steps=__a    )

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

    # Save a trained model
		if args.do_train:
				# Save a trained model, configuration and tokenizer
				A__        =   model.module if hasattr(__a    ,     """module"""    ) else model  # Only save the model itself

				# If we save using the predefined names, we can load using `from_pretrained`
				A__        =   os.path.join(args.output_dir    ,     __a    )
				A__        =   os.path.join(args.output_dir    ,     __a    )

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

				# Load a trained model and vocabulary that you have fine-tuned
				A__        =   OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir    )
				A__        =   OpenAIGPTTokenizer.from_pretrained(args.output_dir    )
				model.to(__a    )

		if args.do_eval:
				model.eval()
				A__      ,			A__        =   0, 0
				A__      ,			A__        =   0, 0
				for batch in tqdm(__a    ,     desc="""Evaluating"""    ):
						A__        =   tuple(t.to(__a    ) for t in batch    )
						A__      ,			A__      ,			A__      ,			A__        =   batch
						with torch.no_grad():
								A__      ,			A__      ,			A__      ,			A__        =   model(
								    __a    ,     mc_token_ids=__a    ,     lm_labels=__a    ,     mc_labels=__a    )

						A__        =   mc_logits.detach().cpu().numpy()
						A__        =   mc_labels.to("""cpu"""    ).numpy()
						A__        =   accuracy(__a    ,     __a    )

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

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

				A__        =   eval_loss / nb_eval_steps
				A__        =   eval_accuracy / nb_eval_examples
				A__        =   tr_loss / nb_tr_steps if args.do_train else None
				A__        =   {"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss}

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


if __name__ == "__main__":
					main()



