

"""simple docstring"""




import os
import tempfile
from pathlib import Path
from unittest import TestCase

import pyarrow as pa
import pytest

from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo

from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases







class        __lowercase     (      __lowerCamelCase   ):

  def 				__lowercase    (					self						:     Union[str, Any]   ,A						:     Tuple   ,A						:     Optional[int]=False      ):






   '''simple docstring'''
   UpperCAmelCase__				, UpperCAmelCase__				, UpperCAmelCase__   :					Optional[int]   				=   (
       filename_skip_take["""filename"""],
       filename_skip_take["""skip"""] if """skip""" in filename_skip_take else None,
       filename_skip_take["""take"""] if """take""" in filename_skip_take else None,
   )
   open(os.path.join(A      )   ,"""wb"""      ).close()
   UpperCAmelCase__   :					Optional[int]   				=   pa.Table.from_pydict({"""filename""": [Path(A      ).name] * 100}      )
   if take == -1:
    UpperCAmelCase__   :					Optional[Any]   				=   len(A      ) - skip
   if skip is not None and take is not None:
    UpperCAmelCase__   :					List[str]   				=   pa_table.slice(A   ,A      )
   return pa_table







class        __lowercase     (      __lowerCamelCase   ):

  def 				__lowercase    (					self						:     List[Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[int]   				=   """my_name"""
   UpperCAmelCase__   :					Tuple   				=   SplitInfo(name="""train"""   ,num_examples=100      )
   UpperCAmelCase__   :					List[Any]   				=   SplitInfo(name="""test"""   ,num_examples=100      )
   UpperCAmelCase__   :					List[Any]   				=   [train_info, test_info]
   UpperCAmelCase__   :					Optional[int]   				=   SplitDict()
   split_dict.add(A      )
   split_dict.add(A      )
   UpperCAmelCase__   :					List[Any]   				=   DatasetInfo(splits=A      )

   with tempfile.TemporaryDirectory() as tmp_dir:
    UpperCAmelCase__   :					int   				=   ReaderTest(A   ,A      )

    UpperCAmelCase__   :					List[str]   				=   """test[:33%]"""
    UpperCAmelCase__   :					Union[str, Any]   				=   Dataset(**reader.read(A   ,A   ,A      )      )
    self.assertEqual(dset["""filename"""][0]   ,f"{name}-test"      )
    self.assertEqual(dset.num_rows   ,33      )
    self.assertEqual(dset.num_columns   ,1      )

    UpperCAmelCase__   :					Optional[Any]   				=   ["""train""", """test[:33%]"""]
    UpperCAmelCase__   :					Optional[Any]   				=   [Split.TRAIN, ReadInstruction.from_spec("""test[:33%]"""      )]
    for instructions in [instructionsa, instructionsa]:
     UpperCAmelCase__   :					Any   				=   [reader.read(A   ,A   ,A      ) for instr in instructions]
     UpperCAmelCase__				, UpperCAmelCase__   :					List[Any]   				=   (Dataset(**A      ) for dataset_kwargs in datasets_kwargs)
     self.assertEqual(train_dset["""filename"""][0]   ,f"{name}-train"      )
     self.assertEqual(train_dset.num_rows   ,100      )
     self.assertEqual(train_dset.num_columns   ,1      )
     self.assertIsInstance(train_dset.split   ,A      )
     self.assertEqual(str(train_dset.split      )   ,"""train"""      )
     self.assertEqual(test_dset["""filename"""][0]   ,f"{name}-test"      )
     self.assertEqual(test_dset.num_rows   ,33      )
     self.assertEqual(test_dset.num_columns   ,1      )
     self.assertIsInstance(test_dset.split   ,A      )
     self.assertEqual(str(test_dset.split      )   ,"""test[:33%]"""      )
     del train_dset, test_dset

  def 				__lowercase    (					self						:     Union[str, Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Any   				=   """my_name"""
   UpperCAmelCase__   :					Union[str, Any]   				=   SplitInfo(name="""train"""   ,num_examples=1_000   ,shard_lengths=[100] * 10      )
   UpperCAmelCase__   :					int   				=   [train_info]
   UpperCAmelCase__   :					List[Any]   				=   SplitDict()
   split_dict.add(A      )
   UpperCAmelCase__   :					int   				=   DatasetInfo(splits=A      )

   with tempfile.TemporaryDirectory() as tmp_dir:
    UpperCAmelCase__   :					Dict   				=   ReaderTest(A   ,A      )

    UpperCAmelCase__   :					Optional[int]   				=   """train[:33%]"""
    UpperCAmelCase__   :					Tuple   				=   Dataset(**reader.read(A   ,A   ,A      )      )
    self.assertEqual(dset["""filename"""][0]   ,f"{name}-train-00000-of-00010"      )
    self.assertEqual(dset["""filename"""][-1]   ,f"{name}-train-00003-of-00010"      )
    self.assertEqual(dset.num_rows   ,330      )
    self.assertEqual(dset.num_columns   ,1      )




  def 				__lowercase    (					self						:     List[str]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   SplitInfo(name="""train"""   ,num_examples=100      )
   UpperCAmelCase__   :					Optional[int]   				=   SplitInfo(name="""test"""   ,num_examples=100      )
   UpperCAmelCase__   :					Any   				=   SplitDict()
   split_dict.add(A      )
   split_dict.add(A      )
   UpperCAmelCase__   :					str   				=   DatasetInfo(splits=A      )

   with tempfile.TemporaryDirectory() as tmp_dir:
    UpperCAmelCase__   :					Optional[int]   				=   ReaderTest(A   ,A      )

    UpperCAmelCase__   :					List[str]   				=   [
        {"""filename""": os.path.join(A   ,"""train"""      )},
        {"""filename""": os.path.join(A   ,"""test"""      ), """skip""": 10, """take""": 10},
    ]
    UpperCAmelCase__   :					Tuple   				=   Dataset(**reader.read_files(A   ,original_instructions="""train+test[10:20]"""      )      )
    self.assertEqual(dset.num_rows   ,110      )
    self.assertEqual(dset.num_columns   ,1      )
    del dset







@pytest.mark.parametrize("""in_memory"""							,      [False, True] )
def 					lowerCAmelCase  (   __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					Optional[int]   				=   arrow_file
 with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
  UpperCAmelCase__   :					List[str]   				=   ArrowReader.read_table(__UpperCamelCase							,      in_memory=__UpperCamelCase )
 assert table.shape == dataset.data.shape
 assert set(table.column_names ) == set(dataset.data.column_names )
 assert dict(table.to_pydict() ) == dict(dataset.data.to_pydict() )  # to_pydict returns OrderedDict
@pytest.mark.parametrize("""in_memory"""							,      [False, True] )
def 					lowerCAmelCase  (   __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					List[Any]   				=   arrow_file
 UpperCAmelCase__   :					Tuple   				=   ArrowReader(""""""							,      __UpperCamelCase )
 with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
  UpperCAmelCase__   :					Tuple   				=   reader.read_files([{"""filename""": filename}]							,      in_memory=__UpperCamelCase )
 assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
 UpperCAmelCase__   :					Optional[Any]   				=   dataset_kwargs["""arrow_table"""]
 assert table.shape == dataset.data.shape
 assert set(table.column_names ) == set(dataset.data.column_names )
 assert dict(table.to_pydict() ) == dict(dataset.data.to_pydict() )  # to_pydict returns OrderedDict
def 					lowerCAmelCase  (   ):
 '''simple docstring'''





 assert ReadInstruction("""train"""							,      to=10							,      unit="""abs""" ).to_spec() == "train[:10]"
 assert ReadInstruction("""train"""							,      from_=-80							,      to=10							,      unit="""%""" ).to_spec() == "train[-80%:10%]"

 UpperCAmelCase__   :					Union[str, Any]   				=   """train+test"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == spec_train_test

 UpperCAmelCase__   :					List[Any]   				=   """train[2:10]"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == spec_train_abs

 UpperCAmelCase__   :					int   				=   """train[15%:-20%]"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == spec_train_pct

 UpperCAmelCase__   :					Optional[int]   				=   """train[:10%](closest)"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == "train[:10%]"

 UpperCAmelCase__   :					List[str]   				=   """train[:10%](pct1_dropremainder)"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == spec_train_pct_rounding

 UpperCAmelCase__   :					Optional[int]   				=   """train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)"""
 assert ReadInstruction.from_spec(__UpperCamelCase ).to_spec() == spec_train_test_pct_rounding
def 					lowerCAmelCase  (   ):
 '''simple docstring'''





 UpperCAmelCase__   :					Tuple   				=   """dummy"""
 UpperCAmelCase__   :					Optional[Any]   				=   [SplitInfo(name="""train"""							,      num_examples=100 )]
 UpperCAmelCase__   :					int   				=   """train[:33%]"""
 UpperCAmelCase__   :					Optional[Any]   				=   """arrow"""
 UpperCAmelCase__   :					Optional[int]   				=   """prefix"""

 UpperCAmelCase__   :					str   				=   make_file_instructions(__UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase )
 assert isinstance(__UpperCamelCase							,      __UpperCamelCase )
 assert file_instructions.num_examples == 33
 assert file_instructions.file_instructions == [
     {"filename": os.path.join(__UpperCamelCase							,      F"{name}-train.arrow" ), "skip": 0, "take": 33}
 ]

 UpperCAmelCase__   :					Dict   				=   [SplitInfo(name="""train"""							,      num_examples=100							,      shard_lengths=[10] * 10 )]
 UpperCAmelCase__   :					int   				=   make_file_instructions(__UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase )
 assert isinstance(__UpperCamelCase							,      __UpperCamelCase )
 assert file_instructions.num_examples == 33
 assert file_instructions.file_instructions == [
     {"filename": os.path.join(__UpperCamelCase							,      F"{name}-train-00000-of-00010.arrow" ), "skip": 0, "take": -1},
     {"filename": os.path.join(__UpperCamelCase							,      F"{name}-train-00001-of-00010.arrow" ), "skip": 0, "take": -1},
     {"filename": os.path.join(__UpperCamelCase							,      F"{name}-train-00002-of-00010.arrow" ), "skip": 0, "take": -1},
     {"filename": os.path.join(__UpperCamelCase							,      F"{name}-train-00003-of-00010.arrow" ), "skip": 0, "take": 3},
 ]




@pytest.mark.parametrize("""name, expected_exception"""							,      [(None, TypeError), ("""""", ValueError)] )
def 					lowerCAmelCase  (   __UpperCamelCase							,      __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					Any   				=   [SplitInfo(name="""train"""							,      num_examples=100 )]
 UpperCAmelCase__   :					List[Any]   				=   """train"""
 UpperCAmelCase__   :					Tuple   				=   """arrow"""
 UpperCAmelCase__   :					Optional[Any]   				=   """prefix_path"""
 with pytest.raises(__UpperCamelCase ):
  UpperCAmelCase__   :					int   				=   make_file_instructions(__UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase							,      __UpperCamelCase )








"""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        __lowercase     :
  snake_case_			    =    field(
      metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}   )
  snake_case_			    =    field(
      default=__lowerCamelCase		,     metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}   )
  snake_case_			    =    field(
      default=__lowerCamelCase		,     metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}   )
  snake_case_			    =    field(
      default=__lowerCamelCase		,     metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,     )







@dataclass
class        __lowercase     :
  snake_case_			    =    field(
      metadata={"""help""": """The name of the task to train selected in the list: """ + """, """.join(hans_processors.keys()   )}   )
  snake_case_			    =    field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}   )
  snake_case_			    =    field(
      default=1_2_8		,     metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }		,     )
  snake_case_			    =    field(
      default=__lowerCamelCase		,     metadata={"""help""": """Overwrite the cached training and evaluation sets"""}   )







def 					lowerCAmelCase  (   __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					Optional[Any]   				=   default_data_collator(__UpperCamelCase )
 UpperCAmelCase__   :					List[str]   				=   batch.pop("""pairID"""							,      __UpperCamelCase )
 return batch
def 					lowerCAmelCase  (   ):
 '''simple docstring'''





 UpperCAmelCase__   :					Dict   				=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
 UpperCAmelCase__				, UpperCAmelCase__				, UpperCAmelCase__   :					Union[str, 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"""							,      __UpperCamelCase )

 # Set seed
 set_seed(training_args.seed )

 try:
  UpperCAmelCase__   :					Optional[int]   				=   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.

 UpperCAmelCase__   :					Tuple   				=   AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path							,      num_labels=__UpperCamelCase							,      finetuning_task=data_args.task_name							,      cache_dir=model_args.cache_dir							,      )
 UpperCAmelCase__   :					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							,      )
 UpperCAmelCase__   :					List[Any]   				=   AutoModelForSequenceClassification.from_pretrained(
     model_args.model_name_or_path							,      from_tf=bool(""".ckpt""" in model_args.model_name_or_path )							,      config=__UpperCamelCase							,      cache_dir=model_args.cache_dir							,      )

 # Get datasets
 UpperCAmelCase__   :					Optional[int]   				=   (
     HansDataset(
         data_dir=data_args.data_dir							,      tokenizer=__UpperCamelCase							,      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
 )
 UpperCAmelCase__   :					str   				=   (
     HansDataset(
         data_dir=data_args.data_dir							,      tokenizer=__UpperCamelCase							,      task=data_args.task_name							,      max_seq_length=data_args.max_seq_length							,      overwrite_cache=data_args.overwrite_cache							,      evaluate=__UpperCamelCase							,      )
     if training_args.do_eval
     else None
 )

 # Initialize our Trainer
 UpperCAmelCase__   :					List[Any]   				=   Trainer(
     model=__UpperCamelCase							,      args=__UpperCamelCase							,      train_dataset=__UpperCamelCase							,      eval_dataset=__UpperCamelCase							,      data_collator=__UpperCamelCase							,      )

 # 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 ***""" )

  UpperCAmelCase__   :					Optional[Any]   				=   trainer.predict(__UpperCamelCase )
  UpperCAmelCase__   :					List[str]   				=   output.predictions
  UpperCAmelCase__   :					Dict   				=   np.argmax(__UpperCamelCase							,      axis=1 )

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

  trainer._log(output.metrics )
def 					lowerCAmelCase  (   __UpperCamelCase ):
 '''simple docstring'''





 main()


if __name__ == "__main__":
      main()





