





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



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase					)						->			List[Any]:
 UpperCamelCase     : str	     =       np.argmax(_lowerCAmelCase							,       axis=1					)
 return np.sum(outputs == labels					)



def 		A_    (					_lowerCAmelCase					)						->			int:
 with open(_lowerCAmelCase							,       encoding="utf_8"					) as f:
  UpperCamelCase     : Any	     =       csv.reader(_lowerCAmelCase					)
  UpperCamelCase     : List[str]	     =       []
  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 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase					)						->			List[Any]:
 UpperCamelCase     : Optional[int]	     =       []
 for dataset in encoded_datasets:
  UpperCamelCase     : List[str]	     =       len(_lowerCAmelCase					)
  UpperCamelCase     : List[Any]	     =       np.zeros((n_batch, 2, input_len)							,       dtype=np.intaa					)
  UpperCamelCase     : Dict	     =       np.zeros((n_batch, 2)							,       dtype=np.intaa					)
  UpperCamelCase     : Dict	     =       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(_lowerCAmelCase					):
   UpperCamelCase     : Tuple	     =       [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     : Dict	     =       with_conta
   UpperCamelCase     : Optional[Any]	     =       with_conta
   UpperCamelCase     : Tuple	     =       len(_lowerCAmelCase					) - 1
   UpperCamelCase     : str	     =       len(_lowerCAmelCase					) - 1
   UpperCamelCase     : Union[str, Any]	     =       with_conta
   UpperCamelCase     : Tuple	     =       with_conta
   UpperCamelCase     : int	     =       mc_label
  UpperCamelCase     : 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 		A_    (					)						->			Optional[Any]:
 UpperCamelCase     : 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=42					)
 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=16					)
 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=374					)

 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."					)
 UpperCamelCase     : Optional[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					)

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

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

 # Prepare inputs tensors and dataloaders
 UpperCamelCase     : str	     =       pre_process_datasets(_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       *_lowerCAmelCase					)
 UpperCamelCase     ,   UpperCamelCase     : Dict	     =       tensor_datasets[0], tensor_datasets[1]

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

 UpperCamelCase     : List[Any]	     =       TensorDataset(*_lowerCAmelCase					)
 UpperCamelCase     : Optional[Any]	     =       SequentialSampler(_lowerCAmelCase					)
 UpperCamelCase     : List[str]	     =       DataLoader(_lowerCAmelCase							,       sampler=_lowerCAmelCase							,       batch_size=args.eval_batch_size					)

 # Prepare optimizer
 if args.do_train:
  if args.max_steps > 0:
   UpperCamelCase     : Union[str, Any]	     =       args.max_steps
   UpperCamelCase     : Optional[Any]	     =       args.max_steps // (len(_lowerCAmelCase					) // args.gradient_accumulation_steps) + 1
  else:
   UpperCamelCase     : Optional[int]	     =       len(_lowerCAmelCase					) // args.gradient_accumulation_steps * args.num_train_epochs

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

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

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

   UpperCamelCase     : List[str]	     =       mc_logits.detach().cpu().numpy()
   UpperCamelCase     : Union[str, Any]	     =       mc_labels.to("cpu"					).numpy()
   UpperCamelCase     : List[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

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

  UpperCamelCase     : Union[str, Any]	     =       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()







from __future__ import annotations

import numpy as np
from numpy import floataa
from numpy.typing import NDArray



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase							,       )						->			list[float]:
 UpperCamelCase     ,   UpperCamelCase     : List[Any]	     =       coefficient_matrix.shape
 UpperCamelCase     ,   UpperCamelCase     : Optional[int]	     =       constant_matrix.shape

 if rowsa != colsa:
  UpperCamelCase     : List[Any]	     =       F"""Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}"""
  raise ValueError(_lowerCAmelCase					)

 if colsa != 1:
  UpperCamelCase     : Any	     =       F"""Constant matrix must be nx1 but received {rowsa}x{colsa}"""
  raise ValueError(_lowerCAmelCase					)

 if rowsa != rowsa:
  UpperCamelCase     : Tuple	     =       (
      "Coefficient and constant matrices dimensions must be nxn and nx1 but "
      F"""received {rowsa}x{colsa} and {rowsa}x{colsa}"""
  )
  raise ValueError(_lowerCAmelCase					)

 if len(_lowerCAmelCase					) != rowsa:
  UpperCamelCase     : Any	     =       (
      "Number of initial values must be equal to number of rows in coefficient "
      F"""matrix but received {len(_lowerCAmelCase					)} and {rowsa}"""
  )
  raise ValueError(_lowerCAmelCase					)

 if iterations <= 0:
  raise ValueError("Iterations must be at least 1"					)

 UpperCamelCase     : NDArray[floataa]	     =       np.concatenate(
     (coefficient_matrix, constant_matrix)							,       axis=1					)

 UpperCamelCase     ,   UpperCamelCase     : str	     =       table.shape

 strictly_diagonally_dominant(_lowerCAmelCase					)

 # Iterates the whole matrix for given number of times
 for _ in range(_lowerCAmelCase					):
  UpperCamelCase     : Optional[Any]	     =       []
  for row in range(_lowerCAmelCase					):
   UpperCamelCase     : Optional[int]	     =       0
   for col in range(_lowerCAmelCase					):
    if col == row:
     UpperCamelCase     : Union[str, Any]	     =       table[row][col]
    elif col == cols - 1:
     UpperCamelCase     : List[Any]	     =       table[row][col]
    else:
     temp += (-1) * table[row][col] * init_val[col]
   UpperCamelCase     : Dict	     =       (temp + val) / denom
   new_val.append(_lowerCAmelCase					)
  UpperCamelCase     : List[str]	     =       new_val

 return [float(_lowerCAmelCase					) for i in new_val]



def 		A_    (					_lowerCAmelCase					)						->			bool:
 UpperCamelCase     ,   UpperCamelCase     : Dict	     =       table.shape

 UpperCamelCase     : List[Any]	     =       True

 for i in range(0							,       _lowerCAmelCase					):
  UpperCamelCase     : Union[str, Any]	     =       0
  for j in range(0							,       cols - 1					):
   if i == j:
    continue
   else:
    total += table[i][j]

  if table[i][i] <= total:
   raise ValueError("Coefficient matrix is not strictly diagonally dominant"					)

 return is_diagonally_dominant


# Test Cases
if __name__ == "__main__":
    import doctest

    doctest.testmod()
