
"""simple docstring"""




import json
import os
from typing import Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase__							=				logging.get_logger(__name__)

lowerCAmelCase__							=				{
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
}

lowerCAmelCase__							=				{
    'vocab_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'},
    'merges_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'},
}

lowerCAmelCase__							=				{
    'ctrl': 256,
}

lowerCAmelCase__							=				{
    'Pregnancy': 168629,
    'Christianity': 7675,
    'Explain': 106423,
    'Fitness': 63440,
    'Saving': 63163,
    'Ask': 27171,
    'Ass': 95985,
    'Joke': 163509,
    'Questions': 45622,
    'Thoughts': 49605,
    'Retail': 52342,
    'Feminism': 164338,
    'Writing': 11992,
    'Atheism': 192263,
    'Netflix': 48616,
    'Computing': 39639,
    'Opinion': 43213,
    'Alone': 44967,
    'Funny': 58917,
    'Gaming': 40358,
    'Human': 4088,
    'India': 1331,
    'Joker': 77138,
    'Diet': 36206,
    'Legal': 11859,
    'Norman': 4939,
    'Tip': 72689,
    'Weight': 52343,
    'Movies': 46273,
    'Running': 23425,
    'Science': 2090,
    'Horror': 37793,
    'Confession': 60572,
    'Finance': 12250,
    'Politics': 16360,
    'Scary': 191985,
    'Support': 12654,
    'Technologies': 32516,
    'Teenage': 66160,
    'Event': 32769,
    'Learned': 67460,
    'Notion': 182770,
    'Wikipedia': 37583,
    'Books': 6665,
    'Extract': 76050,
    'Confessions': 102701,
    'Conspiracy': 75932,
    'Links': 63674,
    'Narcissus': 150425,
    'Relationship': 54766,
    'Relationships': 134796,
    'Reviews': 41671,
    'News': 4256,
    'Translation': 26820,
    'multilingual': 128406,
}



def        _lowerCamelCase ( __a    ):
		SCREAMING_SNAKE_CASE_						 = set()
		SCREAMING_SNAKE_CASE_						 = word[0]
		for char in word[1:]:
				pairs.add((prev_char, char)    )
				SCREAMING_SNAKE_CASE_						 = char

		SCREAMING_SNAKE_CASE_						 = set(__a    )
		return pairs





class  snake_case     (							__lowercase   ):
							UpperCAmelCase__						     =      VOCAB_FILES_NAMES
							UpperCAmelCase__						     =      PRETRAINED_VOCAB_FILES_MAP
							UpperCAmelCase__						     =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							UpperCAmelCase__						     =      CONTROL_CODES

							def __init__(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_="<unk>"       ,       **SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									super().__init__(unk_token=SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_    )

									with open(SCREAMING_SNAKE_CASE_       ,       encoding='''utf-8'''    ) as vocab_handle:
											SCREAMING_SNAKE_CASE_						 = json.load(SCREAMING_SNAKE_CASE_    )
									SCREAMING_SNAKE_CASE_						 = {v: k for k, v in self.encoder.items()}
									with open(SCREAMING_SNAKE_CASE_       ,       encoding='''utf-8'''    ) as merges_handle:
											SCREAMING_SNAKE_CASE_						 = merges_handle.read().split('''\n'''    )[1:-1]
									SCREAMING_SNAKE_CASE_						 = [tuple(merge.split()    ) for merge in merges]
									SCREAMING_SNAKE_CASE_						 = dict(zip(SCREAMING_SNAKE_CASE_       ,       range(len(SCREAMING_SNAKE_CASE_    )    )    )    )
									SCREAMING_SNAKE_CASE_						 = {}

							@property
							def _lowercase					(self    ):

									"""simple docstring"""







									return len(self.encoder    )

							def _lowercase					(self    ):

									"""simple docstring"""







									return dict(self.encoder       ,       **self.added_tokens_encoder    )

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									if token in self.cache:
											return self.cache[token]
									SCREAMING_SNAKE_CASE_						 = tuple(SCREAMING_SNAKE_CASE_    )
									SCREAMING_SNAKE_CASE_						 = tuple(list(word[:-1]    ) + [word[-1] + '''</w>''']    )
									SCREAMING_SNAKE_CASE_						 = get_pairs(SCREAMING_SNAKE_CASE_    )

									if not pairs:
											return token

									while True:
											SCREAMING_SNAKE_CASE_						 = min(SCREAMING_SNAKE_CASE_       ,       key=lambda SCREAMING_SNAKE_CASE_    : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_       ,       float('''inf'''    )    )    )
											if bigram not in self.bpe_ranks:
													break
											SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_						 = bigram
											SCREAMING_SNAKE_CASE_						 = []
											SCREAMING_SNAKE_CASE_						 = 0
											while i < len(SCREAMING_SNAKE_CASE_    ):
													try:
															SCREAMING_SNAKE_CASE_						 = word.index(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )
													except ValueError:
															new_word.extend(word[i:]    )
															break
													else:
															new_word.extend(word[i:j]    )
															SCREAMING_SNAKE_CASE_						 = j

													if word[i] == first and i < len(SCREAMING_SNAKE_CASE_    ) - 1 and word[i + 1] == second:
															new_word.append(first + second    )
															i += 2
													else:
															new_word.append(word[i]    )
															i += 1
											SCREAMING_SNAKE_CASE_						 = tuple(SCREAMING_SNAKE_CASE_    )
											SCREAMING_SNAKE_CASE_						 = new_word
											if len(SCREAMING_SNAKE_CASE_    ) == 1:
													break
											else:
													SCREAMING_SNAKE_CASE_						 = get_pairs(SCREAMING_SNAKE_CASE_    )
									SCREAMING_SNAKE_CASE_						 = '''@@ '''.join(SCREAMING_SNAKE_CASE_    )
									SCREAMING_SNAKE_CASE_						 = word[:-4]
									SCREAMING_SNAKE_CASE_						 = word
									return word

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = []

									SCREAMING_SNAKE_CASE_						 = re.findall(R'''\S+\n?'''       ,       SCREAMING_SNAKE_CASE_    )

									for token in words:
											split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_    ).split(''' '''    )    )    )
									return split_tokens

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									return self.encoder.get(SCREAMING_SNAKE_CASE_       ,       self.encoder.get(self.unk_token    )    )

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									return self.decoder.get(SCREAMING_SNAKE_CASE_       ,       self.unk_token    )

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = ''' '''.join(SCREAMING_SNAKE_CASE_    ).replace('''@@ '''       ,       ''''''    ).strip()
									return out_string







							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_ = None    ):

									"""simple docstring"""







									if not os.path.isdir(SCREAMING_SNAKE_CASE_    ):
											logger.error(f'Vocabulary path ({save_directory}) should be a directory'    )
											return
									SCREAMING_SNAKE_CASE_						 = os.path.join(
									    SCREAMING_SNAKE_CASE_       ,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']    )
									SCREAMING_SNAKE_CASE_						 = os.path.join(
									    SCREAMING_SNAKE_CASE_       ,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']    )

									with open(SCREAMING_SNAKE_CASE_       ,       '''w'''       ,       encoding='''utf-8'''    ) as f:
											f.write(json.dumps(self.encoder       ,       indent=2       ,       sort_keys=SCREAMING_SNAKE_CASE_       ,       ensure_ascii=SCREAMING_SNAKE_CASE_    ) + '''\n'''    )

									SCREAMING_SNAKE_CASE_						 = 0
									with open(SCREAMING_SNAKE_CASE_       ,       '''w'''       ,       encoding='''utf-8'''    ) as writer:
											writer.write('''#version: 0.2\n'''    )
											for bpe_tokens, token_index in sorted(self.bpe_ranks.items()       ,       key=lambda SCREAMING_SNAKE_CASE_    : kv[1]    ):
													if index != token_index:
															logger.warning(
															    f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
															    ''' Please check that the tokenizer is not corrupted!'''    )
															SCREAMING_SNAKE_CASE_						 = token_index
													writer.write(''' '''.join(SCREAMING_SNAKE_CASE_    ) + '''\n'''    )
													index += 1

									return vocab_file, merge_file

							# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
							#     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
							#     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
							#     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
							#     return ''.join(tokens_generated_so_far)

"""simple docstring"""




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

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


lowerCAmelCase__							=				logging.getLogger(__name__)



def        _lowerCamelCase ( __a,							__a    ):
		return (preds == labels).mean()





@dataclass
class  snake_case     :
							UpperCAmelCase__						     =      field(
							    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}   )
							UpperCAmelCase__						     =      field(
							    default=__lowercase       ,			metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}   )
							UpperCAmelCase__						     =      field(
							    default=__lowercase       ,			metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}   )
							UpperCAmelCase__						     =      field(
							    default=__lowercase       ,			metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}       ,			)







@dataclass
class  snake_case     :
							UpperCAmelCase__						     =      field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys()   )}   )
							UpperCAmelCase__						     =      field(metadata={'''help''': '''Should contain the data files for the task.'''}   )
							UpperCAmelCase__						     =      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__						     =      field(
							    default=__lowercase       ,			metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}   )







def        _lowerCamelCase ( ):
		# 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.

		SCREAMING_SNAKE_CASE_						 = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
		SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_						 = 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''',							__a    )

		# Set seed
		set_seed(training_args.seed    )

		try:
				SCREAMING_SNAKE_CASE_						 = processors[data_args.task_name]()
				SCREAMING_SNAKE_CASE_						 = processor.get_labels()
				SCREAMING_SNAKE_CASE_						 = len(__a    )
		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.

		SCREAMING_SNAKE_CASE_						 = AutoConfig.from_pretrained(
		    model_args.config_name if model_args.config_name else model_args.model_name_or_path,							num_labels=__a,							finetuning_task=data_args.task_name,							cache_dir=model_args.cache_dir,							)
		SCREAMING_SNAKE_CASE_						 = 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,							)
		SCREAMING_SNAKE_CASE_						 = AutoModelForMultipleChoice.from_pretrained(
		    model_args.model_name_or_path,							from_tf=bool('''.ckpt''' in model_args.model_name_or_path    ),							config=__a,							cache_dir=model_args.cache_dir,							)

		# Get datasets
		SCREAMING_SNAKE_CASE_						 = (
		    MultipleChoiceDataset(
		        data_dir=data_args.data_dir,							tokenizer=__a,							task=data_args.task_name,							max_seq_length=data_args.max_seq_length,							overwrite_cache=data_args.overwrite_cache,							mode=Split.train,							)
		    if training_args.do_train
		    else None
		)
		SCREAMING_SNAKE_CASE_						 = (
		    MultipleChoiceDataset(
		        data_dir=data_args.data_dir,							tokenizer=__a,							task=data_args.task_name,							max_seq_length=data_args.max_seq_length,							overwrite_cache=data_args.overwrite_cache,							mode=Split.dev,							)
		    if training_args.do_eval
		    else None
		)

		def compute_metrics(__a    ) -> Dict:
				SCREAMING_SNAKE_CASE_						 = np.argmax(p.predictions,							axis=1    )
				return {"acc": simple_accuracy(__a,							p.label_ids    )}

		# Data collator
		SCREAMING_SNAKE_CASE_						 = DataCollatorWithPadding(__a,							pad_to_multiple_of=8    ) if training_args.fpaa else None

		# Initialize our Trainer
		SCREAMING_SNAKE_CASE_						 = Trainer(
		    model=__a,							args=__a,							train_dataset=__a,							eval_dataset=__a,							compute_metrics=__a,							data_collator=__a,							)

		# 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
		SCREAMING_SNAKE_CASE_						 = {}
		if training_args.do_eval:
				logger.info('''*** Evaluate ***'''    )

				SCREAMING_SNAKE_CASE_						 = trainer.evaluate()

				SCREAMING_SNAKE_CASE_						 = os.path.join(training_args.output_dir,							'''eval_results.txt'''    )
				if trainer.is_world_master():
						with open(__a,							'''w'''    ) as writer:
								logger.info('''***** Eval results *****'''    )
								for key, value in result.items():
										logger.info('''  %s = %s''',							__a,							__a    )
										writer.write('''%s = %s\n''' % (key, value)    )

								results.update(__a    )

		return results



def        _lowerCamelCase ( __a    ):
		# For xla_spawn (TPUs)
		main()


if __name__ == "__main__":
						main()