



'''simple docstring'''
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_					:      Tuple    			=    logging.getLogger(__name__)






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_				):
						_UpperCamelCase   :						str												=  np.argmax(UpperCAmelCase_    ,    axis=1				)
						return np.sum(outputs == labels				)






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

						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.'				)
						_UpperCamelCase   :						str												=  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				)

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

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

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

						_UpperCamelCase   :						str												=  TensorDataset(*UpperCAmelCase_				)
						_UpperCamelCase   :						Optional[Any]												=  RandomSampler(UpperCAmelCase_				)
						_UpperCamelCase   :						List[Any]												=  DataLoader(UpperCAmelCase_    ,    sampler=UpperCAmelCase_    ,    batch_size=args.train_batch_size				)

						_UpperCamelCase   :						Tuple												=  TensorDataset(*UpperCAmelCase_				)
						_UpperCamelCase   :						Optional[int]												=  SequentialSampler(UpperCAmelCase_				)
						_UpperCamelCase   :						Optional[Any]												=  DataLoader(UpperCAmelCase_    ,    sampler=UpperCAmelCase_    ,    batch_size=args.eval_batch_size				)

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

												_UpperCamelCase   :						Tuple												=  list(model.named_parameters()				)
												_UpperCamelCase   :						str												=  ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
												_UpperCamelCase   :						Optional[Any]												=  [
												    {
												        '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},
												]
												_UpperCamelCase   :						Any												=  AdamW(UpperCAmelCase_    ,    lr=args.learning_rate    ,    eps=args.adam_epsilon				)
												_UpperCamelCase   :						Union[str, Any]												=  get_linear_schedule_with_warmup(
												    UpperCAmelCase_    ,    num_warmup_steps=args.warmup_steps    ,    num_training_steps=UpperCAmelCase_				)

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

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

																		_UpperCamelCase   :						List[Any]												=  mc_logits.detach().cpu().numpy()
																		_UpperCamelCase   :						Optional[Any]												=  mc_labels.to('cpu'				).numpy()
																		_UpperCamelCase   :						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

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

												_UpperCamelCase   :						List[Any]												=  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()







'''simple docstring'''
import argparse

import torch

from transformers import YosoConfig, YosoForMaskedLM






def A__       (	UpperCAmelCase_				):
						if "model" in orig_key:
												_UpperCamelCase   :						List[Any]												=  orig_key.replace('model.'    ,    ''				)
						if "norm1" in orig_key:
												_UpperCamelCase   :						List[Any]												=  orig_key.replace('norm1'    ,    'attention.output.LayerNorm'				)
						if "norm2" in orig_key:
												_UpperCamelCase   :						int												=  orig_key.replace('norm2'    ,    'output.LayerNorm'				)
						if "norm" in orig_key:
												_UpperCamelCase   :						str												=  orig_key.replace('norm'    ,    'LayerNorm'				)
						if "transformer" in orig_key:
												_UpperCamelCase   :						int												=  orig_key.split('.'				)[0].split('_'				)[-1]
												_UpperCamelCase   :						Tuple												=  orig_key.replace(f'transformer_{layer_num}'    ,    f'encoder.layer.{layer_num}'				)
						if "mha.attn" in orig_key:
												_UpperCamelCase   :						List[Any]												=  orig_key.replace('mha.attn'    ,    'attention.self'				)
						if "mha" in orig_key:
												_UpperCamelCase   :						Union[str, Any]												=  orig_key.replace('mha'    ,    'attention'				)
						if "W_q" in orig_key:
												_UpperCamelCase   :						Union[str, Any]												=  orig_key.replace('W_q'    ,    'self.query'				)
						if "W_k" in orig_key:
												_UpperCamelCase   :						List[Any]												=  orig_key.replace('W_k'    ,    'self.key'				)
						if "W_v" in orig_key:
												_UpperCamelCase   :						List[Any]												=  orig_key.replace('W_v'    ,    'self.value'				)
						if "ff1" in orig_key:
												_UpperCamelCase   :						Optional[Any]												=  orig_key.replace('ff1'    ,    'intermediate.dense'				)
						if "ff2" in orig_key:
												_UpperCamelCase   :						List[str]												=  orig_key.replace('ff2'    ,    'output.dense'				)
						if "ff" in orig_key:
												_UpperCamelCase   :						Union[str, Any]												=  orig_key.replace('ff'    ,    'output.dense'				)
						if "mlm_class" in orig_key:
												_UpperCamelCase   :						Tuple												=  orig_key.replace('mlm.mlm_class'    ,    'cls.predictions.decoder'				)
						if "mlm" in orig_key:
												_UpperCamelCase   :						int												=  orig_key.replace('mlm'    ,    'cls.predictions.transform'				)
						if "cls" not in orig_key:
												_UpperCamelCase   :						Optional[int]												=  'yoso.' + orig_key

						return orig_key






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_				):
						for key in orig_state_dict.copy().keys():
												_UpperCamelCase   :						Any												=  orig_state_dict.pop(UpperCAmelCase_				)

												if ("pooler" in key) or ("sen_class" in key):
																		continue
												else:
																		_UpperCamelCase   :						Union[str, Any]												=  val

						_UpperCamelCase   :						Any												=  orig_state_dict['cls.predictions.decoder.bias']
						_UpperCamelCase   :						Union[str, Any]												=  torch.arange(UpperCAmelCase_				).expand((1, -1)				) + 2

						return orig_state_dict






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_    ,    UpperCAmelCase_				):
						_UpperCamelCase   :						List[Any]												=  torch.load(UpperCAmelCase_    ,    map_location='cpu'				)['model_state_dict']
						_UpperCamelCase   :						List[str]												=  YosoConfig.from_json_file(UpperCAmelCase_				)
						_UpperCamelCase   :						Union[str, Any]												=  YosoForMaskedLM(UpperCAmelCase_				)

						_UpperCamelCase   :						Tuple												=  convert_checkpoint_helper(config.max_position_embeddings    ,    UpperCAmelCase_				)

						print(model.load_state_dict(UpperCAmelCase_				)				)
						model.eval()
						model.save_pretrained(UpperCAmelCase_				)

						print(f'Checkpoint successfuly converted. Model saved at {pytorch_dump_path}'				)


if __name__ == "__main__":
					snake_case_					:      int    			=    argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '--pytorch_model_path', default=None, type=str, required=True, help='Path to YOSO pytorch checkpoint.'
					)
					parser.add_argument(
					    '--config_file',
					    default=None,
					    type=str,
					    required=True,
					    help='The json file for YOSO model config.',
					)
					parser.add_argument(
					    '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
					)
					snake_case_					:      List[Any]    			=    parser.parse_args()
					convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)


