





"""simple docstring"""




import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


a						: List[Any]     	=			logging.getLogger(__name__)


@dataclass(frozen=a__						)
class        __UpperCamelCase				:
							lowerCamelCase   :					str
							lowerCamelCase   :					str
							lowerCamelCase   :					Optional[str]      					=None
							lowerCamelCase   :					Optional[str]      					=None
							lowerCamelCase   :					Optional[str]      					=None


@dataclass(frozen=a__						)
class        __UpperCamelCase				:
							lowerCamelCase   :					List[int]
							lowerCamelCase   :					Optional[List[int]]      					=None
							lowerCamelCase   :					Optional[List[int]]      					=None
							lowerCamelCase   :					Optional[Union[int, float]]      					=None
							lowerCamelCase   :					Optional[int]      					=None


if is_torch_available():
		import torch
		from torch.utils.data import Dataset


		class        __UpperCamelCase				(						a__						):
									lowerCamelCase   :					List[InputFeatures]






									def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__=False      ,					lowerCAmelCase__ = False      ,					)	-> Optional[int]:
										a      :		Union[str, Any]	=				hans_processors[task]()

										a      :		Dict	=				os.path.join(
										    lowerCAmelCase__      ,					"cached_{}_{}_{}_{}".format(
										        "dev" if evaluate else "train"      ,					tokenizer.__class__.__name__      ,					str(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					)      ,					)
										a      :		Dict	=				processor.get_labels()
										if tokenizer.__class__ in (
										    RobertaTokenizer,
										    RobertaTokenizerFast,
										    XLMRobertaTokenizer,
										    BartTokenizer,
										    BartTokenizerFast,
										):
											# HACK(label indices are swapped in RoBERTa pretrained model)
											a,       a      :		Union[str, Any]	=				label_list[2], label_list[1]
										a      :		Optional[Any]	=				label_list

										# Make sure only the first process in distributed training processes the dataset,
										# and the others will use the cache.
										a      :		int	=				cached_features_file + ".lock"
										with FileLock(lowerCAmelCase__      ):
											if os.path.exists(lowerCAmelCase__      ) and not overwrite_cache:
												logger.info(f"""Loading features from cached file {cached_features_file}"""      )
												a      :		Union[str, Any]	=				torch.load(lowerCAmelCase__      )
											else:
												logger.info(f"""Creating features from dataset file at {data_dir}"""      )

												a      :		List[Any]	=				(
												    processor.get_dev_examples(lowerCAmelCase__      ) if evaluate else processor.get_train_examples(lowerCAmelCase__      )
												)

												logger.info("Training examples: %s"      ,					len(lowerCAmelCase__      )      )
												a      :		Union[str, Any]	=				hans_convert_examples_to_features(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )
												logger.info("Saving features into cached file %s"      ,					lowerCAmelCase__      )
												torch.save(self.features      ,					lowerCAmelCase__      )






									def __len__(   self      )	-> int:
										return len(self.features      )






									def __getitem__(   self      ,					lowerCAmelCase__      )	-> InputFeatures:
										return self.features[i]






									def     __a   (   self      )	-> Optional[Any]:
										return self.label_list


if is_tf_available():
		import tensorflow as tf


		class        __UpperCamelCase				:
									lowerCamelCase   :					List[InputFeatures]






									def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 128      ,					lowerCAmelCase__=False      ,					lowerCAmelCase__ = False      ,					)	-> Dict:
										a      :		Tuple	=				hans_processors[task]()
										a      :		Union[str, Any]	=				processor.get_labels()
										if tokenizer.__class__ in (
										    RobertaTokenizer,
										    RobertaTokenizerFast,
										    XLMRobertaTokenizer,
										    BartTokenizer,
										    BartTokenizerFast,
										):
											# HACK(label indices are swapped in RoBERTa pretrained model)
											a,       a      :		List[Any]	=				label_list[2], label_list[1]
										a      :		int	=				label_list

										a      :		Dict	=				processor.get_dev_examples(lowerCAmelCase__      ) if evaluate else processor.get_train_examples(lowerCAmelCase__      )
										a      :		int	=				hans_convert_examples_to_features(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )

										def gen():
											for ex_index, ex in tqdm.tqdm(enumerate(self.features      )      ,					desc="convert examples to features"      ):
												if ex_index % 1_0000 == 0:
													logger.info("Writing example %d of %d" % (ex_index, len(lowerCAmelCase__      ))      )

												yield (
												    {
												        "example_id": 0,
												        "input_ids": ex.input_ids,
												        "attention_mask": ex.attention_mask,
												        "token_type_ids": ex.token_type_ids,
												    },
												    ex.label,
												)

										a      :		List[Any]	=				tf.data.Dataset.from_generator(
										    lowerCAmelCase__      ,					(
										        {
										            "example_id": tf.intaa,
										            "input_ids": tf.intaa,
										            "attention_mask": tf.intaa,
										            "token_type_ids": tf.intaa,
										        },
										        tf.intaa,
										    )      ,					(
										        {
										            "example_id": tf.TensorShape([]      ),
										            "input_ids": tf.TensorShape([None, None]      ),
										            "attention_mask": tf.TensorShape([None, None]      ),
										            "token_type_ids": tf.TensorShape([None, None]      ),
										        },
										        tf.TensorShape([]      ),
										    )      ,					)






									def     __a   (   self      )	-> Tuple:
										return self.dataset






									def __len__(   self      )	-> Tuple:
										return len(self.features      )






									def __getitem__(   self      ,					lowerCAmelCase__      )	-> InputFeatures:
										return self.features[i]






									def     __a   (   self      )	-> Optional[int]:
										return self.label_list


class        __UpperCamelCase				(						a__						):






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Any:
								return self._create_examples(self._read_tsv(os.path.join(lowerCAmelCase__      ,					"heuristics_train_set.txt"      )      )      ,					"train"      )






							def     __a   (   self      ,					lowerCAmelCase__      )	-> List[str]:
								return self._create_examples(self._read_tsv(os.path.join(lowerCAmelCase__      ,					"heuristics_evaluation_set.txt"      )      )      ,					"dev"      )






							def     __a   (   self      )	-> Optional[int]:
								return ["contradiction", "entailment", "neutral"]






							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Tuple:
								a      :		List[str]	=				[]
								for i, line in enumerate(lowerCAmelCase__      ):
									if i == 0:
										continue
									a      :		Union[str, Any]	=				"%s-%s" % (set_type, line[0])
									a      :		Optional[int]	=				line[5]
									a      :		List[Any]	=				line[6]
									a      :		int	=				line[7][2:] if line[7].startswith("ex"      ) else line[7]
									a      :		List[str]	=				line[0]
									examples.append(InputExample(guid=lowerCAmelCase__      ,					text_a=lowerCAmelCase__      ,					text_b=lowerCAmelCase__      ,					label=lowerCAmelCase__      ,					pairID=lowerCAmelCase__      )      )
								return examples






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    List[InputExample]    ,       _lowercase						:    List[str]    ,       _lowercase						:    int    ,       _lowercase						:    PreTrainedTokenizer    ,       ) ->List[str]:






	'''simple docstring'''






	a      :		Optional[int]	=				{label: i for i, label in enumerate(_lowercase					)}

	a      :		str	=				[]
	for ex_index, example in tqdm.tqdm(enumerate(_lowercase					)    ,       desc="convert examples to features"					):
		if ex_index % 1_0000 == 0:
			logger.info("Writing example %d" % (ex_index)					)

		a      :		List[Any]	=				tokenizer(
		    example.text_a    ,       example.text_b    ,       add_special_tokens=_lowercase    ,       max_length=_lowercase    ,       padding="max_length"    ,       truncation=_lowercase    ,       return_overflowing_tokens=_lowercase    ,       )

		a      :		Tuple	=				label_map[example.label] if example.label in label_map else 0

		a      :		Tuple	=				int(example.pairID					)

		features.append(InputFeatures(**_lowercase    ,       label=_lowercase    ,       pairID=_lowercase					)					)

	for i, example in enumerate(examples[:5]					):
		logger.info("*** Example ***"					)
		logger.info(F"""guid: {example}"""					)
		logger.info(F"""features: {features[i]}"""					)

	return features


a						: Tuple     	=			{
    '''hans''': 3,
}







a						: Dict     	=			{
    '''hans''': HansProcessor,
}









'''simple docstring'''







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCAmelCase_					:    int      	=			logging.get_logger(__name__)

lowerCAmelCase_					:    Tuple      	=			{
    'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json',
    'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json',
    'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json',
    # See all BigBird models at https://huggingface.co/models?filter=big_bird
}
class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_      ):






				"""simple docstring"""







				__a            ='big_bird'




				def __init__(  self     :					Optional[int]					,				__a     :					Dict=5_03_58					,				__a     :					str=7_68					,				__a     :					List[Any]=12					,				__a     :					List[str]=12					,				__a     :					Union[str, Any]=30_72					,				__a     :					str="gelu_new"					,				__a     :					Dict=0.1					,				__a     :					Union[str, Any]=0.1					,				__a     :					Any=40_96					,				__a     :					int=2					,				__a     :					Tuple=0.02					,				__a     :					List[Any]=1e-1_2					,				__a     :					int=True					,				__a     :					List[str]=0					,				__a     :					Tuple=1					,				__a     :					Optional[Any]=2					,				__a     :					Tuple=66					,				__a     :					str="block_sparse"					,				__a     :					Tuple=True					,				__a     :					Optional[int]=False					,				__a     :					str=64					,				__a     :					Tuple=3					,				__a     :					Any=None					,				**__a     :					Dict					,				):
								super().__init__(
								    pad_token_id=__a					,				bos_token_id=__a					,				eos_token_id=__a					,				sep_token_id=__a					,				**__a					,				)

								_a								= vocab_size
								_a								= max_position_embeddings
								_a								= hidden_size
								_a								= num_hidden_layers
								_a								= num_attention_heads
								_a								= intermediate_size
								_a								= hidden_act
								_a								= hidden_dropout_prob
								_a								= attention_probs_dropout_prob
								_a								= initializer_range
								_a								= type_vocab_size
								_a								= layer_norm_eps
								_a								= use_cache

								_a								= rescale_embeddings
								_a								= attention_type
								_a								= use_bias
								_a								= block_size
								_a								= num_random_blocks
								_a								= classifier_dropout


class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_      ):






				"""simple docstring"""







				@property
				def   UpperCamelCase__   (  self     :					Optional[int]					):
								if self.task == "multiple-choice":
												_a								= {0: "batch", 1: "choice", 2: "sequence"}
								else:
												_a								= {0: "batch", 1: "sequence"}
								return OrderedDict(
								    [
								        ("input_ids", dynamic_axis),
								        ("attention_mask", dynamic_axis),
								    ]					)
