






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
)
SCREAMING_SNAKE_CASE__				     =			logging.getLogger(__name__)

def        UpperCAmelCase__		(						lowerCamelCase_       :       Any   ,  lowerCamelCase_       :       List[Any]				):
			__a						:  Any									=     np.argmax(lowerCamelCase_   ,  axis=1				)
			return np.sum(outputs == labels				)

def        UpperCAmelCase__		(						lowerCamelCase_       :       Tuple				):
			with open(lowerCamelCase_   ,  encoding='utf_8'				) as f:
						__a						:  Optional[Any]									=     csv.reader(lowerCamelCase_				)
						__a						:  Optional[int]									=     []
						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        UpperCAmelCase__		(						lowerCamelCase_       :       Any   ,  lowerCamelCase_       :       Dict   ,  lowerCamelCase_       :       Dict   ,  lowerCamelCase_       :       List[Any]   ,  lowerCamelCase_       :       str   ,  lowerCamelCase_       :       Optional[Any]				):
			__a						:  int									=     []
			for dataset in encoded_datasets:
						__a						:  List[Any]									=     len(lowerCamelCase_				)
						__a						:  Optional[Any]									=     np.zeros((n_batch, 2, input_len)   ,  dtype=np.intaa				)
						__a						:  Optional[int]									=     np.zeros((n_batch, 2)   ,  dtype=np.intaa				)
						__a						:  str									=     np.full((n_batch, 2, input_len)   ,  fill_value=-1_0_0   ,  dtype=np.intaa				)
						__a						:  List[Any]									=     np.zeros((n_batch,)   ,  dtype=np.intaa				)
						for (
						    i,
						    (story, conta, conta, mc_label),
						) in enumerate(lowerCamelCase_				):
									__a						:  str									=     [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
									__a						:  int									=     [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
									__a						:  List[str]									=     with_conta
									__a						:  Optional[Any]									=     with_conta
									__a						:  Any									=     len(lowerCamelCase_				) - 1
									__a						:  Any									=     len(lowerCamelCase_				) - 1
									__a						:  Optional[int]									=     with_conta
									__a						:  Tuple									=     with_conta
									__a						:  Optional[int]									=     mc_label
						__a						:  Union[str, Any]									=     (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        UpperCAmelCase__		(						):
			__a						:  List[str]									=     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=4_2				)
			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=1_6				)
			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=3_7_4				)

			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						:  int									=     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						:  Any									=     torch.device('cuda' if torch.cuda.is_available() else 'cpu'				)
			__a						:  Union[str, Any]									=     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						:  Optional[int]									=     OpenAIGPTTokenizer.from_pretrained(args.model_name				)
			tokenizer.add_tokens(lowerCamelCase_				)
			__a						:  Optional[int]									=     tokenizer.convert_tokens_to_ids(lowerCamelCase_				)
			__a						:  int									=     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_       :       Optional[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						:  Tuple									=     load_rocstories_dataset(args.train_dataset				)
			__a						:  List[Any]									=     load_rocstories_dataset(args.eval_dataset				)
			__a						:  str									=     (train_dataset, eval_dataset)
			__a						:  str									=     tokenize_and_encode(lowerCamelCase_				)

			# Compute the max input length for the Transformer
			__a						:  Any									=     model.config.n_positions // 2 - 2
			__a						:  Dict									=     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						:  Dict									=     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						,					__a						:  str									=     tensor_datasets[0], tensor_datasets[1]

			__a						:  str									=     TensorDataset(*lowerCamelCase_				)
			__a						:  int									=     RandomSampler(lowerCamelCase_				)
			__a						:  str									=     DataLoader(lowerCamelCase_   ,  sampler=lowerCamelCase_   ,  batch_size=args.train_batch_size				)

			__a						:  List[Any]									=     TensorDataset(*lowerCamelCase_				)
			__a						:  str									=     SequentialSampler(lowerCamelCase_				)
			__a						:  Dict									=     DataLoader(lowerCamelCase_   ,  sampler=lowerCamelCase_   ,  batch_size=args.eval_batch_size				)

			# Prepare optimizer
			if args.do_train:
						if args.max_steps > 0:
									__a						:  Optional[Any]									=     args.max_steps
									__a						:  int									=     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						:  Any									=     list(model.named_parameters()				)
						__a						:  Optional[int]									=     ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
						__a						:  int									=     [
						    {
						        '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						:  List[str]									=     AdamW(lowerCamelCase_   ,  lr=args.learning_rate   ,  eps=args.adam_epsilon				)
						__a						:  Optional[Any]									=     get_linear_schedule_with_warmup(
						    lowerCamelCase_   ,  num_warmup_steps=args.warmup_steps   ,  num_training_steps=lowerCamelCase_				)

			if args.do_train:
						__a						,					__a						,					__a						:  List[Any]									=     0, 0, None
						model.train()
						for _ in trange(int(args.num_train_epochs				)   ,  desc='Epoch'				):
									__a						:  Union[str, Any]									=     0
									__a						:  int									=     0
									__a						:  str									=     tqdm(lowerCamelCase_   ,  desc='Training'				)
									for step, batch in enumerate(lowerCamelCase_				):
												__a						:  int									=     tuple(t.to(lowerCamelCase_				) for t in batch				)
												__a						,					__a						,					__a						,					__a						:  Any									=     batch
												__a						:  List[Any]									=     model(lowerCamelCase_   ,  mc_token_ids=lowerCamelCase_   ,  lm_labels=lowerCamelCase_   ,  mc_labels=lowerCamelCase_				)
												__a						:  Union[str, Any]									=     args.lm_coef * losses[0] + losses[1]
												loss.backward()
												optimizer.step()
												scheduler.step()
												optimizer.zero_grad()
												tr_loss += loss.item()
												__a						:  Optional[int]									=     (
												    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
												)
												nb_tr_steps += 1
												__a						:  Optional[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						:  List[str]									=     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						:  Union[str, Any]									=     os.path.join(args.output_dir   ,  lowerCamelCase_				)
						__a						:  List[Any]									=     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						:  str									=     OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir				)
						__a						:  Tuple									=     OpenAIGPTTokenizer.from_pretrained(args.output_dir				)
						model.to(lowerCamelCase_				)

			if args.do_eval:
						model.eval()
						__a						,					__a						:  Union[str, Any]									=     0, 0
						__a						,					__a						:  List[Any]									=     0, 0
						for batch in tqdm(lowerCamelCase_   ,  desc='Evaluating'				):
									__a						:  int									=     tuple(t.to(lowerCamelCase_				) for t in batch				)
									__a						,					__a						,					__a						,					__a						:  Dict									=     batch
									with torch.no_grad():
												__a						,					__a						,					__a						,					__a						:  Dict									=     model(
												    lowerCamelCase_   ,  mc_token_ids=lowerCamelCase_   ,  lm_labels=lowerCamelCase_   ,  mc_labels=lowerCamelCase_				)

									__a						:  int									=     mc_logits.detach().cpu().numpy()
									__a						:  List[str]									=     mc_labels.to('cpu'				).numpy()
									__a						:  str									=     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[int]									=     eval_loss / nb_eval_steps
						__a						:  Dict									=     eval_accuracy / nb_eval_examples
						__a						:  Dict									=     tr_loss / nb_tr_steps if args.do_train else None
						__a						:  Dict									=     {'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

						__a						:  str									=     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 warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


def       snake_case   (	snake_case      : Any			) ->  Any:


    """simple docstring"""


    return 1.0 / (1.0 + np.exp(-_outputs			))


def       snake_case   (	snake_case      : Dict			) ->  str:


    """simple docstring"""


    lowerCAmelCase 						=							np.max(_outputs					,		axis=-1					,		keepdims=snake_case			)
    lowerCAmelCase 						=							np.exp(_outputs - maxes			)
    return shifted_exp / shifted_exp.sum(axis=-1					,		keepdims=snake_case			)



class 				_snake_case					(   a_			):
  SCREAMING_SNAKE_CASE			:       List[str]				=     '''sigmoid'''
  SCREAMING_SNAKE_CASE			:       List[Any]				=     '''softmax'''
  SCREAMING_SNAKE_CASE			:       Optional[Any]				=     '''none'''



@add_end_docstrings(
    a_     , R'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''     , )
class 				_snake_case					(   a_			):
  SCREAMING_SNAKE_CASE			:       Union[str, Any]				=     False
  SCREAMING_SNAKE_CASE			:       Dict				=     ClassificationFunction.NONE

  def __init__(				self      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      super().__init__(**_SCREAMING_SNAKE_CASE	)

      self.check_model_type(
          TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
          if self.framework == 'tf'
          else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=""      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							tokenizer_kwargs

      lowerCAmelCase 						=							{}
      if hasattr(self.model.config      , 'return_all_scores'	) and return_all_scores is None:
          lowerCAmelCase 						=							self.model.config.return_all_scores

      if isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	) or top_k is None:
          lowerCAmelCase 						=							top_k
          lowerCAmelCase 						=							False
      elif return_all_scores is not None:
          warnings.warn(
              '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
              ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'      , _SCREAMING_SNAKE_CASE      , )
          if return_all_scores:
              lowerCAmelCase 						=							None
          else:
              lowerCAmelCase 						=							1

      if isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          lowerCAmelCase 						=							ClassificationFunction[function_to_apply.upper()]

      if function_to_apply is not None:
          lowerCAmelCase 						=							function_to_apply
      return preprocess_params, {}, postprocess_params

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





      '''simple docstring'''

      lowerCAmelCase 						=							super().__call__(*_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      # TODO try and retrieve it in a nicer way from _sanitize_parameters.
      lowerCAmelCase 						=							'top_k' not in kwargs
      if isinstance(args[0]      , _SCREAMING_SNAKE_CASE	) and _legacy:
          # This pipeline is odd, and return a list when single item is run
          return [result]
      else:
          return result

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.framework
      if isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          return self.tokenizer(**_SCREAMING_SNAKE_CASE      , return_tensors=_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      elif isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	) and len(_SCREAMING_SNAKE_CASE	) == 1 and isinstance(inputs[0]      , _SCREAMING_SNAKE_CASE	) and len(inputs[0]	) == 2:
          # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
          return self.tokenizer(
              text=inputs[0][0]      , text_pair=inputs[0][1]      , return_tensors=_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      elif isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          # This is likely an invalid usage of the pipeline attempting to pass text pairs.
          raise ValueError(
              'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
              ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'	)
      return self.tokenizer(_SCREAMING_SNAKE_CASE      , return_tensors=_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      return self.model(**_SCREAMING_SNAKE_CASE	)


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=1      , _SCREAMING_SNAKE_CASE=True	):





      '''simple docstring'''

      if function_to_apply is None:
          if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
              lowerCAmelCase 						=							ClassificationFunction.SIGMOID
          elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
              lowerCAmelCase 						=							ClassificationFunction.SOFTMAX
          elif hasattr(self.model.config      , 'function_to_apply'	) and function_to_apply is None:
              lowerCAmelCase 						=							self.model.config.function_to_apply
          else:
              lowerCAmelCase 						=							ClassificationFunction.NONE

      lowerCAmelCase 						=							model_outputs['logits'][0]
      lowerCAmelCase 						=							outputs.numpy()

      if function_to_apply == ClassificationFunction.SIGMOID:
          lowerCAmelCase 						=							sigmoid(_SCREAMING_SNAKE_CASE	)
      elif function_to_apply == ClassificationFunction.SOFTMAX:
          lowerCAmelCase 						=							softmax(_SCREAMING_SNAKE_CASE	)
      elif function_to_apply == ClassificationFunction.NONE:
          lowerCAmelCase 						=							outputs
      else:
          raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}'	)

      if top_k == 1 and _legacy:
          return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

      lowerCAmelCase 						=							[
          {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(_SCREAMING_SNAKE_CASE	)
      ]
      if not _legacy:
          dict_scores.sort(key=lambda _SCREAMING_SNAKE_CASE	: x["score"]      , reverse=_SCREAMING_SNAKE_CASE	)
          if top_k is not None:
              lowerCAmelCase 						=							dict_scores[:top_k]
      return dict_scores





