

"""simple docstring"""

from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.openai.modeling_tf_openai import (
        TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFOpenAIGPTDoubleHeadsModel,
        TFOpenAIGPTForSequenceClassification,
        TFOpenAIGPTLMHeadModel,
        TFOpenAIGPTModel,
    )






class  __a				:






       def __init__(      self ,				snake_case ,				):





        """simple docstring"""

        lowerCAmelCase__      :							Union[str, Any]    =							parent
        lowerCAmelCase__      :							Optional[int]    =							13
        lowerCAmelCase__      :							Tuple    =							7
        lowerCAmelCase__      :							Any    =							True
        lowerCAmelCase__      :							Optional[int]    =							True
        lowerCAmelCase__      :							Any    =							True
        lowerCAmelCase__      :							Any    =							True
        lowerCAmelCase__      :							Optional[Any]    =							True
        lowerCAmelCase__      :							int    =							99
        lowerCAmelCase__      :							List[str]    =							32
        lowerCAmelCase__      :							Optional[Any]    =							2
        lowerCAmelCase__      :							Optional[int]    =							4
        lowerCAmelCase__      :							Optional[Any]    =							37
        lowerCAmelCase__      :							str    =							"gelu"
        lowerCAmelCase__      :							int    =							0.1
        lowerCAmelCase__      :							Union[str, Any]    =							0.1
        lowerCAmelCase__      :							List[Any]    =							512
        lowerCAmelCase__      :							Optional[Any]    =							16
        lowerCAmelCase__      :							Dict    =							2
        lowerCAmelCase__      :							List[str]    =							0.02
        lowerCAmelCase__      :							Optional[int]    =							3
        lowerCAmelCase__      :							Optional[Any]    =							4
        lowerCAmelCase__      :							List[Any]    =							None
        lowerCAmelCase__      :							Optional[Any]    =							self.vocab_size - 1






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[Any]    =							ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size      )

        lowerCAmelCase__      :							Dict    =							None
        if self.use_input_mask:
         lowerCAmelCase__      :							Tuple    =							random_attention_mask([self.batch_size, self.seq_length]      )

        lowerCAmelCase__      :							Tuple    =							None
        if self.use_token_type_ids:
         lowerCAmelCase__      :							Optional[Any]    =							ids_tensor([self.batch_size, self.seq_length] ,				self.type_vocab_size      )

        lowerCAmelCase__      :							Optional[Any]    =							None
        if self.use_mc_token_ids:
         lowerCAmelCase__      :							Optional[Any]    =							ids_tensor([self.batch_size, self.num_choices] ,				self.seq_length      )

        lowerCAmelCase__      :							Optional[Any]    =							None
        lowerCAmelCase__      :							Dict    =							None
        lowerCAmelCase__      :							Tuple    =							None
        if self.use_labels:
         lowerCAmelCase__      :							Optional[Any]    =							ids_tensor([self.batch_size] ,				self.type_sequence_label_size      )
         lowerCAmelCase__      :							Any    =							ids_tensor([self.batch_size, self.seq_length] ,				self.num_labels      )
         lowerCAmelCase__      :							Dict    =							ids_tensor([self.batch_size] ,				self.num_choices      )

        lowerCAmelCase__      :							Optional[Any]    =							OpenAIGPTConfig(
            vocab_size=self.vocab_size ,				n_embd=self.hidden_size ,				n_layer=self.num_hidden_layers ,				n_head=self.num_attention_heads ,				n_positions=self.max_position_embeddings ,				pad_token_id=self.pad_token_id ,				)

        lowerCAmelCase__      :							Optional[int]    =							ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,				2      )

        return (
            config,
            input_ids,
            input_mask,
            head_mask,
            token_type_ids,
            mc_token_ids,
            sequence_labels,
            token_labels,
            choice_labels,
        )






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				*snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[str]    =							TFOpenAIGPTModel(config=snake_case      )
        lowerCAmelCase__      :							List[str]    =							{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        lowerCAmelCase__      :							Dict    =							model(snake_case      )

        lowerCAmelCase__      :							List[Any]    =							[input_ids, input_mask]
        lowerCAmelCase__      :							List[str]    =							model(snake_case      )

        lowerCAmelCase__      :							Optional[int]    =							model(snake_case      )

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






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				*snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							Dict    =							TFOpenAIGPTLMHeadModel(config=snake_case      )
        lowerCAmelCase__      :							Optional[int]    =							{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        lowerCAmelCase__      :							Tuple    =							model(snake_case      )
        self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.vocab_size)      )






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				*snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[Any]    =							TFOpenAIGPTDoubleHeadsModel(config=snake_case      )

        lowerCAmelCase__      :							Union[str, Any]    =							tf.tile(tf.expand_dims(snake_case ,				1      ) ,				(1, self.num_choices, 1)      )
        lowerCAmelCase__      :							Optional[Any]    =							tf.tile(tf.expand_dims(snake_case ,				1      ) ,				(1, self.num_choices, 1)      )
        lowerCAmelCase__      :							Optional[Any]    =							tf.tile(tf.expand_dims(snake_case ,				1      ) ,				(1, self.num_choices, 1)      )

        lowerCAmelCase__      :							Any    =							{
            "input_ids": multiple_choice_inputs_ids,
            "mc_token_ids": mc_token_ids,
            "attention_mask": multiple_choice_input_mask,
            "token_type_ids": multiple_choice_token_type_ids,
        }
        lowerCAmelCase__      :							str    =							model(snake_case      )
        self.parent.assertEqual(
            result.logits.shape ,				(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)      )
        self.parent.assertEqual(result.mc_logits.shape ,				(self.batch_size, self.num_choices)      )






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				*snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							Optional[Any]    =							self.num_labels
        lowerCAmelCase__      :							Tuple    =							ids_tensor([self.batch_size] ,				self.type_sequence_label_size      )
        lowerCAmelCase__      :							List[Any]    =							{
            "input_ids": input_ids,
            "attention_mask": input_mask,
            "token_type_ids": token_type_ids,
            "labels": sequence_labels,
        }
        lowerCAmelCase__      :							Union[str, Any]    =							TFOpenAIGPTForSequenceClassification(snake_case      )
        lowerCAmelCase__      :							Optional[Any]    =							model(snake_case      )
        self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Dict    =							self.prepare_config_and_inputs()

        (
            lowerCAmelCase__	
        )      :							Any    =							config_and_inputs

        lowerCAmelCase__      :							List[Any]    =							{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
        return config, inputs_dict






@require_tf
class  __a				(	__magic_name__					,  __magic_name__					,  unittest.TestCase					):
       __UpperCamelCase				:			int          =	(
           (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
           if is_tf_available()
           else ()
       )
       __UpperCamelCase				:			Tuple          =	(
           (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
       )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
       __UpperCamelCase				:			str          =	(
           {
               'feature-extraction': TFOpenAIGPTModel,
               'text-classification': TFOpenAIGPTForSequenceClassification,
               'text-generation': TFOpenAIGPTLMHeadModel,
               'zero-shot': TFOpenAIGPTForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       __UpperCamelCase				:			Tuple          =	False
       __UpperCamelCase				:			Optional[Any]          =	False






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case      ):





        """simple docstring"""

        if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
         # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
         # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
         # tiny config could not be created.
         return True

        return False






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Any    =							TFOpenAIGPTModelTester(self      )
        lowerCAmelCase__      :							Union[str, Any]    =							ConfigTester(self ,				config_class=snake_case ,				n_embd=37      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        self.config_tester.run_common_tests()






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Optional[int]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_model(*snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Dict    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_lm_head(*snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Any    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_double_head(*snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Optional[Any]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case      )






       @slow
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__      :							List[Any]    =							TFOpenAIGPTModel.from_pretrained(snake_case      )
         self.assertIsNotNone(snake_case      )






@require_tf
class  __a				(	unittest.TestCase					):






       @slow
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							str    =							TFOpenAIGPTLMHeadModel.from_pretrained("openai-gpt"      )
        lowerCAmelCase__      :							Union[str, Any]    =							tf.convert_to_tensor([[481, 4_735, 544]] ,				dtype=tf.intaa      )  # the president is
        lowerCAmelCase__      :							str    =							[
            481,
            4_735,
            544,
            246,
            963,
            870,
            762,
            239,
            244,
            40_477,
            244,
            249,
            719,
            881,
            487,
            544,
            240,
            244,
            603,
            481,
        ]  # the president is a very good man. " \n " i\'m sure he is, " said the

        lowerCAmelCase__      :							Tuple    =							model.generate(snake_case ,				do_sample=snake_case      )
        self.assertListEqual(output_ids[0].numpy().tolist() ,				snake_case      )









"""simple docstring"""

import logging
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional

import numpy as np
import torch
from utils_hans import HansDataset, InputFeatures, hans_processors, hans_tasks_num_labels

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_UpperCamelCase		    =						logging.getLogger(__name__)






@dataclass
class  __a				:





       """simple docstring"""


       __UpperCamelCase				:			str          =	field(
           metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}					)
       __UpperCamelCase				:			Optional[str]          =	field(
           default=__magic_name__					,  metadata={'help': 'Pretrained config name or path if not the same as model_name'}					)
       __UpperCamelCase				:			Optional[str]          =	field(
           default=__magic_name__					,  metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}					)
       __UpperCamelCase				:			Optional[str]          =	field(
           default=__magic_name__					,  metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}					,  )






@dataclass
class  __a				:





       """simple docstring"""


       __UpperCamelCase				:			str          =	field(
           metadata={'help': 'The name of the task to train selected in the list: ' + ', '.join(hans_processors.keys()					)}					)
       __UpperCamelCase				:			str          =	field(
           metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'}					)
       __UpperCamelCase				:			int          =	field(
           default=128					,  metadata={
               'help': (
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )
           }					,  )
       __UpperCamelCase				:			bool          =	field(
           default=__magic_name__					,  metadata={'help': 'Overwrite the cached training and evaluation sets'}					)




def 			SCREAMING_SNAKE_CASE       (   lowercase__      ) ->	Dict[str, torch.Tensor]:
 lowerCAmelCase__      :							List[Any]    =							default_data_collator(lowercase__      )
 lowerCAmelCase__      :							Union[str, Any]    =							batch.pop("pairID"				,				lowercase__      )
 return batch



def 			SCREAMING_SNAKE_CASE       (   ) ->	int:
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 lowerCAmelCase__      :							str    =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )
 lowerCAmelCase__ ,	lowerCAmelCase__ ,	lowerCAmelCase__      :							List[Any]    =							parser.parse_args_into_dataclasses()

 if (
     os.path.exists(training_args.output_dir      )
     and os.listdir(training_args.output_dir      )
     and training_args.do_train
     and not training_args.overwrite_output_dir
 ):
  raise ValueError(
      F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
      " --overwrite_output_dir to overcome."      )

 # Setup logging
 logging.basicConfig(
     format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"				,				datefmt="%m/%d/%Y %H:%M:%S"				,				level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN				,				)
 logger.warning(
     "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"				,				training_args.local_rank				,				training_args.device				,				training_args.n_gpu				,				bool(training_args.local_rank != -1      )				,				training_args.fpaa				,				)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank      ):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()
 logger.info("Training/evaluation parameters %s"				,				lowercase__      )

 # Set seed
 set_seed(training_args.seed      )

 try:
  lowerCAmelCase__      :							Tuple    =							hans_tasks_num_labels[data_args.task_name]
 except KeyError:
  raise ValueError("Task not found: %s" % (data_args.task_name)      )

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 lowerCAmelCase__      :							int    =							AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path				,				num_labels=lowercase__				,				finetuning_task=data_args.task_name				,				cache_dir=model_args.cache_dir				,				)
 lowerCAmelCase__      :							Optional[int]    =							AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path				,				cache_dir=model_args.cache_dir				,				)
 lowerCAmelCase__      :							Union[str, Any]    =							AutoModelForSequenceClassification.from_pretrained(
     model_args.model_name_or_path				,				from_tf=bool(".ckpt" in model_args.model_name_or_path      )				,				config=lowercase__				,				cache_dir=model_args.cache_dir				,				)

 # Get datasets
 lowerCAmelCase__      :							Dict    =							(
     HansDataset(
         data_dir=data_args.data_dir				,				tokenizer=lowercase__				,				task=data_args.task_name				,				max_seq_length=data_args.max_seq_length				,				overwrite_cache=data_args.overwrite_cache				,				)
     if training_args.do_train
     else None
 )
 lowerCAmelCase__      :							Union[str, Any]    =							(
     HansDataset(
         data_dir=data_args.data_dir				,				tokenizer=lowercase__				,				task=data_args.task_name				,				max_seq_length=data_args.max_seq_length				,				overwrite_cache=data_args.overwrite_cache				,				evaluate=lowercase__				,				)
     if training_args.do_eval
     else None
 )

 # Initialize our Trainer
 lowerCAmelCase__      :							Any    =							Trainer(
     model=lowercase__				,				args=lowercase__				,				train_dataset=lowercase__				,				eval_dataset=lowercase__				,				data_collator=lowercase__				,				)

 # Training
 if training_args.do_train:
  trainer.train(
      model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path      ) else None      )
  trainer.save_model()
  # For convenience, we also re-save the tokenizer to the same directory,
  # so that you can share your model easily on huggingface.co/models =)
  if trainer.is_world_master():
   tokenizer.save_pretrained(training_args.output_dir      )

    # Evaluation
 if training_args.do_eval:
  logger.info("*** Evaluate ***"      )

  lowerCAmelCase__      :							Tuple    =							trainer.predict(lowercase__      )
  lowerCAmelCase__      :							Optional[Any]    =							output.predictions
  lowerCAmelCase__      :							Dict    =							np.argmax(lowercase__				,				axis=1      )

  lowerCAmelCase__      :							int    =							[ex.pairID for ex in eval_dataset]
  lowerCAmelCase__      :							Tuple    =							os.path.join(training_args.output_dir				,				"hans_predictions.txt"      )
  lowerCAmelCase__      :							Tuple    =							eval_dataset.get_labels()
  if trainer.is_world_master():
   with open(lowercase__				,				"w"      ) as writer:
    writer.write("pairID,gold_label\n"      )
    for pid, pred in zip(lowercase__				,				lowercase__      ):
     writer.write("ex" + str(lowercase__      ) + "," + label_list[int(lowercase__      )] + "\n"      )

  trainer._log(output.metrics      )



def 			SCREAMING_SNAKE_CASE       (   lowercase__      ) ->	Optional[Any]:
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
    main()






