



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





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase       ):
    __a		 =       np.argmax(_UpperCAmelCase     ,				axis=1       )
    return np.sum(outputs == labels       )





def   __snake_case			(    _UpperCAmelCase       ):
    with open(_UpperCAmelCase     ,				encoding='''utf_8'''       ) as f:
        __a		 =       csv.reader(_UpperCAmelCase       )
        __a		 =       []
        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   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       ):
    __a		 =       []
    for dataset in encoded_datasets:
        __a		 =       len(_UpperCAmelCase       )
        __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=-100     ,				dtype=np.intaa       )
        __a		 =       np.zeros((n_batch,)     ,				dtype=np.intaa       )
        for (
            i,
            (story, conta, conta, mc_label),
        ) in enumerate(_UpperCAmelCase       ):
            __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(_UpperCAmelCase       ) - 1
            __a		 =       len(_UpperCAmelCase       ) - 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(_UpperCAmelCase       ) for t in all_inputs       )       )
    return tensor_datasets





def   __snake_case			(    ):
    __a		 =       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.2_5E-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		 =       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		 =       torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''       )
    __a		 =       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		 =       ['''_start_''', '''_delimiter_''', '''_classify_''']
    __a		 =       OpenAIGPTTokenizer.from_pretrained(args.model_name       )
    tokenizer.add_tokens(_UpperCAmelCase       )
    __a		 =       tokenizer.convert_tokens_to_ids(_UpperCAmelCase       )
    __a		 =       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       ):
        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		 =       load_rocstories_dataset(args.train_dataset       )
    __a		 =       load_rocstories_dataset(args.eval_dataset       )
    __a		 =       (train_dataset, eval_dataset)
    __a		 =       tokenize_and_encode(_UpperCAmelCase       )

    # 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(_UpperCAmelCase     ,				model.config.n_positions       )  # Max size of input for the pre-trained model

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

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

    __a		 =       TensorDataset(*_UpperCAmelCase       )
    __a		 =       SequentialSampler(_UpperCAmelCase       )
    __a		 =       DataLoader(_UpperCAmelCase     ,				sampler=_UpperCAmelCase     ,				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(_UpperCAmelCase       ) // args.gradient_accumulation_steps) + 1
        else:
            __a		 =       len(_UpperCAmelCase       ) // 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(_UpperCAmelCase     ,				lr=args.learning_rate     ,				eps=args.adam_epsilon       )
        __a		 =       get_linear_schedule_with_warmup(
            _UpperCAmelCase     ,				num_warmup_steps=args.warmup_steps     ,				num_training_steps=_UpperCAmelCase       )

    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(_UpperCAmelCase     ,				desc='''Training'''       )
            for step, batch in enumerate(_UpperCAmelCase       ):
                __a		 =       tuple(t.to(_UpperCAmelCase       ) for t in batch       )
                __a ,     __a ,     __a ,     __a		 =       batch
                __a		 =       model(_UpperCAmelCase     ,				mc_token_ids=_UpperCAmelCase     ,				lm_labels=_UpperCAmelCase     ,				mc_labels=_UpperCAmelCase       )
                __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(_UpperCAmelCase     ,				scheduler.get_lr()[0]       )

    # Save a trained model
    if args.do_train:
        # Save a trained model, configuration and tokenizer
        __a		 =       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		 =       os.path.join(args.output_dir     ,				_UpperCAmelCase       )
        __a		 =       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		 =       OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir       )
        __a		 =       OpenAIGPTTokenizer.from_pretrained(args.output_dir       )
        model.to(_UpperCAmelCase       )

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

            __a		 =       mc_logits.detach().cpu().numpy()
            __a		 =       mc_labels.to('''cpu'''       ).numpy()
            __a		 =       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		 =       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(_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 collections.abc import Generator
from math import sin





def   __snake_case			(    _UpperCAmelCase       ):
    if len(_UpperCAmelCase       ) != 32:
        raise ValueError('''Input must be of length 32'''       )

    __a		 =       b''''''
    for i in [3, 2, 1, 0]:
        little_endian += string_aa[8 * i : 8 * i + 8]
    return little_endian





def   __snake_case			(    _UpperCAmelCase       ):
    if i < 0:
        raise ValueError('''Input must be non-negative'''       )

    __a		 =       format(_UpperCAmelCase     ,				'''08x'''       )[-8:]
    __a		 =       b''''''
    for i in [3, 2, 1, 0]:
        little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8'''       )
    return little_endian_hex





def   __snake_case			(    _UpperCAmelCase       ):
    __a		 =       b''''''
    for char in message:
        bit_string += format(_UpperCAmelCase     ,				'''08b'''       ).encode('''utf-8'''       )
    __a		 =       format(len(_UpperCAmelCase       )     ,				'''064b'''       ).encode('''utf-8'''       )

    # Pad bit_string to a multiple of 512 chars
    bit_string += b"1"
    while len(_UpperCAmelCase       ) % 512 != 448:
        bit_string += b"0"
    bit_string += to_little_endian(start_len[32:]       ) + to_little_endian(start_len[:32]       )

    return bit_string





def   __snake_case			(    _UpperCAmelCase       ):
    if len(_UpperCAmelCase       ) % 512 != 0:
        raise ValueError('''Input must have length that\'s a multiple of 512'''       )

    for pos in range(0     ,				len(_UpperCAmelCase       )     ,				512       ):
        __a		 =       bit_string[pos : pos + 512]
        __a		 =       []
        for i in range(0     ,				512     ,				32       ):
            block_words.append(int(to_little_endian(block[i : i + 32]       )     ,				2       )       )
        yield block_words





def   __snake_case			(    _UpperCAmelCase       ):
    if i < 0:
        raise ValueError('''Input must be non-negative'''       )

    __a		 =       format(_UpperCAmelCase     ,				'''032b'''       )
    __a		 =       ''''''
    for c in i_str:
        new_str += "1" if c == "0" else "0"
    return int(_UpperCAmelCase     ,				2       )





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase       ):
    return (a + b) % 2**32





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase       ):
    if i < 0:
        raise ValueError('''Input must be non-negative'''       )
    if shift < 0:
        raise ValueError('''Shift must be non-negative'''       )
    return ((i << shift) ^ (i >> (32 - shift))) % 2**32





def   __snake_case			(    _UpperCAmelCase       ):
    __a		 =       preprocess(_UpperCAmelCase       )

    __a		 =       [int(2**32 * abs(sin(i + 1       )       )       ) for i in range(64       )]

    # Starting states
    __a		 =       0X67_452_301
    __a		 =       0Xef_cda_b89
    __a		 =       0X98_bad_cfe
    __a		 =       0X10_325_476

    __a		 =       [
        7,
        12,
        17,
        22,
        7,
        12,
        17,
        22,
        7,
        12,
        17,
        22,
        7,
        12,
        17,
        22,
        5,
        9,
        14,
        20,
        5,
        9,
        14,
        20,
        5,
        9,
        14,
        20,
        5,
        9,
        14,
        20,
        4,
        11,
        16,
        23,
        4,
        11,
        16,
        23,
        4,
        11,
        16,
        23,
        4,
        11,
        16,
        23,
        6,
        10,
        15,
        21,
        6,
        10,
        15,
        21,
        6,
        10,
        15,
        21,
        6,
        10,
        15,
        21,
    ]

    # Process bit string in chunks, each with 16 32-char words
    for block_words in get_block_words(_UpperCAmelCase       ):
        __a		 =       aa
        __a		 =       ba
        __a		 =       ca
        __a		 =       da

        # Hash current chunk
        for i in range(64       ):
            if i <= 15:
                # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                __a		 =       d ^ (b & (c ^ d))
                __a		 =       i
            elif i <= 31:
                # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                __a		 =       c ^ (d & (b ^ c))
                __a		 =       (5 * i + 1) % 16
            elif i <= 47:
                __a		 =       b ^ c ^ d
                __a		 =       (3 * i + 5) % 16
            else:
                __a		 =       c ^ (b | not_aa(_UpperCAmelCase       ))
                __a		 =       (7 * i) % 16
            __a		 =       (f + a + added_consts[i] + block_words[g]) % 2**32
            __a		 =       d
            __a		 =       c
            __a		 =       b
            __a		 =       sum_aa(_UpperCAmelCase     ,				left_rotate_aa(_UpperCAmelCase     ,				shift_amounts[i]       )       )

        # Add hashed chunk to running total
        __a		 =       sum_aa(_UpperCAmelCase     ,				_UpperCAmelCase       )
        __a		 =       sum_aa(_UpperCAmelCase     ,				_UpperCAmelCase       )
        __a		 =       sum_aa(_UpperCAmelCase     ,				_UpperCAmelCase       )
        __a		 =       sum_aa(_UpperCAmelCase     ,				_UpperCAmelCase       )

    __a		 =       reformat_hex(_UpperCAmelCase       ) + reformat_hex(_UpperCAmelCase       ) + reformat_hex(_UpperCAmelCase       ) + reformat_hex(_UpperCAmelCase       )
    return digest


if __name__ == "__main__":
 import doctest

 doctest.testmod()





