
import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import (
        MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
        MODEL_FOR_QUESTION_ANSWERING_MAPPING,
        MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
        MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
        LayoutLMvaConfig,
        LayoutLMvaForQuestionAnswering,
        LayoutLMvaForSequenceClassification,
        LayoutLMvaForTokenClassification,
        LayoutLMvaModel,
    )
    from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import LayoutLMvaImageProcessor




class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Any			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: List[str]=2			,							UpperCamelCase__			: Tuple=3			,							UpperCamelCase__			: Optional[Any]=4			,							UpperCamelCase__			: Tuple=2			,							UpperCamelCase__			: Dict=7			,							UpperCamelCase__			: Union[str, Any]=True			,							UpperCamelCase__			: Dict=True			,							UpperCamelCase__			: List[Any]=True			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: List[Any]=99			,							UpperCamelCase__			: Dict=36			,							UpperCamelCase__			: Dict=3			,							UpperCamelCase__			: Optional[Any]=4			,							UpperCamelCase__			: Union[str, Any]=37			,							UpperCamelCase__			: List[str]="gelu"			,							UpperCamelCase__			: List[Any]=0.1			,							UpperCamelCase__			: List[Any]=0.1			,							UpperCamelCase__			: Optional[Any]=512			,							UpperCamelCase__			: List[str]=16			,							UpperCamelCase__			: Union[str, Any]=2			,							UpperCamelCase__			: str=0.02			,							UpperCamelCase__			: Dict=6			,							UpperCamelCase__			: Optional[Any]=6			,							UpperCamelCase__			: Optional[Any]=3			,							UpperCamelCase__			: Optional[Any]=4			,							UpperCamelCase__			: Any=None			,							UpperCamelCase__			: Tuple=1000			,							)			->	Optional[int]:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       num_channels
    __magic_name__				     =       image_size
    __magic_name__				     =       patch_size
    __magic_name__				     =       text_seq_length
    __magic_name__				     =       is_training
    __magic_name__				     =       use_input_mask
    __magic_name__				     =       use_token_type_ids
    __magic_name__				     =       use_labels
    __magic_name__				     =       vocab_size
    __magic_name__				     =       hidden_size
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       num_attention_heads
    __magic_name__				     =       intermediate_size
    __magic_name__				     =       hidden_act
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       max_position_embeddings
    __magic_name__				     =       type_vocab_size
    __magic_name__				     =       type_sequence_label_size
    __magic_name__				     =       initializer_range
    __magic_name__				     =       coordinate_size
    __magic_name__				     =       shape_size
    __magic_name__				     =       num_labels
    __magic_name__				     =       num_choices
    __magic_name__				     =       scope
    __magic_name__				     =       range_bbox

    # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
    __magic_name__				     =       text_seq_length
    __magic_name__				     =       (image_size // patch_size) ** 2 + 1
    __magic_name__				     =       self.text_seq_length + self.image_seq_length
  def 							_lowercase							( self			: int    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       ids_tensor([self.batch_size, self.text_seq_length]			,							self.vocab_size    )

    __magic_name__				     =       ids_tensor([self.batch_size, self.text_seq_length, 4]			,							self.range_bbox    )
    # Ensure that bbox is legal
    for i in range(bbox.shape[0]    ):
      for j in range(bbox.shape[1]    ):
        if bbox[i, j, 3] < bbox[i, j, 1]:
          __magic_name__				     =       bbox[i, j, 3]
          __magic_name__				     =       bbox[i, j, 1]
          __magic_name__				     =       t
        if bbox[i, j, 2] < bbox[i, j, 0]:
          __magic_name__				     =       bbox[i, j, 2]
          __magic_name__				     =       bbox[i, j, 0]
          __magic_name__				     =       t

    __magic_name__				     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

    __magic_name__				     =       None
    if self.use_input_mask:
      __magic_name__				     =       random_attention_mask([self.batch_size, self.text_seq_length]    )

    __magic_name__				     =       None
    if self.use_token_type_ids:
      __magic_name__				     =       ids_tensor([self.batch_size, self.text_seq_length]			,							self.type_vocab_size    )

    __magic_name__				     =       None
    __magic_name__				     =       None
    if self.use_labels:
      __magic_name__				     =       ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
      __magic_name__				     =       ids_tensor([self.batch_size, self.text_seq_length]			,							self.num_labels    )

    __magic_name__				     =       LayoutLMvaConfig(
        vocab_size=self.vocab_size			,							hidden_size=self.hidden_size			,							num_hidden_layers=self.num_hidden_layers			,							num_attention_heads=self.num_attention_heads			,							intermediate_size=self.intermediate_size			,							hidden_act=self.hidden_act			,							hidden_dropout_prob=self.hidden_dropout_prob			,							attention_probs_dropout_prob=self.attention_probs_dropout_prob			,							max_position_embeddings=self.max_position_embeddings			,							type_vocab_size=self.type_vocab_size			,							initializer_range=self.initializer_range			,							coordinate_size=self.coordinate_size			,							shape_size=self.shape_size			,							input_size=self.image_size			,							patch_size=self.patch_size			,							)

    return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
  def 							_lowercase							( self			: List[Any]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Dict    )			->	Optional[int]:







    """simple docstring"""






    __magic_name__				     =       LayoutLMvaModel(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()

    # text + image
    __magic_name__				     =       model(UpperCamelCase__			,							pixel_values=UpperCamelCase__    )
    __magic_name__				     =       model(
        UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__    )
    __magic_name__				     =       model(UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__			,							token_type_ids=UpperCamelCase__    )
    __magic_name__				     =       model(UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__    )

    self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)    )

    # text only
    __magic_name__				     =       model(UpperCamelCase__    )
    self.parent.assertEqual(
        result.last_hidden_state.shape			,							(self.batch_size, self.text_seq_length, self.hidden_size)    )

    # image only
    __magic_name__				     =       model(pixel_values=UpperCamelCase__    )
    self.parent.assertEqual(
        result.last_hidden_state.shape			,							(self.batch_size, self.image_seq_length, self.hidden_size)    )
  def 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Dict    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       self.num_labels
    __magic_name__				     =       LayoutLMvaForSequenceClassification(UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(
        UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__			,							)
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )
  def 							_lowercase							( self			: List[str]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: str			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Tuple    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       self.num_labels
    __magic_name__				     =       LayoutLMvaForTokenClassification(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(
        UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__			,							)
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.text_seq_length, self.num_labels)    )
  def 							_lowercase							( self			: Any			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: int			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Optional[int]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       LayoutLMvaForQuestionAnswering(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(
        UpperCamelCase__			,							bbox=UpperCamelCase__			,							pixel_values=UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							start_positions=UpperCamelCase__			,							end_positions=UpperCamelCase__			,							)
    self.parent.assertEqual(result.start_logits.shape			,							(self.batch_size, self.seq_length)    )
    self.parent.assertEqual(result.end_logits.shape			,							(self.batch_size, self.seq_length)    )





  def 							_lowercase							( self			: int    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       self.prepare_config_and_inputs()
    (
        (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    (
        __magic_name__
    )     ,    
    )				     =       config_and_inputs
    __magic_name__				     =       {
        """input_ids""": input_ids,
        """bbox""": bbox,
        """pixel_values""": pixel_values,
        """token_type_ids""": token_type_ids,
        """attention_mask""": input_mask,
    }
    return config, inputs_dict







@require_torch
class        UpperCAmelCase_			( _A  ,       _A  ,       unittest.TestCase     ):


  '''simple docstring'''







  a__           =		False
  a__           =		False
  a__           =		False

  a__           =		(
      (
          LayoutLMvaModel,
          LayoutLMvaForSequenceClassification,
          LayoutLMvaForTokenClassification,
          LayoutLMvaForQuestionAnswering,
      )
      if is_torch_available()
      else ()
  )
  a__           =		(
      {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
      if is_torch_available()
      else {}
  )
  def 							_lowercase							( self			: Any			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Optional[int]    )			->	List[str]:







    """simple docstring"""






    return True
  def 							_lowercase							( self			: Optional[Any]    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       LayoutLMvaModelTester(self    )
    __magic_name__				     =       ConfigTester(self			,							config_class=UpperCamelCase__			,							hidden_size=37    )
  def 							_lowercase							( self			: Tuple			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Union[str, Any]=False    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       copy.deepcopy(UpperCamelCase__    )
    if model_class in get_values(UpperCamelCase__    ):
      __magic_name__				     =       {
          k: v.unsqueeze(1    ).expand(-1			,							self.model_tester.num_choices			,							-1    ).contiguous()
          if isinstance(UpperCamelCase__			,							torch.Tensor    ) and v.ndim > 1
          else v
          for k, v in inputs_dict.items()
      }
    if return_labels:
      if model_class in get_values(UpperCamelCase__    ):
        __magic_name__				     =       torch.ones(self.model_tester.batch_size			,							dtype=torch.long			,							device=UpperCamelCase__    )
      elif model_class in get_values(UpperCamelCase__    ):
        __magic_name__				     =       torch.zeros(
            self.model_tester.batch_size			,							dtype=torch.long			,							device=UpperCamelCase__    )
        __magic_name__				     =       torch.zeros(
            self.model_tester.batch_size			,							dtype=torch.long			,							device=UpperCamelCase__    )
      elif model_class in [
          *get_values(UpperCamelCase__    ),
      ]:
        __magic_name__				     =       torch.zeros(
            self.model_tester.batch_size			,							dtype=torch.long			,							device=UpperCamelCase__    )
      elif model_class in [
          *get_values(UpperCamelCase__    ),
      ]:
        __magic_name__				     =       torch.zeros(
            (self.model_tester.batch_size, self.model_tester.text_seq_length)			,							dtype=torch.long			,							device=UpperCamelCase__			,							)

    return inputs_dict
  def 							_lowercase							( self			: Dict    )			->	Union[str, Any]:







    """simple docstring"""






    self.config_tester.run_common_tests()
  def 							_lowercase							( self			: Any    )			->	Optional[int]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
      __magic_name__				     =       type
      self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__    )
  def 							_lowercase							( self			: str    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__    )
  def 							_lowercase							( self			: Tuple    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__    )





  @slow
  def 							_lowercase							( self			: int    )			->	Optional[Any]:







    """simple docstring"""






    for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __magic_name__				     =       LayoutLMvaModel.from_pretrained(UpperCamelCase__    )
      self.assertIsNotNone(UpperCamelCase__    )







def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
  return image





@require_torch
class        UpperCAmelCase_			( unittest.TestCase     ):


  '''simple docstring'''







  @cached_property
  def 							_lowercase							( self			: Dict    )			->	int:







    """simple docstring"""






    return LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase__    ) if is_vision_available() else None





  @slow
  def 							_lowercase							( self			: str    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""    ).to(UpperCamelCase__    )

    __magic_name__				     =       self.default_image_processor
    __magic_name__				     =       prepare_img()
    __magic_name__				     =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""    ).pixel_values.to(UpperCamelCase__    )

    __magic_name__				     =       torch.tensor([[1, 2]]    )
    __magic_name__				     =       torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]    ).unsqueeze(0    )

    # forward pass
    __magic_name__				     =       model(
        input_ids=input_ids.to(UpperCamelCase__    )			,							bbox=bbox.to(UpperCamelCase__    )			,							pixel_values=pixel_values.to(UpperCamelCase__    )			,							)

    # verify the logits
    __magic_name__				     =       torch.Size((1, 199, 768)    )
    self.assertEqual(outputs.last_hidden_state.shape			,							UpperCamelCase__    )

    __magic_name__				     =       torch.tensor(
        [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]    ).to(UpperCamelCase__    )

    self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]			,							UpperCamelCase__			,							atol=1E-4    )    )





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

def 						_UpperCAmelCase				(			SCREAMING_SNAKE_CASE__			:					List[Any]			,     SCREAMING_SNAKE_CASE__			:					List[Any]				):
     __UpperCamelCase    							=np.argmax(SCREAMING_SNAKE_CASE__			,     axis=1				)
     return np.sum(outputs == labels				)

def 						_UpperCAmelCase				(			SCREAMING_SNAKE_CASE__			:					List[Any]				):
     with open(SCREAMING_SNAKE_CASE__			,     encoding='utf_8'				) as f:
          __UpperCamelCase    							=csv.reader(SCREAMING_SNAKE_CASE__				)
          __UpperCamelCase    							=[]
          next(SCREAMING_SNAKE_CASE__				)  # skip the first line
          for line in tqdm(SCREAMING_SNAKE_CASE__				):
               output.append((' '.join(line[1:5]				), line[5], line[6], int(line[-1]				) - 1)				)
     return output

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

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

     parser.add_argument('--server_ip'			,     type=SCREAMING_SNAKE_CASE__			,     default=''			,     help='Can be used for distant debugging.'				)
     parser.add_argument('--server_port'			,     type=SCREAMING_SNAKE_CASE__			,     default=''			,     help='Can be used for distant debugging.'				)
     __UpperCamelCase    							=parser.parse_args()
     print(SCREAMING_SNAKE_CASE__				)

     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=SCREAMING_SNAKE_CASE__				)
          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    							=torch.device('cuda' if torch.cuda.is_available() else 'cpu'				)
     __UpperCamelCase    							=torch.cuda.device_count()
     logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__			,     SCREAMING_SNAKE_CASE__				)				)

     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    							=['_start_', '_delimiter_', '_classify_']
     __UpperCamelCase    							=OpenAIGPTTokenizer.from_pretrained(args.model_name				)
     tokenizer.add_tokens(SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name				)
     model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__				)				)
     model.to(SCREAMING_SNAKE_CASE__				)

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

     logger.info('Encoding dataset...'				)
     __UpperCamelCase    							=load_rocstories_dataset(args.train_dataset				)
     __UpperCamelCase    							=load_rocstories_dataset(args.eval_dataset				)
     __UpperCamelCase    							=(train_dataset, eval_dataset)
     __UpperCamelCase    							=tokenize_and_encode(SCREAMING_SNAKE_CASE__				)

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

     # Prepare inputs tensors and dataloaders
     __UpperCamelCase    							=pre_process_datasets(SCREAMING_SNAKE_CASE__			,     SCREAMING_SNAKE_CASE__			,     SCREAMING_SNAKE_CASE__			,     *SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase							,      __UpperCamelCase    							=tensor_datasets[0], tensor_datasets[1]

     __UpperCamelCase    							=TensorDataset(*SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=RandomSampler(SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=DataLoader(SCREAMING_SNAKE_CASE__			,     sampler=SCREAMING_SNAKE_CASE__			,     batch_size=args.train_batch_size				)

     __UpperCamelCase    							=TensorDataset(*SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=SequentialSampler(SCREAMING_SNAKE_CASE__				)
     __UpperCamelCase    							=DataLoader(SCREAMING_SNAKE_CASE__			,     sampler=SCREAMING_SNAKE_CASE__			,     batch_size=args.eval_batch_size				)

     # Prepare optimizer
     if args.do_train:
          if args.max_steps > 0:
               __UpperCamelCase    							=args.max_steps
               __UpperCamelCase    							=args.max_steps // (len(SCREAMING_SNAKE_CASE__				) // args.gradient_accumulation_steps) + 1
          else:
               __UpperCamelCase    							=len(SCREAMING_SNAKE_CASE__				) // args.gradient_accumulation_steps * args.num_train_epochs

          __UpperCamelCase    							=list(model.named_parameters()				)
          __UpperCamelCase    							=['bias', 'LayerNorm.bias', 'LayerNorm.weight']
          __UpperCamelCase    							=[
              {
                  '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    							=AdamW(SCREAMING_SNAKE_CASE__			,     lr=args.learning_rate			,     eps=args.adam_epsilon				)
          __UpperCamelCase    							=get_linear_schedule_with_warmup(
              SCREAMING_SNAKE_CASE__			,     num_warmup_steps=args.warmup_steps			,     num_training_steps=SCREAMING_SNAKE_CASE__				)

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

    # Save a trained model
     if args.do_train:
          # Save a trained model, configuration and tokenizer
          __UpperCamelCase    							=model.module if hasattr(SCREAMING_SNAKE_CASE__			,     'module'				) else model  # Only save the model itself

          # If we save using the predefined names, we can load using `from_pretrained`
          __UpperCamelCase    							=os.path.join(args.output_dir			,     SCREAMING_SNAKE_CASE__				)
          __UpperCamelCase    							=os.path.join(args.output_dir			,     SCREAMING_SNAKE_CASE__				)

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

          # Load a trained model and vocabulary that you have fine-tuned
          __UpperCamelCase    							=OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir				)
          __UpperCamelCase    							=OpenAIGPTTokenizer.from_pretrained(args.output_dir				)
          model.to(SCREAMING_SNAKE_CASE__				)

     if args.do_eval:
          model.eval()
          __UpperCamelCase							,      __UpperCamelCase    							=0, 0
          __UpperCamelCase							,      __UpperCamelCase    							=0, 0
          for batch in tqdm(SCREAMING_SNAKE_CASE__			,     desc='Evaluating'				):
               __UpperCamelCase    							=tuple(t.to(SCREAMING_SNAKE_CASE__				) for t in batch				)
               __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase    							=batch
               with torch.no_grad():
                    __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase    							=model(
                        SCREAMING_SNAKE_CASE__			,     mc_token_ids=SCREAMING_SNAKE_CASE__			,     lm_labels=SCREAMING_SNAKE_CASE__			,     mc_labels=SCREAMING_SNAKE_CASE__				)

               __UpperCamelCase    							=mc_logits.detach().cpu().numpy()
               __UpperCamelCase    							=mc_labels.to('cpu'				).numpy()
               __UpperCamelCase    							=accuracy(SCREAMING_SNAKE_CASE__			,     SCREAMING_SNAKE_CASE__				)

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

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

          __UpperCamelCase    							=eval_loss / nb_eval_steps
          __UpperCamelCase    							=eval_accuracy / nb_eval_examples
          __UpperCamelCase    							=tr_loss / nb_tr_steps if args.do_train else None
          __UpperCamelCase    							={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

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


if __name__ == "__main__":
   main()





