


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
)
snake_case    :   List[str]	    =					logging.getLogger(__name__)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		Any						):




      """simple docstring"""





      a						:Optional[Any]										=	np.argmax(UpperCAmelCase_			,  axis=1						)
      return np.sum(outputs == labels						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]						):




      """simple docstring"""





      with open(UpperCAmelCase_			,  encoding='''utf_8'''						) as f:
            a						:List[str]										=	csv.reader(UpperCAmelCase_						)
            a						:Tuple										=	[]
            next(UpperCAmelCase_						)  # skip the first line
            for line in tqdm(UpperCAmelCase_						):
                  output.append((''' '''.join(line[1:5]						), line[5], line[6], int(line[-1]						) - 1)						)
      return output
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[Any]			,  UpperCAmelCase_						:		Dict			,  UpperCAmelCase_						:		str			,  UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		Union[str, Any]			,  UpperCAmelCase_						:		Tuple						):




      """simple docstring"""





      a						:Optional[int]										=	[]
      for dataset in encoded_datasets:
            a						:Union[str, Any]										=	len(UpperCAmelCase_						)
            a						:Tuple										=	np.zeros((n_batch, 2, input_len)			,  dtype=np.intaa						)
            a						:Optional[Any]										=	np.zeros((n_batch, 2)			,  dtype=np.intaa						)
            a						:int										=	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(UpperCAmelCase_						):
                  a						:Optional[int]										=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  a						:Optional[Any]										=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  a						:Union[str, Any]										=	with_conta
                  a						:List[Any]										=	with_conta
                  a						:Dict										=	len(UpperCAmelCase_						) - 1
                  a						:Tuple										=	len(UpperCAmelCase_						) - 1
                  a						:Dict										=	with_conta
                  a						:List[str]										=	with_conta
                  a						:Any										=	mc_label
            a						:str										=	(input_ids, mc_token_ids, lm_labels, mc_labels)
            tensor_datasets.append(tuple(torch.tensor(UpperCAmelCase_						) for t in all_inputs						)						)
      return tensor_datasets
def     __lowerCamelCase						(			):




      """simple docstring"""





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

      parser.add_argument('''--server_ip'''			,  type=UpperCAmelCase_			,  default=''''''			,  help='''Can be used for distant debugging.'''						)
      parser.add_argument('''--server_port'''			,  type=UpperCAmelCase_			,  default=''''''			,  help='''Can be used for distant debugging.'''						)
      a						:int										=	parser.parse_args()
      print(UpperCAmelCase_						)

      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=UpperCAmelCase_						)
            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						:Dict										=	torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''						)
      a						:str										=	torch.cuda.device_count()
      logger.info('''device: {}, n_gpu {}'''.format(UpperCAmelCase_			,  UpperCAmelCase_						)						)

      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						:List[str]										=	['''_start_''', '''_delimiter_''', '''_classify_''']
      a						:Dict										=	OpenAIGPTTokenizer.from_pretrained(args.model_name						)
      tokenizer.add_tokens(UpperCAmelCase_						)
      a						:Tuple										=	tokenizer.convert_tokens_to_ids(UpperCAmelCase_						)
      a						:Tuple										=	OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name						)
      model.resize_token_embeddings(len(UpperCAmelCase_						)						)
      model.to(UpperCAmelCase_						)

      # Load and encode the datasets
      def tokenize_and_encode(UpperCAmelCase_						:		Optional[int]						):
            if isinstance(UpperCAmelCase_			,  UpperCAmelCase_						):
                  return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCAmelCase_						)						)
            elif isinstance(UpperCAmelCase_			,  UpperCAmelCase_						):
                  return obj
            return [tokenize_and_encode(UpperCAmelCase_						) 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						:str										=	(train_dataset, eval_dataset)
      a						:Union[str, Any]										=	tokenize_and_encode(UpperCAmelCase_						)

      # Compute the max input length for the Transformer
      a						:List[Any]										=	model.config.n_positions // 2 - 2
      a						:List[str]										=	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						:List[Any]										=	min(UpperCAmelCase_			,  model.config.n_positions						)  # Max size of input for the pre-trained model

      # Prepare inputs tensors and dataloaders
      a						:Union[str, Any]										=	pre_process_datasets(UpperCAmelCase_			,  UpperCAmelCase_			,  UpperCAmelCase_			,  *UpperCAmelCase_						)
      a							,    a						:Any										=	tensor_datasets[0], tensor_datasets[1]

      a						:int										=	TensorDataset(*UpperCAmelCase_						)
      a						:Tuple										=	RandomSampler(UpperCAmelCase_						)
      a						:Union[str, Any]										=	DataLoader(UpperCAmelCase_			,  sampler=UpperCAmelCase_			,  batch_size=args.train_batch_size						)

      a						:int										=	TensorDataset(*UpperCAmelCase_						)
      a						:Dict										=	SequentialSampler(UpperCAmelCase_						)
      a						:str										=	DataLoader(UpperCAmelCase_			,  sampler=UpperCAmelCase_			,  batch_size=args.eval_batch_size						)

      # Prepare optimizer
      if args.do_train:
            if args.max_steps > 0:
                  a						:List[Any]										=	args.max_steps
                  a						:List[str]										=	args.max_steps // (len(UpperCAmelCase_						) // args.gradient_accumulation_steps) + 1
            else:
                  a						:Dict										=	len(UpperCAmelCase_						) // args.gradient_accumulation_steps * args.num_train_epochs

            a						:Optional[Any]										=	list(model.named_parameters()						)
            a						:List[Any]										=	['''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						:Any										=	AdamW(UpperCAmelCase_			,  lr=args.learning_rate			,  eps=args.adam_epsilon						)
            a						:List[Any]										=	get_linear_schedule_with_warmup(
                UpperCAmelCase_			,  num_warmup_steps=args.warmup_steps			,  num_training_steps=UpperCAmelCase_						)

      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						:List[str]										=	0
                  a						:Any										=	0
                  a						:Optional[int]										=	tqdm(UpperCAmelCase_			,  desc='''Training'''						)
                  for step, batch in enumerate(UpperCAmelCase_						):
                        a						:Optional[Any]										=	tuple(t.to(UpperCAmelCase_						) for t in batch						)
                        a							,    a							,    a							,    a						:Optional[Any]										=	batch
                        a						:int										=	model(UpperCAmelCase_			,  mc_token_ids=UpperCAmelCase_			,  lm_labels=UpperCAmelCase_			,  mc_labels=UpperCAmelCase_						)
                        a						:List[Any]										=	args.lm_coef * losses[0] + losses[1]
                        loss.backward()
                        optimizer.step()
                        scheduler.step()
                        optimizer.zero_grad()
                        tr_loss += loss.item()
                        a						:Any										=	(
                            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                        )
                        nb_tr_steps += 1
                        a						:Union[str, Any]										=	'''Training loss: {:.2e} lr: {:.2e}'''.format(UpperCAmelCase_			,  scheduler.get_lr()[0]						)

    # Save a trained model
      if args.do_train:
            # Save a trained model, configuration and tokenizer
            a						:List[Any]										=	model.module if hasattr(UpperCAmelCase_			,  '''module'''						) else model  # Only save the model itself

            # If we save using the predefined names, we can load using `from_pretrained`
            a						:Any										=	os.path.join(args.output_dir			,  UpperCAmelCase_						)
            a						:List[Any]										=	os.path.join(args.output_dir			,  UpperCAmelCase_						)

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

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

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

                  a						:Dict										=	mc_logits.detach().cpu().numpy()
                  a						:Dict										=	mc_labels.to('''cpu'''						).numpy()
                  a						:Union[str, Any]										=	accuracy(UpperCAmelCase_			,  UpperCAmelCase_						)

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

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

            a						:List[Any]										=	eval_loss / nb_eval_steps
            a						:Any										=	eval_accuracy / nb_eval_examples
            a						:str										=	tr_loss / nb_tr_steps if args.do_train else None
            a						:Optional[int]										=	{'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

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


if __name__ == "__main__":
     main()









from . import __version__

# Backward compatibility imports, to make sure all those objects can be found in file_utils
from .utils import (
    CLOUDFRONT_DISTRIB_PREFIX,
    CONFIG_NAME,
    DISABLE_TELEMETRY,
    DUMMY_INPUTS,
    DUMMY_MASK,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    FEATURE_EXTRACTOR_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    MODEL_CARD_NAME,
    MULTIPLE_CHOICE_DUMMY_INPUTS,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    SENTENCEPIECE_UNDERLINE,
    SPIECE_UNDERLINE,
    TF2_WEIGHTS_NAME,
    TF_WEIGHTS_NAME,
    TORCH_FX_REQUIRED_VERSION,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
    ContextManagers,
    DummyObject,
    EntryNotFoundError,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    TensorType,
    _LazyModule,
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    cached_property,
    copy_func,
    default_cache_path,
    define_sagemaker_information,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    get_torch_version,
    has_file,
    http_user_agent,
    is_apex_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_datasets_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_librosa_available,
    is_offline_mode,
    is_onnx_available,
    is_pandas_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_tensor,
    is_tensorflow_probability_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    replace_return_docstrings,
    requires_backends,
    to_numpy,
    to_py_obj,
    torch_only_method,
)





