


import operator as op


__UpperCAmelCase      :str			    =       "scaler.pt"
__UpperCAmelCase      :List[str]			    =       "pytorch_model"
__UpperCAmelCase      :List[str]			    =       "random_states"
__UpperCAmelCase      :Optional[int]			    =       "optimizer"
__UpperCAmelCase      :Any			    =       "scheduler"
__UpperCAmelCase      :Optional[int]			    =       "pytorch_model.bin"
__UpperCAmelCase      :List[str]			    =       "pytorch_model.bin.index.json"
__UpperCAmelCase      :Optional[int]			    =       "model.safetensors"
__UpperCAmelCase      :int			    =       "model.safetensors.index.json"
__UpperCAmelCase      :Optional[Any]			    =       "1.10.2"
__UpperCAmelCase      :Optional[Any]			    =       "py38"
__UpperCAmelCase      :Any			    =       "4.17.0"
__UpperCAmelCase      :Union[str, Any]			    =       ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"]
__UpperCAmelCase      :Tuple			    =       ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"]
__UpperCAmelCase      :Dict			    =       ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"]
__UpperCAmelCase      :Union[str, Any]			    =       ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"]
__UpperCAmelCase      :Tuple			    =       ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"]
__UpperCAmelCase      :int			    =       "2.0.1"
__UpperCAmelCase      :int			    =       ["pdsh", "standard", "openmpi", "mvapich"]
__UpperCAmelCase      :str			    =       ["default", "reduce-overhead", "max-autotune"]

__UpperCAmelCase      :Tuple			    =       {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
__UpperCAmelCase      :Optional[int]			    =       [
    "nnodes",
    "nproc_per_node",
    "rdzv_backend",
    "rdzv_endpoint",
    "rdzv_id",
    "rdzv_conf",
    "standalone",
    "max_restarts",
    "monitor_interval",
    "start_method",
    "role",
    "module",
    "m",
    "no_python",
    "run_path",
    "log_dir",
    "r",
    "redirects",
    "t",
    "tee",
    "node_rank",
    "master_addr",
    "master_port",
]

__UpperCAmelCase      :List[Any]			    =       ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM"]
__UpperCAmelCase      :Tuple			    =       ["DEEPSPEED", "MULTI_XPU", "FSDP"]



'''simple docstring'''



import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


__UpperCAmelCase      :int			    =       datasets.utils.logging.get_logger(__name__)



@dataclass
class      a    (		datasets.BuilderConfig	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Optional[datasets.Features]							       =       None
     SCREAMING_SNAKE_CASE	:			str							       =       "utf-8"
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			bool							       =       True  # deprecated
     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       None  # deprecated
     SCREAMING_SNAKE_CASE	:			int							       =       1_0 << 2_0  # 10MB
     SCREAMING_SNAKE_CASE	:			Optional[bool]							       =       None



class      a    (		datasets.ArrowBasedBuilder	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Tuple							       =       JsonConfig

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Dict:
          if self.config.block_size is not None:
               logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''      )
               __UpperCAmelCase     :			Tuple  							=      self.config.block_size
          if self.config.use_threads is not True:
               logger.warning(
                   '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'''      )
          if self.config.newlines_in_values is not None:
               raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported'''      )
          return datasets.DatasetInfo(features=self.config.features      )

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		Tuple      )						->							str:
          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     :			Optional[int]  							=      dl_manager.download_and_extract(self.config.data_files      )
          if isinstance(snake_case							,			(str, list, tuple)      ):
               __UpperCAmelCase     :			Dict  							=      data_files
               if isinstance(snake_case							,			snake_case      ):
                    __UpperCAmelCase     :			List[Any]  							=      [files]
               __UpperCAmelCase     :			Tuple  							=      [dl_manager.iter_files(snake_case      ) for file in files]
               return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,			gen_kwargs={'''files''': files}      )]
          __UpperCAmelCase     :			Tuple  							=      []
          for split_name, files in data_files.items():
               if isinstance(snake_case							,			snake_case      ):
                    __UpperCAmelCase     :			Any  							=      [files]
               __UpperCAmelCase     :			Optional[int]  							=      [dl_manager.iter_files(snake_case      ) for file in files]
               splits.append(datasets.SplitGenerator(name=snake_case							,			gen_kwargs={'''files''': files}      )      )
          return splits

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		pa.Table      )						->							pa.Table:
          if self.config.features is not None:
               # adding missing columns
               for column_name in set(self.config.features      ) - set(pa_table.column_names      ):
                    __UpperCAmelCase     :			Any  							=      self.config.features.arrow_schema.field(snake_case      ).type
                    __UpperCAmelCase     :			Dict  							=      pa_table.append_column(snake_case							,			pa.array([None] * len(snake_case      )							,			type=snake_case      )      )
               # more expensive cast to support nested structures with keys in a different order
               # allows str <-> int/float or str to Audio for example
               __UpperCAmelCase     :			Tuple  							=      table_cast(snake_case							,			self.config.features.arrow_schema      )
          return pa_table






     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		Any      )						->							Optional[int]:
          for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case      )      ):
               # If the file is one json object and if we need to look at the list of items in one specific field
               if self.config.field is not None:
                    with open(snake_case							,			encoding=self.config.encoding							,			errors=self.config.encoding_errors      ) as f:
                         __UpperCAmelCase     :			Optional[int]  							=      json.load(snake_case      )

                    # We keep only the field we are interested in
                    __UpperCAmelCase     :			int  							=      dataset[self.config.field]

                    # We accept two format: a list of dicts or a dict of lists
                    if isinstance(snake_case							,			(list, tuple)      ):
                         __UpperCAmelCase     :			Optional[Any]  							=      set().union(*[row.keys() for row in dataset]      )
                         __UpperCAmelCase     :			Union[str, Any]  							=      {col: [row.get(snake_case      ) for row in dataset] for col in keys}
                    else:
                         __UpperCAmelCase     :			Optional[int]  							=      dataset
                    __UpperCAmelCase     :			Tuple  							=      pa.Table.from_pydict(snake_case      )
                    yield file_idx, self._cast_table(snake_case      )

               # If the file has one json object per line
               else:
                    with open(snake_case							,			'''rb'''      ) as f:
                         __UpperCAmelCase     :			Optional[Any]  							=      0
                         # Use block_size equal to the chunk size divided by 32 to leverage multithreading
                         # Set a default minimum value of 16kB if the chunk size is really small
                         __UpperCAmelCase     :			int  							=      max(self.config.chunksize // 32							,			16 << 10      )
                         __UpperCAmelCase     :			Any  							=      (
                             self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
                         )
                         while True:
                              __UpperCAmelCase     :			List[Any]  							=      f.read(self.config.chunksize      )
                              if not batch:
                                   break
                              # Finish current line
                              try:
                                   batch += f.readline()
                              except (AttributeError, io.UnsupportedOperation):
                                   batch += readline(snake_case      )
                              # PyArrow only accepts utf-8 encoded bytes
                              if self.config.encoding != "utf-8":
                                   __UpperCAmelCase     :			Union[str, Any]  							=      batch.decode(self.config.encoding							,			errors=snake_case      ).encode('''utf-8'''      )
                              try:
                                   while True:
                                        try:
                                             __UpperCAmelCase     :			List[str]  							=      paj.read_json(
                                                 io.BytesIO(snake_case      )							,			read_options=paj.ReadOptions(block_size=snake_case      )      )
                                             break
                                        except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                                             if (
                                                 isinstance(snake_case							,			pa.ArrowInvalid      )
                                                 and "straddling" not in str(snake_case      )
                                                 or block_size > len(snake_case      )
                                             ):
                                                  raise
                                             else:
                                                  # Increase the block size in case it was too small.
                                                  # The block size will be reset for the next file.
                                                  logger.debug(
                                                      f'Batch of {len(snake_case      )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'      )
                                                  block_size *= 2
                              except pa.ArrowInvalid as e:
                                   try:
                                        with open(
                                            snake_case							,			encoding=self.config.encoding							,			errors=self.config.encoding_errors      ) as f:
                                             __UpperCAmelCase     :			Optional[Any]  							=      json.load(snake_case      )
                                   except json.JSONDecodeError:
                                        logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                        raise e
                                   # If possible, parse the file as a list of json objects and exit the loop
                                   if isinstance(snake_case							,			snake_case      ):  # list is the only sequence type supported in JSON
                                        try:
                                             __UpperCAmelCase     :			Dict  							=      set().union(*[row.keys() for row in dataset]      )
                                             __UpperCAmelCase     :			Optional[Any]  							=      {col: [row.get(snake_case      ) for row in dataset] for col in keys}
                                             __UpperCAmelCase     :			Union[str, Any]  							=      pa.Table.from_pydict(snake_case      )
                                        except (pa.ArrowInvalid, AttributeError) as e:
                                             logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                             raise ValueError(f'Not able to read records in the JSON file at {file}.'      ) from None
                                        yield file_idx, self._cast_table(snake_case      )
                                        break
                                   else:
                                        logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                        raise ValueError(
                                            f'Not able to read records in the JSON file at {file}. '
                                            f'You should probably indicate the field of the JSON file containing your records. '
                                            f'This JSON file contain the following fields: {str(list(dataset.keys()      )      )}. '
                                            f'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '      ) from None
                        # 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(snake_case      )
                              batch_idx += 1