





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



def      __lowerCamelCase   (							a_     :		Dict ,   a_     :		List[str]							)			->      Tuple:
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  np.argmax(a_ ,   axis=1							)
      return np.sum(outputs == labels							)



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



def      __lowerCamelCase   (							a_     :		str ,   a_     :		int ,   a_     :		List[str] ,   a_     :		Tuple ,   a_     :		List[str] ,   a_     :		Optional[int]							)			->      str:
      __SCREAMING_SNAKE_CASE   :Dict						=  []
      for dataset in encoded_datasets:
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  len(a_							)
            __SCREAMING_SNAKE_CASE   :Any						=  np.zeros((n_batch, 2, input_len) ,   dtype=np.intaa							)
            __SCREAMING_SNAKE_CASE   :List[Any]						=  np.zeros((n_batch, 2) ,   dtype=np.intaa							)
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  np.full((n_batch, 2, input_len) ,   fill_value=-1_00 ,   dtype=np.intaa							)
            __SCREAMING_SNAKE_CASE   :List[str]						=  np.zeros((n_batch,) ,   dtype=np.intaa							)
            for (
                i,
                (story, conta, conta, mc_label),
            ) in enumerate(a_							):
                  __SCREAMING_SNAKE_CASE   :int						=  [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  __SCREAMING_SNAKE_CASE   :Tuple						=  [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  __SCREAMING_SNAKE_CASE   :int						=  with_conta
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  with_conta
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  len(a_							) - 1
                  __SCREAMING_SNAKE_CASE   :List[str]						=  len(a_							) - 1
                  __SCREAMING_SNAKE_CASE   :int						=  with_conta
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  with_conta
                  __SCREAMING_SNAKE_CASE   :int						=  mc_label
            __SCREAMING_SNAKE_CASE   :Tuple						=  (input_ids, mc_token_ids, lm_labels, mc_labels)
            tensor_datasets.append(tuple(torch.tensor(a_							) for t in all_inputs							)							)
      return tensor_datasets



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

      parser.add_argument('''--server_ip''' ,   type=a_ ,   default='''''' ,   help='''Can be used for distant debugging.'''							)
      parser.add_argument('''--server_port''' ,   type=a_ ,   default='''''' ,   help='''Can be used for distant debugging.'''							)
      __SCREAMING_SNAKE_CASE   :List[Any]						=  parser.parse_args()
      print(a_							)

      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=a_							)
            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							)

      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''							)
      __SCREAMING_SNAKE_CASE   :Any						=  torch.cuda.device_count()
      logger.info('''device: {}, n_gpu {}'''.format(a_ ,   a_							)							)

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

      # Load and encode the datasets
      def tokenize_and_encode(a_     :		int							):
            if isinstance(a_ ,   a_							):
                  return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(a_							)							)
            elif isinstance(a_ ,   a_							):
                  return obj
            return [tokenize_and_encode(a_							) for o in obj]

      logger.info('''Encoding dataset...'''							)
      __SCREAMING_SNAKE_CASE   :Any						=  load_rocstories_dataset(args.train_dataset							)
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  load_rocstories_dataset(args.eval_dataset							)
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  (train_dataset, eval_dataset)
      __SCREAMING_SNAKE_CASE   :Dict						=  tokenize_and_encode(a_							)

      # Compute the max input length for the Transformer
      __SCREAMING_SNAKE_CASE   :int						=  model.config.n_positions // 2 - 2
      __SCREAMING_SNAKE_CASE   :Union[str, 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							)
      __SCREAMING_SNAKE_CASE   :str						=  min(a_ ,   model.config.n_positions							)  # Max size of input for the pre-trained model

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

      __SCREAMING_SNAKE_CASE   :List[str]						=  TensorDataset(*a_							)
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  RandomSampler(a_							)
      __SCREAMING_SNAKE_CASE   :List[str]						=  DataLoader(a_ ,   sampler=a_ ,   batch_size=args.train_batch_size							)

      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TensorDataset(*a_							)
      __SCREAMING_SNAKE_CASE   :Dict						=  SequentialSampler(a_							)
      __SCREAMING_SNAKE_CASE   :Any						=  DataLoader(a_ ,   sampler=a_ ,   batch_size=args.eval_batch_size							)

      # Prepare optimizer
      if args.do_train:
            if args.max_steps > 0:
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  args.max_steps
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  args.max_steps // (len(a_							) // args.gradient_accumulation_steps) + 1
            else:
                  __SCREAMING_SNAKE_CASE   :Tuple						=  len(a_							) // args.gradient_accumulation_steps * args.num_train_epochs

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

      if args.do_train:
            __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  0, 0, None
            model.train()
            for _ in trange(int(args.num_train_epochs							) ,   desc='''Epoch'''							):
                  __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  0
                  __SCREAMING_SNAKE_CASE   :int						=  0
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  tqdm(a_ ,   desc='''Training'''							)
                  for step, batch in enumerate(a_							):
                        __SCREAMING_SNAKE_CASE   :List[Any]						=  tuple(t.to(a_							) for t in batch							)
                        __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[Any]						=  batch
                        __SCREAMING_SNAKE_CASE   :Dict						=  model(a_ ,   mc_token_ids=a_ ,   lm_labels=a_ ,   mc_labels=a_							)
                        __SCREAMING_SNAKE_CASE   :List[str]						=  args.lm_coef * losses[0] + losses[1]
                        loss.backward()
                        optimizer.step()
                        scheduler.step()
                        optimizer.zero_grad()
                        tr_loss += loss.item()
                        __SCREAMING_SNAKE_CASE   :List[str]						=  (
                            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                        )
                        nb_tr_steps += 1
                        __SCREAMING_SNAKE_CASE   :Optional[Any]						=  '''Training loss: {:.2e} lr: {:.2e}'''.format(a_ ,   scheduler.get_lr()[0]							)

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

            # If we save using the predefined names, we can load using `from_pretrained`
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  os.path.join(args.output_dir ,   a_							)
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  os.path.join(args.output_dir ,   a_							)

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

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

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

                  __SCREAMING_SNAKE_CASE   :List[Any]						=  mc_logits.detach().cpu().numpy()
                  __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  mc_labels.to('''cpu'''							).numpy()
                  __SCREAMING_SNAKE_CASE   :str						=  accuracy(a_ ,   a_							)

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

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

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

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


if __name__ == "__main__":
  main()






"""simple docstring"""
from manim import *






class 					_SCREAMING_SNAKE_CASE(   A  ):




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  Rectangle(height=0.5		,width=0.5							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  Rectangle(height=0.4_6		,width=0.4_6							).set_stroke(width=0							)

             __SCREAMING_SNAKE_CASE   :List[str]						=  [mem.copy() for i in range(6							)]
             __SCREAMING_SNAKE_CASE   :List[str]						=  [mem.copy() for i in range(6							)]
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  VGroup(*SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0							)
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  VGroup(*SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0							)
             __SCREAMING_SNAKE_CASE   :Any						=  VGroup(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0							)
             __SCREAMING_SNAKE_CASE   :Tuple						=  Text('''CPU'''		,font_size=24							)
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  Group(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0.5		,aligned_edge=SCREAMING_SNAKE_CASE__							)
             cpu.move_to([-2.5, -0.5, 0]							)
             self.add(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :List[Any]						=  [mem.copy() for i in range(1							)]
             __SCREAMING_SNAKE_CASE   :str						=  VGroup(*SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0							)
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  Text('''GPU'''		,font_size=24							)
             __SCREAMING_SNAKE_CASE   :int						=  Group(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0.5		,aligned_edge=SCREAMING_SNAKE_CASE__							)
             gpu.align_to(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             gpu.set_x(gpu.get_x() - 1							)

             self.add(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  [mem.copy() for i in range(6							)]
             __SCREAMING_SNAKE_CASE   :int						=  VGroup(*SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0							)

             __SCREAMING_SNAKE_CASE   :List[Any]						=  Text('''Model'''		,font_size=24							)
             __SCREAMING_SNAKE_CASE   :int						=  Group(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							).arrange(SCREAMING_SNAKE_CASE__		,buff=0.5		,aligned_edge=SCREAMING_SNAKE_CASE__							)
             model.move_to([3, -1.0, 0]							)

             self.play(
                 Create(SCREAMING_SNAKE_CASE__		,run_time=1							)		,Create(SCREAMING_SNAKE_CASE__		,run_time=1							)		,Create(SCREAMING_SNAKE_CASE__		,run_time=1							)		,)

             __SCREAMING_SNAKE_CASE   :List[str]						=  MarkupText(
                 f'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.'''		,font_size=24		,)

             __SCREAMING_SNAKE_CASE   :List[Any]						=  Square(side_length=2.2							)
             key.move_to([-5, 2, 0]							)

             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  MarkupText(
                 f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'''		,font_size=18		,)

             key_text.move_to([-5, 2.4, 0]							)

             step_a.move_to([2, 2, 0]							)
             self.play(Write(SCREAMING_SNAKE_CASE__		,run_time=2.5							)		,Write(SCREAMING_SNAKE_CASE__							)		,Write(SCREAMING_SNAKE_CASE__							)							)

             self.add(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  []
             __SCREAMING_SNAKE_CASE   :int						=  []
             __SCREAMING_SNAKE_CASE   :List[Any]						=  []
             for i, rect in enumerate(SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :Any						=  Rectangle(height=0.4_6		,width=0.4_6							).set_stroke(width=0.0							).set_fill(SCREAMING_SNAKE_CASE__		,opacity=0.7							)
                   cpu_target.move_to(SCREAMING_SNAKE_CASE__							)
                   cpu_target.generate_target()
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  0.4_6 / 4
                   __SCREAMING_SNAKE_CASE   :Tuple						=  0.4_6 / 3

                   if i == 0:
                         cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT							)		,buff=0.0_2		,direction=SCREAMING_SNAKE_CASE__							)
                         cpu_target.target.set_x(cpu_target.target.get_x() + 0.1							)
                   elif i == 3:
                         cpu_target.target.next_to(cpu_targs[0].target		,direction=SCREAMING_SNAKE_CASE__		,buff=0.0							)
                   else:
                         cpu_target.target.next_to(cpu_targs[i - 1].target		,direction=SCREAMING_SNAKE_CASE__		,buff=0.0							)
                   cpu_targs.append(SCREAMING_SNAKE_CASE__							)

                   first_animations.append(rect.animate(run_time=0.5							).set_stroke(SCREAMING_SNAKE_CASE__							)							)
                   second_animations.append(MoveToTarget(SCREAMING_SNAKE_CASE__		,run_time=1.5							)							)

             self.play(*SCREAMING_SNAKE_CASE__							)
             self.play(*SCREAMING_SNAKE_CASE__							)

             self.wait()