





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


lowercase_          =		logging.get_logger(__name__)
@dataclass
class     SCREAMING_SNAKE_CASE       :
   _UpperCamelCase   :		str			 =	field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys()				)}				)
   _UpperCamelCase   :		Any			 =	field(
       metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'}				)
   _UpperCamelCase   :		Optional[Any]			 =	field(
       default=1_28      ,     metadata={
           'help': (
               'The maximum total input sequence length after tokenization. Sequences longer '
               'than this will be truncated, sequences shorter will be padded.'
           )
       }      ,     )
   _UpperCamelCase   :		Tuple			 =	field(
       default=_snake_case      ,     metadata={'help': 'Overwrite the cached training and evaluation sets'}				)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]	)->       Any:





     """simple docstring"""







     lowercase__           =  self.task_name.lower()
class     SCREAMING_SNAKE_CASE       (_snake_case				):
   _UpperCamelCase   :		Any			 =	'train'
   _UpperCamelCase   :		int			 =	'dev'
   _UpperCamelCase   :		Dict			 =	'test'
class     SCREAMING_SNAKE_CASE       (_snake_case				):
   _UpperCamelCase   :		str			 =	42
   _UpperCamelCase   :		Tuple			 =	42
   _UpperCamelCase   :		List[str]			 =	42


   def __init__(   self      :    int      ,					a      :    Optional[int]      ,					a      :    int      ,					a      :    List[str] = None      ,					a      :    Union[str, Any] = Split.train      ,					a      :    Any = None      ,					)->       List[Any]:





     """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'      ,					UpperCamelCase__      ,					)
     lowercase__           =  args
     lowercase__           =  glue_processors[args.task_name]()
     lowercase__           =  glue_output_modes[args.task_name]
     if isinstance(UpperCamelCase__      ,					UpperCamelCase__	):
       try:
         lowercase__           =  Split[mode]
       except KeyError:
         raise KeyError('mode is not a valid split name'	)
        # Load data features from cache or dataset file
     lowercase__           =  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}"""      ,					)
     lowercase__           =  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)
       lowercase__      ,   lowercase__           =  label_list[2], label_list[1]
     lowercase__           =  label_list

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





     """simple docstring"""







     return len(self.features	)


   def __getitem__(   self      :    List[Any]      ,					a      :    int	)->       InputFeatures:





     """simple docstring"""







     return self.features[i]


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict	)->       Dict:





     """simple docstring"""







     return self.label_list









import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if is_torch_version('<'		,						'2.0.0'		) or not hasattr(_SCREAMING_SNAKE_CASE		,						'_dynamo'		):
    return False
  return isinstance(_SCREAMING_SNAKE_CASE		,						torch._dynamo.eval_frame.OptimizedModule		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE = True		)    ->       Dict:
  lowercase__           =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

  lowercase__           =  is_compiled_module(_SCREAMING_SNAKE_CASE		)
  if is_compiled:
    lowercase__           =  model
    lowercase__           =  model._orig_mod

  if is_deepspeed_available():
    options += (DeepSpeedEngine,)

  while isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
    lowercase__           =  model.module

  if not keep_fpaa_wrapper:
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'forward'		)
    lowercase__           =  model.__dict__.pop('_original_forward'		,						_SCREAMING_SNAKE_CASE		)
    if original_forward is not None:
      while hasattr(_SCREAMING_SNAKE_CASE		,						'__wrapped__'		):
        lowercase__           =  forward.__wrapped__
        if forward == original_forward:
          break
      lowercase__           =  forward
    if getattr(_SCREAMING_SNAKE_CASE		,						'_converted_to_transformer_engine'		,						_SCREAMING_SNAKE_CASE		):
      convert_model(_SCREAMING_SNAKE_CASE		,						to_transformer_engine=_SCREAMING_SNAKE_CASE		)

  if is_compiled:
    lowercase__           =  model
    lowercase__           =  compiled_model

  return model




def       __UpperCamelCase  ()    ->       Tuple:
  PartialState().wait_for_everyone()




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       List[Any]:
  if PartialState().distributed_type == DistributedType.TPU:
    xm.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
  elif PartialState().local_process_index == 0:
    torch.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)




@contextmanager
def       __UpperCamelCase  (**_SCREAMING_SNAKE_CASE		)    ->       Optional[Any]:
  for key, value in kwargs.items():
    lowercase__           =  str(_SCREAMING_SNAKE_CASE		)

  yield

  for key in kwargs:
    if key.upper() in os.environ:
      del os.environ[key.upper()]




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if not hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		) and not hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'__class__'		,						_SCREAMING_SNAKE_CASE		)
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		):
    return obj.__qualname__
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    return obj.__name__
  return str(_SCREAMING_SNAKE_CASE		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Dict:
  for key, value in source.items():
    if isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
      lowercase__           =  destination.setdefault(_SCREAMING_SNAKE_CASE		,						{}		)
      merge_dicts(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
    else:
      lowercase__           =  value

  return destination




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE = None		)    ->       bool:
  if port is None:
    lowercase__           =  29500
  with socket.socket(socket.AF_INET		,						socket.SOCK_STREAM		) as s:
    return s.connect_ex(('localhost', port)		) == 0


