





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   _SCREAMING_SNAKE_CASE		:







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

 def 				SCREAMING_SNAKE_CASE_   (self							:  Tuple)			->Any:



   '''simple docstring'''



   lowerCamelCase__: int         =self.task_name.lower()



class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''
 lowercase_						=     "train"
 lowercase_						=     "dev"
 lowercase_						=     "test"



class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''
 lowercase_						=     42
 lowercase_						=     42
 lowercase_						=     42

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



   '''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_			,					)
   lowerCamelCase__: Tuple         =args
   lowerCamelCase__: Union[str, Any]         =glue_processors[args.task_name]()
   lowerCamelCase__: List[str]         =glue_output_modes[args.task_name]
   if isinstance(UpperCAmelCase_			,					UpperCAmelCase_):
     try:
       lowerCamelCase__: str         =Split[mode]
     except KeyError:
       raise KeyError("mode is not a valid split name")
        # Load data features from cache or dataset file
   lowerCamelCase__: Tuple         =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__: List[Any]         =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__: List[str]         =label_list[2], label_list[1]
   lowerCamelCase__: Dict         =label_list

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



   '''simple docstring'''



   return len(self.features)

 def __getitem__(self							:  List[str]			,					UpperCAmelCase_							:  str)			->InputFeatures:



   '''simple docstring'''



   return self.features[i]







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



   '''simple docstring'''



   return self.label_list







# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce

def lowercase    (  SCREAMING_SNAKE_CASE )			->							str:


			'''simple docstring'''







			return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Dict:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						gather(SCREAMING_SNAKE_CASE )
			assert gathered_tensor.tolist() == list(range(1       ,    state.num_processes**2 + 1 ) )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[str]:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						[state.process_index]
			SCREAMING_SNAKE_CASE_								=						gather_object(SCREAMING_SNAKE_CASE )
			assert len(SCREAMING_SNAKE_CASE ) == state.num_processes, F'{gathered_obj}, {len(SCREAMING_SNAKE_CASE )} != {state.num_processes}'
			assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							int:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						broadcast(SCREAMING_SNAKE_CASE )
			assert broadcasted_tensor.shape == torch.Size([state.num_processes] )
			assert broadcasted_tensor.tolist() == list(range(1       ,    state.num_processes + 1 ) )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Union[str, Any]:


			'''simple docstring'''







			if state.is_main_process:
						SCREAMING_SNAKE_CASE_								=						torch.arange(state.num_processes + 1 ).to(state.device )
			else:
						SCREAMING_SNAKE_CASE_								=						torch.arange(state.num_processes ).to(state.device )
			SCREAMING_SNAKE_CASE_								=						pad_across_processes(SCREAMING_SNAKE_CASE )
			assert padded_tensor.shape == torch.Size([state.num_processes + 1] )
			if not state.is_main_process:
						assert padded_tensor.tolist() == list(range(0       ,    state.num_processes ) ) + [0]

def lowercase    (  SCREAMING_SNAKE_CASE )			->							str:


			'''simple docstring'''







			if state.num_processes != 2:
						return
			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						reduce(SCREAMING_SNAKE_CASE       ,    'sum' )
			SCREAMING_SNAKE_CASE_								=						torch.tensor([4.0, 6] ).to(state.device )
			assert torch.allclose(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE ), F'{reduced_tensor} != {truth_tensor}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Dict:


			'''simple docstring'''







			if state.num_processes != 2:
						return
			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						reduce(SCREAMING_SNAKE_CASE       ,    'mean' )
			SCREAMING_SNAKE_CASE_								=						torch.tensor([2.0, 3] ).to(state.device )
			assert torch.allclose(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE ), F'{reduced_tensor} != {truth_tensor}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[str]:


			'''simple docstring'''







			main()

def lowercase    (  )			->							str:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						PartialState()
			state.print(F'State: {state}' )
			state.print('testing gather' )
			test_gather(SCREAMING_SNAKE_CASE )
			state.print('testing gather_object' )
			test_gather_object(SCREAMING_SNAKE_CASE )
			state.print('testing broadcast' )
			test_broadcast(SCREAMING_SNAKE_CASE )
			state.print('testing pad_across_processes' )
			test_pad_across_processes(SCREAMING_SNAKE_CASE )
			state.print('testing reduce_sum' )
			test_reduce_sum(SCREAMING_SNAKE_CASE )
			state.print('testing reduce_mean' )
			test_reduce_mean(SCREAMING_SNAKE_CASE )


if __name__ == "__main__":
				main()
