


"""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


__a      			= logging.getLogger(__name__)
@dataclass
class 				lowerCamelCase							:


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   field(
							    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}			)
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}			)
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}			)
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,       )




@dataclass
class 				lowerCamelCase							:


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






def        a__			(							_UpperCamelCase			):





						"""simple docstring"""

						UpperCAmelCase__												=     default_data_collator(_UpperCamelCase			)
						UpperCAmelCase__												=     batch.pop('''pairID'''						,      _UpperCamelCase			)
						return batch






def        a__			(							):





						"""simple docstring"""

						UpperCAmelCase__												=     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
						UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__												=     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__												=     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__												=     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__												=     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__												=     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__												=     (
						    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__												=     (
						    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__												=     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__												=     trainer.predict(_UpperCamelCase			)
												UpperCAmelCase__												=     output.predictions
												UpperCAmelCase__												=     np.argmax(_UpperCamelCase						,      axis=1			)

												UpperCAmelCase__												=     [ex.pairID for ex in eval_dataset]
												UpperCAmelCase__												=     os.path.join(training_args.output_dir						,      '''hans_predictions.txt'''			)
												UpperCAmelCase__												=     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        a__			(							_UpperCamelCase			):





						"""simple docstring"""

						main()


if __name__ == "__main__":
						main()



"""simple docstring"""







import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_deberta import DebertaTokenizer


if TYPE_CHECKING:
						from transformers.pipelines.conversational import Conversation


__a      			= logging.get_logger(__name__)

__a      			= {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

__a      			= {
    "vocab_file": {
        "microsoft/deberta-base": "https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json",
        "microsoft/deberta-large": "https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json",
        "microsoft/deberta-xlarge": "https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json",
        "microsoft/deberta-base-mnli": "https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json",
        "microsoft/deberta-large-mnli": "https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json",
        "microsoft/deberta-xlarge-mnli": (
            "https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json"
        ),
    },
    "merges_file": {
        "microsoft/deberta-base": "https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt",
        "microsoft/deberta-large": "https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt",
        "microsoft/deberta-xlarge": "https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt",
        "microsoft/deberta-base-mnli": "https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt",
        "microsoft/deberta-large-mnli": "https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt",
        "microsoft/deberta-xlarge-mnli": (
            "https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt"
        ),
    },
}

__a      			= {
    "microsoft/deberta-base": 5_12,
    "microsoft/deberta-large": 5_12,
    "microsoft/deberta-xlarge": 5_12,
    "microsoft/deberta-base-mnli": 5_12,
    "microsoft/deberta-large-mnli": 5_12,
    "microsoft/deberta-xlarge-mnli": 5_12,
}

__a      			= {
    "microsoft/deberta-base": {"do_lower_case": False},
    "microsoft/deberta-large": {"do_lower_case": False},
}
class 				lowerCamelCase							(      __SCREAMING_SNAKE_CASE			):


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   VOCAB_FILES_NAMES
							SCREAMING_SNAKE_CASE              =   PRETRAINED_VOCAB_FILES_MAP
							SCREAMING_SNAKE_CASE              =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							SCREAMING_SNAKE_CASE              =   ["""input_ids""", """attention_mask""", """token_type_ids"""]
							SCREAMING_SNAKE_CASE              =   DebertaTokenizer






							def __init__(    self			:  Dict		,			lowerCamelCase_			:  Dict=None		,			lowerCamelCase_			:  Union[str, Any]=None		,			lowerCamelCase_			:  Tuple=None		,			lowerCamelCase_			:  Dict="replace"		,			lowerCamelCase_			:  List[Any]="[CLS]"		,			lowerCamelCase_			:  Optional[Any]="[SEP]"		,			lowerCamelCase_			:  List[Any]="[SEP]"		,			lowerCamelCase_			:  str="[CLS]"		,			lowerCamelCase_			:  List[str]="[UNK]"		,			lowerCamelCase_			:  Any="[PAD]"		,			lowerCamelCase_			:  Tuple="[MASK]"		,			lowerCamelCase_			:  List[str]=False		,			**lowerCamelCase_			:  List[str]		,			):
													super().__init__(
													    lowerCamelCase_		,			lowerCamelCase_		,			tokenizer_file=lowerCamelCase_		,			errors=lowerCamelCase_		,			bos_token=lowerCamelCase_		,			eos_token=lowerCamelCase_		,			unk_token=lowerCamelCase_		,			sep_token=lowerCamelCase_		,			cls_token=lowerCamelCase_		,			pad_token=lowerCamelCase_		,			mask_token=lowerCamelCase_		,			add_prefix_space=lowerCamelCase_		,			**lowerCamelCase_		,			)
													UpperCAmelCase__												=     kwargs.pop('''add_bos_token'''		,			lowerCamelCase_					)

													UpperCAmelCase__												=     json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()					)
													if pre_tok_state.get('''add_prefix_space'''		,			lowerCamelCase_					) != add_prefix_space:
																			UpperCAmelCase__												=     getattr(lowerCamelCase_		,			pre_tok_state.pop('''type'''					)					)
																			UpperCAmelCase__												=     add_prefix_space
																			UpperCAmelCase__												=     pre_tok_class(**lowerCamelCase_					)

													UpperCAmelCase__												=     add_prefix_space






							@property
							def        lowerCAmelCase  (    self			:  int					):
													if self._mask_token is None:
																			if self.verbose:
																									logger.error('''Using mask_token, but it is not set yet.'''					)
																			return None
													return str(self._mask_token					)






							@mask_token.setter
							def        lowerCAmelCase  (    self			:  Union[str, Any]		,			lowerCamelCase_			:  Union[str, Any]					):
													UpperCAmelCase__												=     AddedToken(lowerCamelCase_		,			lstrip=lowerCamelCase_		,			rstrip=lowerCamelCase_					) if isinstance(lowerCamelCase_		,			lowerCamelCase_					) else value
													UpperCAmelCase__												=     value






							def        lowerCAmelCase  (    self			:  int		,			lowerCamelCase_			:  List[int]		,			lowerCamelCase_			:  Optional[List[int]] = None					):
													if token_ids_a is None:
																			return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													UpperCAmelCase__												=     [self.cls_token_id]
													UpperCAmelCase__												=     [self.sep_token_id]
													return cls + token_ids_a + sep + token_ids_a + sep






							def        lowerCAmelCase  (    self			:  Optional[Any]		,			lowerCamelCase_			:  List[int]		,			lowerCamelCase_			:  Optional[List[int]] = None					):
													UpperCAmelCase__												=     [self.sep_token_id]
													UpperCAmelCase__												=     [self.cls_token_id]

													if token_ids_a is None:
																			return len(cls + token_ids_a + sep					) * [0]
													return len(cls + token_ids_a + sep					) * [0] + len(token_ids_a + sep					) * [1]






							def        lowerCAmelCase  (    self			:  Tuple		,			*lowerCamelCase_			:  Optional[int]		,			**lowerCamelCase_			:  Union[str, Any]					):
													UpperCAmelCase__												=     kwargs.get('''is_split_into_words'''		,			lowerCamelCase_					)
													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._batch_encode_plus(*lowerCamelCase_		,			**lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Tuple		,			*lowerCamelCase_			:  str		,			**lowerCamelCase_			:  Any					):
													UpperCAmelCase__												=     kwargs.get('''is_split_into_words'''		,			lowerCamelCase_					)

													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._encode_plus(*lowerCamelCase_		,			**lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Dict		,			lowerCamelCase_			:  str		,			lowerCamelCase_			:  Optional[str] = None					):
													UpperCAmelCase__												=     self._tokenizer.model.save(lowerCamelCase_		,			name=lowerCamelCase_					)
													return tuple(lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Optional[Any]		,			lowerCamelCase_			:  "Conversation"					):
													UpperCAmelCase__												=     []
													for is_user, text in conversation.iter_texts():
																			input_ids.extend(self.encode(lowerCamelCase_		,			add_special_tokens=lowerCamelCase_					) + [self.eos_token_id]					)

													if len(lowerCamelCase_					) > self.model_max_length:
																			UpperCAmelCase__												=     input_ids[-self.model_max_length :]
													return input_ids