



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

def       _snake_case						(						UpperCamelCase						:		Dict			,		UpperCamelCase						:		Optional[Any]						):
 UpperCAmelCase	:					List[Any]	=	np.argmax(UpperCamelCase			,		axis=1						)
 return np.sum(outputs == labels						)

def       _snake_case						(						UpperCamelCase						:		str						):
 with open(UpperCamelCase			,		encoding="""utf_8"""						) as f:
  UpperCAmelCase	:					int	=	csv.reader(UpperCamelCase						)
  UpperCAmelCase	:					str	=	[]
  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						:		Optional[int]			,		UpperCamelCase						:		List[Any]			,		UpperCamelCase						:		Tuple			,		UpperCamelCase						:		Dict			,		UpperCamelCase						:		List[str]			,		UpperCamelCase						:		str						):
 UpperCAmelCase	:					Optional[Any]	=	[]
 for dataset in encoded_datasets:
  UpperCAmelCase	:					List[Any]	=	len(UpperCamelCase						)
  UpperCAmelCase	:					List[Any]	=	np.zeros((n_batch, 2, input_len)			,		dtype=np.intaa						)
  UpperCAmelCase	:					int	=	np.zeros((n_batch, 2)			,		dtype=np.intaa						)
  UpperCAmelCase	:					List[str]	=	np.full((n_batch, 2, input_len)			,		fill_value=-100			,		dtype=np.intaa						)
  UpperCAmelCase	:					List[str]	=	np.zeros((n_batch,)			,		dtype=np.intaa						)
  for (
      i,
      (story, conta, conta, mc_label),
  ) in enumerate(UpperCamelCase						):
   UpperCAmelCase	:					Optional[int]	=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
   UpperCAmelCase	:					List[Any]	=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
   UpperCAmelCase	:					str	=	with_conta
   UpperCAmelCase	:					Union[str, Any]	=	with_conta
   UpperCAmelCase	:					Optional[int]	=	len(UpperCamelCase						) - 1
   UpperCAmelCase	:					List[str]	=	len(UpperCamelCase						) - 1
   UpperCAmelCase	:					Union[str, Any]	=	with_conta
   UpperCAmelCase	:					Dict	=	with_conta
   UpperCAmelCase	:					Dict	=	mc_label
  UpperCAmelCase	:					Union[str, 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       _snake_case						(						):
 UpperCAmelCase	:					str	=	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."""						)
 UpperCAmelCase	:					Tuple	=	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	:					Tuple	=	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	:					Optional[int]	=	["""_start_""", """_delimiter_""", """_classify_"""]
 UpperCAmelCase	:					Tuple	=	OpenAIGPTTokenizer.from_pretrained(args.model_name						)
 tokenizer.add_tokens(UpperCamelCase						)
 UpperCAmelCase	:					str	=	tokenizer.convert_tokens_to_ids(UpperCamelCase						)
 UpperCAmelCase	:					List[Any]	=	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						:		Dict						):
  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	:					Optional[Any]	=	load_rocstories_dataset(args.train_dataset						)
 UpperCAmelCase	:					Dict	=	load_rocstories_dataset(args.eval_dataset						)
 UpperCAmelCase	:					Dict	=	(train_dataset, eval_dataset)
 UpperCAmelCase	:					Dict	=	tokenize_and_encode(UpperCamelCase						)

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

 # Prepare inputs tensors and dataloaders
 UpperCAmelCase	:					Tuple	=	pre_process_datasets(UpperCamelCase			,		UpperCamelCase			,		UpperCamelCase			,		*UpperCamelCase						)
 UpperCAmelCase	,		UpperCAmelCase	:					Optional[int]	=	tensor_datasets[0], tensor_datasets[1]

 UpperCAmelCase	:					Optional[int]	=	TensorDataset(*UpperCamelCase						)
 UpperCAmelCase	:					Optional[int]	=	RandomSampler(UpperCamelCase						)
 UpperCAmelCase	:					Optional[int]	=	DataLoader(UpperCamelCase			,		sampler=UpperCamelCase			,		batch_size=args.train_batch_size						)

 UpperCAmelCase	:					Union[str, Any]	=	TensorDataset(*UpperCamelCase						)
 UpperCAmelCase	:					Any	=	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	:					Union[str, Any]	=	args.max_steps // (len(UpperCamelCase						) // args.gradient_accumulation_steps) + 1
  else:
   UpperCAmelCase	:					Optional[int]	=	len(UpperCamelCase						) // args.gradient_accumulation_steps * args.num_train_epochs

  UpperCAmelCase	:					Any	=	list(model.named_parameters()						)
  UpperCAmelCase	:					Optional[int]	=	["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""]
  UpperCAmelCase	:					Tuple	=	[
      {
          """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	:					Dict	=	AdamW(UpperCamelCase			,		lr=args.learning_rate			,		eps=args.adam_epsilon						)
  UpperCAmelCase	:					Optional[int]	=	get_linear_schedule_with_warmup(
      UpperCamelCase			,		num_warmup_steps=args.warmup_steps			,		num_training_steps=UpperCamelCase						)

 if args.do_train:
  UpperCAmelCase	,		UpperCAmelCase	,		UpperCAmelCase	:					Any	=	0, 0, None
  model.train()
  for _ in trange(int(args.num_train_epochs						)			,		desc="""Epoch"""						):
   UpperCAmelCase	:					List[Any]	=	0
   UpperCAmelCase	:					Tuple	=	0
   UpperCAmelCase	:					str	=	tqdm(UpperCamelCase			,		desc="""Training"""						)
   for step, batch in enumerate(UpperCamelCase						):
    UpperCAmelCase	:					int	=	tuple(t.to(UpperCamelCase						) for t in batch						)
    UpperCAmelCase	,		UpperCAmelCase	,		UpperCAmelCase	,		UpperCAmelCase	:					int	=	batch
    UpperCAmelCase	:					List[str]	=	model(UpperCamelCase			,		mc_token_ids=UpperCamelCase			,		lm_labels=UpperCamelCase			,		mc_labels=UpperCamelCase						)
    UpperCAmelCase	:					Optional[Any]	=	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	:					Tuple	=	"""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[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`
  UpperCAmelCase	:					List[Any]	=	os.path.join(args.output_dir			,		UpperCamelCase						)
  UpperCAmelCase	:					List[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	:					Union[str, Any]	=	OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir						)
  UpperCAmelCase	:					Optional[Any]	=	OpenAIGPTTokenizer.from_pretrained(args.output_dir						)
  model.to(UpperCamelCase						)

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

   UpperCAmelCase	:					List[str]	=	mc_logits.detach().cpu().numpy()
   UpperCAmelCase	:					Dict	=	mc_labels.to("""cpu"""						).numpy()
   UpperCAmelCase	:					str	=	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	:					Dict	=	eval_accuracy / nb_eval_examples
  UpperCAmelCase	:					Union[str, Any]	=	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	:					Optional[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()





"""simple docstring"""
import os
from typing import List, Optional, Union

from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging


A:   str								=		logging.get_logger(__name__)

A:   List[Any]								=		{"vocab_file": "vocab.txt"}

A:   List[str]								=		{
    "vocab_file": {
        "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt",
        "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt",
    },
}

A:   Dict								=		{
    "facebook/esm2_t6_8M_UR50D": 1_0_2_4,
    "facebook/esm2_t12_35M_UR50D": 1_0_2_4,
}

def       _snake_case						(						UpperCamelCase						:		int						):
 with open(UpperCamelCase			,		"""r"""						) as f:
  UpperCAmelCase	:					int	=	f.read().splitlines()
  return [l.strip() for l in lines]



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Union[str, Any]						=						VOCAB_FILES_NAMES
   __lowerCAmelCase  :   Dict						=						PRETRAINED_VOCAB_FILES_MAP
   __lowerCAmelCase  :   List[Any]						=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __lowerCAmelCase  :   str						=						['input_ids', 'attention_mask']

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE="<unk>"      ,     _SCREAMING_SNAKE_CASE="<cls>"      ,     _SCREAMING_SNAKE_CASE="<pad>"      ,     _SCREAMING_SNAKE_CASE="<mask>"      ,     _SCREAMING_SNAKE_CASE="<eos>"      ,     **_SCREAMING_SNAKE_CASE      ,     )  ->      Any:





    '''simple docstring'''




    super().__init__(**_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Optional[Any]	=	load_vocab_file(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Optional[Any]	=	dict(enumerate(self.all_tokens						)						)
    UpperCAmelCase	:					List[str]	=	{tok: ind for ind, tok in enumerate(self.all_tokens						)}
    UpperCAmelCase	:					Any	=	unk_token
    UpperCAmelCase	:					str	=	cls_token
    UpperCAmelCase	:					int	=	pad_token
    UpperCAmelCase	:					Tuple	=	mask_token
    UpperCAmelCase	:					str	=	eos_token
    UpperCAmelCase	:					List[str]	=	self.all_tokens
    self._create_trie(self.unique_no_split_tokens						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE						)  ->      str:





    '''simple docstring'''




    return self._id_to_token.get(_SCREAMING_SNAKE_CASE      ,     self.unk_token						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    return self._token_to_id.get(_SCREAMING_SNAKE_CASE      ,     self._token_to_id.get(self.unk_token						)						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      Optional[Any]:





    '''simple docstring'''




    return text.split()

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE=False						)  ->      Union[str, Any]:





    '''simple docstring'''




    return len(self._id_to_token						)

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Dict:





    '''simple docstring'''




    return {token: i for i, token in enumerate(self.all_tokens						)}

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    return self._token_to_id.get(_SCREAMING_SNAKE_CASE      ,     self._token_to_id.get(self.unk_token						)						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE						)  ->      str:





    '''simple docstring'''




    return self._id_to_token.get(_SCREAMING_SNAKE_CASE      ,     self.unk_token						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = None						)  ->      List[int]:





    '''simple docstring'''




    UpperCAmelCase	:					Optional[Any]	=	[self.cls_token_id]
    UpperCAmelCase	:					Tuple	=	[self.eos_token_id]  # No sep token in ESM vocabulary
    if token_ids_a is None:
     if self.eos_token_id is None:
      return cls + token_ids_a
     else:
      return cls + token_ids_a + sep
    elif self.eos_token_id is None:
     raise ValueError("""Cannot tokenize multiple sequences when EOS token is not set!"""						)
    return cls + token_ids_a + sep + token_ids_a + sep  # Multiple inputs always have an EOS token

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = False						)  ->      List[int]:





    '''simple docstring'''




    if already_has_special_tokens:
     if token_ids_a is not None:
      raise ValueError(
          """You should not supply a second sequence if the provided sequence of """
          """ids is already formatted with special tokens for the model."""						)

     return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
    UpperCAmelCase	:					str	=	[1] + ([0] * len(_SCREAMING_SNAKE_CASE						)) + [1]
    if token_ids_a is not None:
     mask += [0] * len(_SCREAMING_SNAKE_CASE						) + [1]
    return mask

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Optional[int]:





    '''simple docstring'''




    UpperCAmelCase	:					Optional[int]	=	os.path.join(_SCREAMING_SNAKE_CASE      ,     (filename_prefix + """-""" if filename_prefix else """""") + """vocab.txt"""						)
    with open(_SCREAMING_SNAKE_CASE      ,     """w"""						) as f:
     f.write("""\n""".join(self.all_tokens						)						)
    return (vocab_file,)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    return self.get_vocab_size(with_added_tokens=_SCREAMING_SNAKE_CASE						)




   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = False						)  ->      int:





    '''simple docstring'''




    return super()._add_tokens(_SCREAMING_SNAKE_CASE      ,     special_tokens=_SCREAMING_SNAKE_CASE						)
