

import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met

class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							def __init__(			self       ,							*_a       ,							_a=None       ,							_a=None       ,							**_a       )    ->    Optional[Any]:
												super().__init__(*_a       ,							**_a       )
												_a	:    Any         =		eval_examples
												_a	:    Optional[int]         =		post_process_function


							def 				__lowercase				(			self       ,							_a=None       ,							_a=None       ,							_a=None       ,							_a = "eval"       )    ->    List[str]:
												_a	:    List[Any]         =		self.eval_dataset if eval_dataset is None else eval_dataset
												_a	:    List[str]         =		self.get_eval_dataloader(_a       )
												_a	:    Dict         =		self.eval_examples if eval_examples is None else eval_examples

												# Temporarily disable metric computation, we will do it in the loop here.
												_a	:    Any         =		self.compute_metrics
												_a	:    Tuple         =		None
												_a	:    Tuple         =		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
												_a	:    Optional[Any]         =		time.time()
												try:
																	_a	:    List[Any]         =		eval_loop(
																	    _a       ,							description='''Evaluation'''       ,							prediction_loss_only=True if compute_metrics is None else None       ,							ignore_keys=_a       ,							metric_key_prefix=_a       ,							)
												finally:
																	_a	:    Dict         =		compute_metrics
												_a	:    Union[str, Any]         =		self.args.eval_batch_size * self.args.world_size
												if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
																	start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
												output.metrics.update(
												    speed_metrics(
												        _a       ,							_a       ,							num_samples=output.num_samples       ,							num_steps=math.ceil(output.num_samples / total_batch_size       )       ,							)       )
												if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
																	# Only the main node write the results by default
																	_a	:    Union[str, Any]         =		self.post_process_function(_a       ,							_a       ,							output.predictions       )
																	_a	:    Any         =		self.compute_metrics(_a       )

																	# Prefix all keys with metric_key_prefix + '_'
																	for key in list(metrics.keys()       ):
																						if not key.startswith(F"""{metric_key_prefix}_"""       ):
																											_a	:    Tuple         =		metrics.pop(_a       )
																	metrics.update(output.metrics       )
												else:
																	_a	:    Union[str, Any]         =		output.metrics

												if self.args.should_log:
																	# Only the main node log the results by default
																	self.log(_a       )

												if self.args.tpu_metrics_debug or self.args.debug:
																	# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
																	xm.master_print(met.metrics_report()       )

												_a	:    Dict         =		self.callback_handler.on_evaluate(self.args       ,							self.state       ,							self.control       ,							_a       )
												return metrics




							def 				__lowercase				(			self       ,							_a       ,							_a       ,							_a=None       ,							_a = "test"       )    ->    Union[str, Any]:
												_a	:    str         =		self.get_test_dataloader(_a       )

												# Temporarily disable metric computation, we will do it in the loop here.
												_a	:    List[str]         =		self.compute_metrics
												_a	:    Optional[Any]         =		None
												_a	:    Tuple         =		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
												_a	:    Optional[int]         =		time.time()
												try:
																	_a	:    List[str]         =		eval_loop(
																	    _a       ,							description='''Prediction'''       ,							prediction_loss_only=True if compute_metrics is None else None       ,							ignore_keys=_a       ,							metric_key_prefix=_a       ,							)
												finally:
																	_a	:    Dict         =		compute_metrics
												_a	:    Optional[int]         =		self.args.eval_batch_size * self.args.world_size
												if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
																	start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
												output.metrics.update(
												    speed_metrics(
												        _a       ,							_a       ,							num_samples=output.num_samples       ,							num_steps=math.ceil(output.num_samples / total_batch_size       )       ,							)       )

												if self.post_process_function is None or self.compute_metrics is None:
																	return output

												_a	:    str         =		self.post_process_function(_a       ,							_a       ,							output.predictions       ,							'''predict'''       )
												_a	:    Union[str, Any]         =		self.compute_metrics(_a       )

												# Prefix all keys with metric_key_prefix + '_'
												for key in list(metrics.keys()       ):
																	if not key.startswith(F"""{metric_key_prefix}_"""       ):
																						_a	:    str         =		metrics.pop(_a       )
												metrics.update(output.metrics       )
												return PredictionOutput(predictions=predictions.predictions       ,							label_ids=predictions.label_ids       ,							metrics=_a       )






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 				UpperCAmelCase_		:
							"""simple docstring"""







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


							def 				__lowercase				(			self       )    ->    List[Any]:
												_a	:    List[Any]         =		self.task_name.lower()



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						List[str]	    =    "train"
							UpperCAmelCase__       :						List[str]	    =    "dev"
							UpperCAmelCase__       :						Union[str, Any]	    =    "test"



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						GlueDataTrainingArguments
							UpperCAmelCase__       :						str
							UpperCAmelCase__       :						List[InputFeatures]


							def __init__(			self       ,							_a       ,							_a       ,							_a = None       ,							_a = Split.train       ,							_a = None       ,							)    ->    str:
												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'''       ,							_a       ,							)
												_a	:    List[str]         =		args
												_a	:    List[str]         =		glue_processors[args.task_name]()
												_a	:    List[Any]         =		glue_output_modes[args.task_name]
												if isinstance(_a       ,							_a       ):
																	try:
																						_a	:    Any         =		Split[mode]
																	except KeyError:
																						raise KeyError('''mode is not a valid split name'''       )
        # Load data features from cache or dataset file
												_a	:    Union[str, Any]         =		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}"""       ,							)
												_a	:    str         =		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)
																	_a      ,					_a	:    Optional[int]         =		label_list[2], label_list[1]
												_a	:    Dict         =		label_list

												# Make sure only the first process in distributed training processes the dataset,
												# and the others will use the cache.
												_a	:    Optional[int]         =		cached_features_file + '''.lock'''
												with FileLock(_a       ):
																	if os.path.exists(_a       ) and not args.overwrite_cache:
																						_a	:    List[Any]         =		time.time()
																						_a	:    str         =		torch.load(_a       )
																						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:
																											_a	:    str         =		self.processor.get_dev_examples(args.data_dir       )
																						elif mode == Split.test:
																											_a	:    Any         =		self.processor.get_test_examples(args.data_dir       )
																						else:
																											_a	:    List[str]         =		self.processor.get_train_examples(args.data_dir       )
																						if limit_length is not None:
																											_a	:    Dict         =		examples[:limit_length]
																						_a	:    Union[str, Any]         =		glue_convert_examples_to_features(
																						    _a       ,							_a       ,							max_length=args.max_seq_length       ,							label_list=_a       ,							output_mode=self.output_mode       ,							)
																						_a	:    Optional[int]         =		time.time()
																						torch.save(self.features       ,							_a       )
																						# ^ 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       )    ->    Optional[int]:
												return len(self.features       )


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




							def 				__lowercase				(			self       )    ->    Tuple:
												return self.label_list



