


'''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
)
__magic_name__			=      logging.getLogger(__name__)




def      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]							,						lowerCamelCase  :      Any):
      A_						:  List[Any]          =				np.argmax(lowerCamelCase							,						axis=1)
      return np.sum(outputs == labels)




def      lowerCamelCase					(      lowerCamelCase  :      List[str]):
      with open(lowerCamelCase							,						encoding="""utf_8""") as f:
            A_						:  str          =				csv.reader(lowerCamelCase)
            A_						:  Tuple          =				[]
            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      lowerCamelCase					(      lowerCamelCase  :      Optional[int]							,						lowerCamelCase  :      Dict							,						lowerCamelCase  :      str							,						lowerCamelCase  :      Any							,						lowerCamelCase  :      Optional[Any]							,						lowerCamelCase  :      Dict):
      A_						:  int          =				[]
      for dataset in encoded_datasets:
            A_						:  int          =				len(lowerCamelCase)
            A_						:  Dict          =				np.zeros((n_batch, 2, input_len)							,						dtype=np.intaa)
            A_						:  List[str]          =				np.zeros((n_batch, 2)							,						dtype=np.intaa)
            A_						:  List[str]          =				np.full((n_batch, 2, input_len)							,						fill_value=-100							,						dtype=np.intaa)
            A_						:  Union[str, Any]          =				np.zeros((n_batch,)							,						dtype=np.intaa)
            for (
                i,
                (story, conta, conta, mc_label),
            ) in enumerate(lowerCamelCase):
                  A_						:  List[Any]          =				[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  A_						:  Union[str, Any]          =				[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  A_						:  Dict          =				with_conta
                  A_						:  Dict          =				with_conta
                  A_						:  str          =				len(lowerCamelCase) - 1
                  A_						:  Any          =				len(lowerCamelCase) - 1
                  A_						:  Optional[Any]          =				with_conta
                  A_						:  Dict          =				with_conta
                  A_						:  Optional[Any]          =				mc_label
            A_						:  List[str]          =				(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      lowerCamelCase					(      ):
      A_						:  List[Any]          =				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.""")
      A_						:  str          =				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)

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

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

      # Prepare inputs tensors and dataloaders
      A_						:  Dict          =				pre_process_datasets(lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase							,						*lowerCamelCase)
      A_   ,					A_						:  Optional[Any]          =				tensor_datasets[0], tensor_datasets[1]

      A_						:  List[Any]          =				TensorDataset(*lowerCamelCase)
      A_						:  Tuple          =				RandomSampler(lowerCamelCase)
      A_						:  Any          =				DataLoader(lowerCamelCase							,						sampler=lowerCamelCase							,						batch_size=args.train_batch_size)

      A_						:  List[Any]          =				TensorDataset(*lowerCamelCase)
      A_						:  Tuple          =				SequentialSampler(lowerCamelCase)
      A_						:  int          =				DataLoader(lowerCamelCase							,						sampler=lowerCamelCase							,						batch_size=args.eval_batch_size)

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

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

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

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

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

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

            A_						:  Tuple          =				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()




'''simple docstring'''


import json
import os
from collections import Counter

import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from torch import nn
from torch.utils.data import Dataset


__magic_name__			=      {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)}



class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Dict	,_a :       Dict ):

        '''simple docstring'''




        super().__init__()
        A_						:  List[str]          =				torchvision.models.resnetaaa(pretrained=_a )
        A_						:  int          =				list(model.children() )[:-2]
        A_						:  int          =				nn.Sequential(*_a )
        A_						:  Optional[int]          =				nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] )






  def        _a							(							self :       str	,_a :       Optional[int] ):

        '''simple docstring'''




        A_						:  Tuple          =				self.pool(self.model(_a ) )
        A_						:  Any          =				torch.flatten(_a	,start_dim=2 )
        A_						:  str          =				out.transpose(1	,2 ).contiguous()
        return out  # BxNx2048







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  def __init__(							self :       int	,_a :       Optional[Any]	,_a :       Optional[Any]	,_a :       Dict	,_a :       Dict	,_a :       Optional[Any] ):

        '''simple docstring'''




        A_						:  Dict          =				[json.loads(_a ) for l in open(_a )]
        A_						:  Optional[int]          =				os.path.dirname(_a )
        A_						:  Optional[Any]          =				tokenizer
        A_						:  Optional[Any]          =				labels
        A_						:  List[Any]          =				len(_a )
        A_						:  str          =				max_seq_length

        A_						:  str          =				transforms






  def __len__(							self :       str ):

        '''simple docstring'''




        return len(self.data )






  def __getitem__(							self :       Tuple	,_a :       Optional[Any] ):

        '''simple docstring'''




        A_						:  Optional[int]          =				torch.LongTensor(self.tokenizer.encode(self.data[index]["""text"""]	,add_special_tokens=_a ) )
        A_   ,					A_   ,					A_						:  Dict          =				sentence[0], sentence[1:-1], sentence[-1]
        A_						:  Optional[int]          =				sentence[: self.max_seq_length]

        A_						:  Any          =				torch.zeros(self.n_classes )
        A_						:  Tuple          =				1

        A_						:  Optional[Any]          =				Image.open(os.path.join(self.data_dir	,self.data[index]["""img"""] ) ).convert("""RGB""" )
        A_						:  Union[str, Any]          =				self.transforms(_a )

        return {
            "image_start_token": start_token,
            "image_end_token": end_token,
            "sentence": sentence,
            "image": image,
            "label": label,
        }






  def        _a							(							self :       List[Any] ):

        '''simple docstring'''




        A_						:  str          =				Counter()
        for row in self.data:
              label_freqs.update(row["""label"""] )
        return label_freqs







def      lowerCamelCase					(      lowerCamelCase  :      str):
      A_						:  List[Any]          =				[len(row["""sentence"""]) for row in batch]
      A_   ,					A_						:  Dict          =				len(lowerCamelCase), max(lowerCamelCase)

      A_						:  Optional[int]          =				torch.zeros(lowerCamelCase							,						lowerCamelCase							,						dtype=torch.long)
      A_						:  Tuple          =				torch.zeros(lowerCamelCase							,						lowerCamelCase							,						dtype=torch.long)

      for i_batch, (input_row, length) in enumerate(zip(lowerCamelCase							,						lowerCamelCase)):
            A_						:  str          =				input_row["""sentence"""]
            A_						:  Tuple          =				1

      A_						:  int          =				torch.stack([row["""image"""] for row in batch])
      A_						:  str          =				torch.stack([row["""label"""] for row in batch])
      A_						:  List[Any]          =				torch.stack([row["""image_start_token"""] for row in batch])
      A_						:  Tuple          =				torch.stack([row["""image_end_token"""] for row in batch])

      return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor




def      lowerCamelCase					(      ):
      return [
          "Crime",
          "Drama",
          "Thriller",
          "Action",
          "Comedy",
          "Romance",
          "Documentary",
          "Short",
          "Mystery",
          "History",
          "Family",
          "Adventure",
          "Fantasy",
          "Sci-Fi",
          "Western",
          "Horror",
          "Sport",
          "War",
          "Music",
          "Musical",
          "Animation",
          "Biography",
          "Film-Noir",
      ]






def      lowerCamelCase					(      ):
      return transforms.Compose(
          [
              transforms.Resize(256),
              transforms.CenterCrop(224),
              transforms.ToTensor(),
              transforms.Normalize(
                  mean=[0.4677_7044, 0.4453_1429, 0.4066_1017]							,						std=[0.1222_1994, 0.1214_5835, 0.1438_0469]							,						),
          ])
