





import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_a						=   logging.get_logger(__name__)

_a						=   list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_a						=   tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class       __A					:

			'''simple docstring'''







			lowerCAmelCase_							  =		field(
			    default=lowerCAmelCase    ,       metadata={"""help""": """Model type selected in the list: """ + """, """.join(lowerCAmelCase				)}				)
			lowerCAmelCase_							  =		field(
			    default=lowerCAmelCase    ,       metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}				)
			lowerCAmelCase_							  =		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."""
			        )
			    }    ,       )
			lowerCAmelCase_							  =		field(
			    default=128    ,       metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}    ,       )
			lowerCAmelCase_							  =		field(
			    default=64    ,       metadata={
			        """help""": (
			            """The maximum number of tokens for the question. Questions longer than this will """
			            """be truncated to this length."""
			        )
			    }    ,       )
			lowerCAmelCase_							  =		field(
			    default=30    ,       metadata={
			        """help""": (
			            """The maximum length of an answer that can be generated. This is needed because the start """
			            """and end predictions are not conditioned on one another."""
			        )
			    }    ,       )
			lowerCAmelCase_							  =		field(
			    default=lowerCAmelCase    ,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)
			lowerCAmelCase_							  =		field(
			    default=lowerCAmelCase    ,       metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}				)
			lowerCAmelCase_							  =		field(
			    default=0.0    ,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
			lowerCAmelCase_							  =		field(
			    default=20    ,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
			lowerCAmelCase_							  =		field(
			    default=0    ,       metadata={
			        """help""": (
			            """language id of input for language-specific xlm models (see"""
			            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
			        )
			    }    ,       )
			lowerCAmelCase_							  =		field(default=1    ,       metadata={"""help""": """multiple threads for converting example to features"""}				)






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		"""train"""
			lowerCAmelCase_							  =		"""dev"""






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42





			def __init__(					self ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase = None ,						__lowerCAmelCase = Split.train ,						__lowerCAmelCase = False ,						__lowerCAmelCase = None ,						__lowerCAmelCase = "pt" ,						):



				'''simple docstring'''







				lowerCamelCase__              =	args
				lowerCamelCase__              =	is_language_sensitive
				lowerCamelCase__              =	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
				if isinstance(__lowerCAmelCase ,						__lowerCAmelCase							):
					try:
						lowerCamelCase__              =	Split[mode]
					except KeyError:
						raise KeyError('''mode is not a valid split name'''							)
				lowerCamelCase__              =	mode
				# Load data features from cache or dataset file
				lowerCamelCase__              =	'''v2''' if args.version_2_with_negative else '''v1'''
				lowerCamelCase__              =	os.path.join(
				    cache_dir if cache_dir is not None else args.data_dir ,						F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' ,						)

				# Make sure only the first process in distributed training processes the dataset,
				# and the others will use the cache.
				lowerCamelCase__              =	cached_features_file + '''.lock'''
				with FileLock(__lowerCAmelCase							):
					if os.path.exists(__lowerCAmelCase							) and not args.overwrite_cache:
						lowerCamelCase__              =	time.time()
						lowerCamelCase__              =	torch.load(__lowerCAmelCase							)

						# Legacy cache files have only features, while new cache files
						# will have dataset and examples also.
						lowerCamelCase__              =	self.old_features['''features''']
						lowerCamelCase__              =	self.old_features.get('''dataset''' ,						__lowerCAmelCase							)
						lowerCamelCase__              =	self.old_features.get('''examples''' ,						__lowerCAmelCase							)
						logger.info(
						    F'Loading features from cached file {cached_features_file} [took %.3f s]' ,						time.time() - start							)

						if self.dataset is None or self.examples is None:
							logger.warning(
							    F'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
							    ''' future run'''							)
					else:
						if mode == Split.dev:
							lowerCamelCase__              =	self.processor.get_dev_examples(args.data_dir							)
						else:
							lowerCamelCase__              =	self.processor.get_train_examples(args.data_dir							)

						lowerCamelCase__       ,			lowerCamelCase__              =	squad_convert_examples_to_features(
						    examples=self.examples ,						tokenizer=__lowerCAmelCase ,						max_seq_length=args.max_seq_length ,						doc_stride=args.doc_stride ,						max_query_length=args.max_query_length ,						is_training=mode == Split.train ,						threads=args.threads ,						return_dataset=__lowerCAmelCase ,						)

						lowerCamelCase__              =	time.time()
						torch.save(
						    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples} ,						__lowerCAmelCase ,						)
						# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
						logger.info(
						    F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'							)





			def __len__(					self							):



				'''simple docstring'''







				return len(self.features							)





			def __getitem__(					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	self.features[i]

				lowerCamelCase__              =	torch.tensor(feature.input_ids ,						dtype=torch.long							)
				lowerCamelCase__              =	torch.tensor(feature.attention_mask ,						dtype=torch.long							)
				lowerCamelCase__              =	torch.tensor(feature.token_type_ids ,						dtype=torch.long							)
				lowerCamelCase__              =	torch.tensor(feature.cls_index ,						dtype=torch.long							)
				lowerCamelCase__              =	torch.tensor(feature.p_mask ,						dtype=torch.float							)
				lowerCamelCase__              =	torch.tensor(feature.is_impossible ,						dtype=torch.float							)

				lowerCamelCase__              =	{
				    '''input_ids''': input_ids,
				    '''attention_mask''': attention_mask,
				    '''token_type_ids''': token_type_ids,
				}

				if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
					del inputs["token_type_ids"]

				if self.args.model_type in ["xlnet", "xlm"]:
					inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask}							)
					if self.args.version_2_with_negative:
						inputs.update({'''is_impossible''': is_impossible}							)
					if self.is_language_sensitive:
						inputs.update({'''langs''': (torch.ones(input_ids.shape ,						dtype=torch.intaa							) * self.args.lang_id)}							)

				if self.mode == Split.train:
					lowerCamelCase__              =	torch.tensor(feature.start_position ,						dtype=torch.long							)
					lowerCamelCase__              =	torch.tensor(feature.end_position ,						dtype=torch.long							)
					inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}							)

				return inputs










import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


_a						=   logging.get_logger(__name__)






class       __A					:

			'''simple docstring'''







			lowerCAmelCase_							  =		None





@experimental
def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   Tuple:







	'''simple docstring'''







	if ParallelBackendConfig.backend_name is None:
		return _map_with_multiprocessing_pool(
		    __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case							)

	return _map_with_joblib(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case							)





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   int:







	'''simple docstring'''







	lowerCamelCase__              =	num_proc if num_proc <= len(__snake_case							) else len(__snake_case							)
	lowerCamelCase__              =	[]  # We organize the splits ourselve (contiguous splits)
	for index in range(__snake_case							):
		lowerCamelCase__              =	len(__snake_case							) // num_proc
		lowerCamelCase__              =	len(__snake_case							) % num_proc
		lowerCamelCase__              =	div * index + min(__snake_case ,__snake_case							)
		lowerCamelCase__              =	start + div + (1 if index < mod else 0)
		split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)							)

	if len(__snake_case							) != sum(len(i[1]							) for i in split_kwds							):
		raise ValueError(
		    F'Error dividing inputs iterable among processes. '
		    F'Total number of objects {len(__snake_case							)}, '
		    F'length: {sum(len(i[1]							) for i in split_kwds							)}'							)

	logger.info(
	    F'Spawning {num_proc} processes for {len(__snake_case							)} objects in slices of {[len(i[1]							) for i in split_kwds]}'							)
	lowerCamelCase__       ,			lowerCamelCase__              =	None, None
	if not disable_tqdm:
		lowerCamelCase__       ,			lowerCamelCase__              =	(RLock(),), tqdm.set_lock
	with Pool(__snake_case ,initargs=__snake_case ,initializer=__snake_case							) as pool:
		lowerCamelCase__              =	pool.map(__snake_case ,__snake_case							)
	logger.info(F'Finished {num_proc} processes'							)
	lowerCamelCase__              =	[obj for proc_res in mapped for obj in proc_res]
	logger.info(F'Unpacked {len(__snake_case							)} objects'							)

	return mapped





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   List[str]:







	'''simple docstring'''







	import joblib

	with joblib.parallel_backend(ParallelBackendConfig.backend_name ,n_jobs=__snake_case							):
		return joblib.Parallel()(
		    joblib.delayed(__snake_case							)((function, obj, types, None, True, None)							) for obj in iterable							)





@experimental
@contextlib.contextmanager
def lowerCAmelCase__(__snake_case							)       ->   int:







	'''simple docstring'''







	lowerCamelCase__              =	backend_name

	if backend_name == "spark":
		from joblibspark import register_spark

		register_spark()

		# TODO: call create_cache_and_write_probe if "download" in steps
		# TODO: raise NotImplementedError when Dataset.map etc is called

	try:
		yield
	finally:
		lowerCamelCase__              =	None



