


import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


__snake_case   							=						datasets.utils.logging.get_logger(__name__)

__snake_case   							=						['''names''', '''prefix''']
__snake_case   							=						['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
__snake_case   							=						['''encoding_errors''', '''on_bad_lines''']
__snake_case   							=						['''date_format''']



@dataclass
class 	__lowerCamelCase			(datasets.BuilderConfig						):
       _lowercase											=     ","
       _lowercase											=     None
       _lowercase											=     "infer"
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     False
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     True
       _lowercase											=     False
       _lowercase											=     True
       _lowercase											=     None
       _lowercase											=     "."
       _lowercase											=     None
       _lowercase											=     '"'
       _lowercase											=     0
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     True
       _lowercase											=     0
       _lowercase											=     True
       _lowercase											=     False
       _lowercase											=     None
       _lowercase											=     1_0000
       _lowercase											=     None
       _lowercase											=     "strict"
       _lowercase											=     "error"
       _lowercase											=     None







       def 		snake_case_	(			self: str					):






            '''simple docstring'''




            if self.delimiter is not None:
                 __UpperCamelCase =			self.delimiter
            if self.column_names is not None:
                 __UpperCamelCase =			self.column_names







       @property
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            __UpperCamelCase =			{
                'sep': self.sep,
                'header': self.header,
                'names': self.names,
                'index_col': self.index_col,
                'usecols': self.usecols,
                'prefix': self.prefix,
                'mangle_dupe_cols': self.mangle_dupe_cols,
                'engine': self.engine,
                'converters': self.converters,
                'true_values': self.true_values,
                'false_values': self.false_values,
                'skipinitialspace': self.skipinitialspace,
                'skiprows': self.skiprows,
                'nrows': self.nrows,
                'na_values': self.na_values,
                'keep_default_na': self.keep_default_na,
                'na_filter': self.na_filter,
                'verbose': self.verbose,
                'skip_blank_lines': self.skip_blank_lines,
                'thousands': self.thousands,
                'decimal': self.decimal,
                'lineterminator': self.lineterminator,
                'quotechar': self.quotechar,
                'quoting': self.quoting,
                'escapechar': self.escapechar,
                'comment': self.comment,
                'encoding': self.encoding,
                'dialect': self.dialect,
                'error_bad_lines': self.error_bad_lines,
                'warn_bad_lines': self.warn_bad_lines,
                'skipfooter': self.skipfooter,
                'doublequote': self.doublequote,
                'memory_map': self.memory_map,
                'float_precision': self.float_precision,
                'chunksize': self.chunksize,
                'encoding_errors': self.encoding_errors,
                'on_bad_lines': self.on_bad_lines,
                'date_format': self.date_format,
            }

            # some kwargs must not be passed if they don't have a default value
            # some others are deprecated and we can also not pass them if they are the default value
            for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
                 if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig(),A_					):
                      del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
            if not (datasets.config.PANDAS_VERSION.major >= 2):
                 for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                      del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
            if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
                 for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                      del pd_read_csv_kwargs[pd_read_csv_parameter]

            return pd_read_csv_kwargs



class 	__lowerCamelCase			(datasets.ArrowBasedBuilder						):
       _lowercase											=     CsvConfig







       def 		snake_case_	(			self: Optional[int]					):






            '''simple docstring'''




            return datasets.DatasetInfo(features=self.config.features					)







       def 		snake_case_	(			self: List[str],A_: Any					):






            '''simple docstring'''




            if not self.config.data_files:
                 raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}'''					)
            __UpperCamelCase =			dl_manager.download_and_extract(self.config.data_files					)
            if isinstance(A_,(str, list, tuple)					):
                 __UpperCamelCase =			data_files
                 if isinstance(A_,A_					):
                      __UpperCamelCase =			[files]
                 __UpperCamelCase =			[dl_manager.iter_files(A_					) for file in files]
                 return [datasets.SplitGenerator(name=datasets.Split.TRAIN,gen_kwargs={'files': files}					)]
            __UpperCamelCase =			[]
            for split_name, files in data_files.items():
                 if isinstance(A_,A_					):
                      __UpperCamelCase =			[files]
                 __UpperCamelCase =			[dl_manager.iter_files(A_					) for file in files]
                 splits.append(datasets.SplitGenerator(name=A_,gen_kwargs={'files': files}					)					)
            return splits







       def 		snake_case_	(			self: Dict,A_: pa.Table					):






            '''simple docstring'''




            if self.config.features is not None:
                 __UpperCamelCase =			self.config.features.arrow_schema
                 if all(not require_storage_cast(A_					) for feature in self.config.features.values()					):
                      # cheaper cast
                      __UpperCamelCase =			pa.Table.from_arrays([pa_table[field.name] for field in schema],schema=A_					)
                 else:
                      # more expensive cast; allows str <-> int/float or str to Audio for example
                      __UpperCamelCase =			table_cast(A_,A_					)
            return pa_table







       def 		snake_case_	(			self: Optional[Any],A_: Optional[int]					):






            '''simple docstring'''




            __UpperCamelCase =			self.config.features.arrow_schema if self.config.features else None
            # dtype allows reading an int column as str
            __UpperCamelCase =			(
                {
                    name: dtype.to_pandas_dtype() if not require_storage_cast(A_					) else object
                    for name, dtype, feature in zip(schema.names,schema.types,self.config.features.values()					)
                }
                if schema is not None
                else None
            )
            for file_idx, file in enumerate(itertools.chain.from_iterable(A_					)					):
                 __UpperCamelCase =			pd.read_csv(A_,iterator=A_,dtype=A_,**self.config.pd_read_csv_kwargs					)
                 try:
                      for batch_idx, df in enumerate(A_					):
                           __UpperCamelCase =			pa.Table.from_pandas(A_					)
                           # Uncomment for debugging (will print the Arrow table size and elements)
                           # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                           # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                           yield (file_idx, batch_idx), self._cast_table(A_					)
                 except ValueError as e:
                      logger.error(F'''Failed to read file \'{file}\' with error {type(A_					)}: {e}'''					)
                      raise







'''simple docstring'''






import baseaa
import io
import json
import os
from copy import deepcopy

from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler

class 				a__:







    def __init__( self					:    List[Any]		,     __snake_case					:    str      ):
      if isinstance(__snake_case		,     __snake_case      ):
        # Don't modify user's data should they want to reuse it (e.g. in tests), because once we
        # modified it, it will not be accepted here again, since `auto` values would have been overridden
        a		:   Union[str, Any]	  =	deepcopy(__snake_case      )
      elif os.path.exists(__snake_case      ):
        with io.open(__snake_case		,     'r'		,     encoding='utf-8'      ) as f:
          a		:   List[str]	  =	json.load(__snake_case      )
      else:
        try:
          a		:   str	  =	baseaa.urlsafe_baadecode(__snake_case      ).decode('utf-8'      )
          a		:   Union[str, Any]	  =	json.loads(__snake_case      )
        except (UnicodeDecodeError, AttributeError, ValueError):
          raise ValueError(
              F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}"""      )

      a		:   Optional[int]	  =	config

      self.set_stage_and_offload()







    def      lowercase_			( self					:    Any      ):
      # zero stage - this is done as early as possible, before model is created, to allow
      # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object
      # during ``zero.Init()`` which needs to know the dtype, and some other hparams.
      a		:   List[str]	  =	self.get_value('zero_optimization.stage'		,     -1      )

      # offload
      a		:   Union[str, Any]	  =	False
      if self.is_zeroa() or self.is_zeroa():
        a		:   Any	  =	set(['cpu', 'nvme']      )
        a		:   Tuple	  =	set(
            [
                self.get_value('zero_optimization.offload_optimizer.device'      ),
                self.get_value('zero_optimization.offload_param.device'      ),
            ]      )
        if len(offload_devices & offload_devices_valid      ) > 0:
          a		:   Optional[int]	  =	True







    def      lowercase_			( self					:    str		,     __snake_case					:    Optional[Any]      ):
      a		:   Any	  =	self.config

      # find the config node of interest if it exists
      a		:   Dict	  =	ds_key_long.split('.'      )
      a		:   str	  =	nodes.pop()
      for node in nodes:
        a		:   Tuple	  =	config.get(__snake_case      )
        if config is None:
          return None, ds_key

      return config, ds_key







    def      lowercase_			( self					:    int		,     __snake_case					:    Optional[int]		,     __snake_case					:    List[str]=None      ):
      a  ,      a		:   int	  =	self.find_config_node(__snake_case      )
      if config is None:
        return default
      return config.get(__snake_case		,     __snake_case      )







    def      lowercase_			( self					:    Dict		,     __snake_case					:    List[str]		,     __snake_case					:    List[Any]=False      ):
      a		:   Union[str, Any]	  =	self.config

      # find the config node of interest if it exists
      a		:   Tuple	  =	ds_key_long.split('.'      )
      for node in nodes:
        a		:   Optional[int]	  =	config
        a		:   List[str]	  =	config.get(__snake_case      )
        if config is None:
          if must_exist:
            raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}"""      )
          else:
            return

        # if found remove it
      if parent_config is not None:
        parent_config.pop(__snake_case      )







    def      lowercase_			( self					:    List[str]		,     __snake_case					:    Dict      ):
      a		:   Optional[Any]	  =	self.get_value(__snake_case      )
      return False if value is None else bool(__snake_case      )







    def      lowercase_			( self					:    str		,     __snake_case					:    Optional[Any]      ):
      a		:   Optional[Any]	  =	self.get_value(__snake_case      )
      return False if value is None else not bool(__snake_case      )







    def      lowercase_			( self					:    Tuple      ):
      return self._stage == 2







    def      lowercase_			( self					:    str      ):
      return self._stage == 3







    def      lowercase_			( self					:    int      ):
      return self._offload

class 				a__:







    def __init__( self					:    str		,     __snake_case					:    Any      ):
      a		:   Any	  =	engine







    def      lowercase_			( self					:    Optional[Any]		,     __snake_case					:    int		,     **__snake_case					:    List[Any]      ):
      # runs backpropagation and handles mixed precision
      self.engine.backward(__snake_case		,     **__snake_case      )

      # Deepspeed's `engine.step` performs the following operations:
      # - gradient accumulation check
      # - gradient clipping
      # - optimizer step
      # - zero grad
      # - checking overflow
      # - lr_scheduler step (only if engine.lr_scheduler is not None)
      self.engine.step()
      # and this plugin overrides the above calls with no-ops when Accelerate runs under
      # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
      # training loop that works transparently under many training regimes.

class 				a__(   lowerCamelCase__      ):







    def __init__( self					:    Dict		,     __snake_case					:    Any      ):
      super().__init__(__snake_case		,     device_placement=__snake_case		,     scaler=__snake_case      )
      a		:   List[Any]	  =	hasattr(self.optimizer		,     'overflow'      )







    def      lowercase_			( self					:    Optional[Any]		,     __snake_case					:    str=None      ):
      pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed







    def      lowercase_			( self					:    int      ):
      pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed







    @property
    def      lowercase_			( self					:    Any      ):
      if self.__has_overflow__:
        return self.optimizer.overflow
      return False

class 				a__(   lowerCamelCase__      ):







    def __init__( self					:    str		,     __snake_case					:    List[Any]		,     __snake_case					:    str      ):
      super().__init__(__snake_case		,     __snake_case      )







    def      lowercase_			( self					:    Union[str, Any]      ):
      pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed

class 				a__:







    def __init__( self					:    Optional[Any]		,     __snake_case					:    Union[str, Any]		,     __snake_case					:    int=0.001		,     __snake_case					:    Any=0		,     **__snake_case					:    List[Any]      ):
      a		:   Optional[Any]	  =	params
      a		:   Union[str, Any]	  =	lr
      a		:   Any	  =	weight_decay
      a		:   Any	  =	kwargs

class 				a__:







    def __init__( self					:    Any		,     __snake_case					:    int		,     __snake_case					:    int=None		,     __snake_case					:    Dict=0		,     **__snake_case					:    Optional[int]      ):
      a		:   Optional[int]	  =	optimizer
      a		:   List[str]	  =	total_num_steps
      a		:   Tuple	  =	warmup_num_steps
      a		:   Optional[Any]	  =	kwargs