





'''simple docstring'''





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










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

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

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


_a						=   logging.get_logger(__name__)






@dataclass
class       __A					:

			'''simple docstring'''







			lowerCAmelCase_							  =		field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()				)}				)
			lowerCAmelCase_							  =		field(
			    metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the 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=lowerCAmelCase    ,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				lowerCamelCase__              =	self.task_name.lower()






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







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






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42





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



				'''simple docstring'''







				warnings.warn(
				    '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
				    '''library. You can have a look at this example script for pointers: '''
				    '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ,						__lowerCAmelCase ,						)
				lowerCamelCase__              =	args
				lowerCamelCase__              =	glue_processors[args.task_name]()
				lowerCamelCase__              =	glue_output_modes[args.task_name]
				if isinstance(__lowerCAmelCase ,						__lowerCAmelCase							):
					try:
						lowerCamelCase__              =	Split[mode]
					except KeyError:
						raise KeyError('''mode is not a valid split name'''							)
        # Load data features from cache or dataset file
				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}_{args.task_name}' ,						)
				lowerCamelCase__              =	self.processor.get_labels()
				if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
				    "RobertaTokenizer",
				    "RobertaTokenizerFast",
				    "XLMRobertaTokenizer",
				    "BartTokenizer",
				    "BartTokenizerFast",
				):
					# HACK(label indices are swapped in RoBERTa pretrained model)
					lowerCamelCase__       ,			lowerCamelCase__              =	label_list[2], label_list[1]
				lowerCamelCase__              =	label_list

				# 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							)
						logger.info(
						    F'Loading features from cached file {cached_features_file} [took %.3f s]' ,						time.time() - start							)
					else:
						logger.info(F'Creating features from dataset file at {args.data_dir}'							)

						if mode == Split.dev:
							lowerCamelCase__              =	self.processor.get_dev_examples(args.data_dir							)
						elif mode == Split.test:
							lowerCamelCase__              =	self.processor.get_test_examples(args.data_dir							)
						else:
							lowerCamelCase__              =	self.processor.get_train_examples(args.data_dir							)
						if limit_length is not None:
							lowerCamelCase__              =	examples[:limit_length]
						lowerCamelCase__              =	glue_convert_examples_to_features(
						    __lowerCAmelCase ,						__lowerCAmelCase ,						max_length=args.max_seq_length ,						label_list=__lowerCAmelCase ,						output_mode=self.output_mode ,						)
						lowerCamelCase__              =	time.time()
						torch.save(self.features ,						__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'''







				return self.features[i]





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				return self.label_list



