


"""simple docstring"""







import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


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

if TYPE_CHECKING:
 import pyspark






@dataclass
class 						_A  (  datasets.BuilderConfig  ):







    """simple docstring"""




    UpperCAmelCase	:							Optional[datasets.Features]     =	None






def 					lowercase      (    A_  ,       A_  ,       )->				Union[str, Any]:
  '''simple docstring'''







  import pyspark

  def generate_fn():
    a						:		str											=      df.select("*"  ,       pyspark.sql.functions.spark_partition_id().alias("part_id"	)	)
    for partition_id in partition_order:
      a						:		Union[str, Any]											=      df_with_partition_id.select("*"	).where(F'''part_id = {partition_id}'''	).drop("part_id"	)
      a						:		Optional[int]											=      partition_df.collect()
      a						:		List[Any]											=      0
      for row in rows:
        yield F'''{partition_id}_{row_id}''', row.asDict()
        row_id += 1

  return generate_fn






class 						_A  (  _BaseExamplesIterable  ):







    """simple docstring"""




    def __init__( self    :   List[str]    ,			__UpperCAmelCase    :   "pyspark.sql.DataFrame"    ,			__UpperCAmelCase    :   Dict=None    ,			):
      a						:		str											=      df
      a						:		Tuple											=      partition_order or range(self.df.rdd.getNumPartitions())
      a						:		Optional[Any]											=      _generate_iterable_examples(self.df    ,			self.partition_order)






    def __iter__( self    :   str):
      yield from self.generate_examples_fn()






    def      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   np.random.Generator):
      a						:		int											=      list(range(self.df.rdd.getNumPartitions()))
      generator.shuffle(__UpperCAmelCase)
      return SparkExamplesIterable(self.df    ,			partition_order=__UpperCAmelCase)






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   int):
      a						:		Union[str, Any]											=      self.split_shard_indices_by_worker(__UpperCAmelCase    ,			__UpperCAmelCase)
      return SparkExamplesIterable(self.df    ,			partition_order=__UpperCAmelCase)






    @property
    def      __snake_case							( self    :   List[Any]):
      return len(self.partition_order)






class 						_A  (  datasets.DatasetBuilder  ):







    """simple docstring"""




    UpperCAmelCase	:							Union[str, Any]     =	SparkConfig






    def __init__( self    :   str    ,			__UpperCAmelCase    :   "pyspark.sql.DataFrame"    ,			__UpperCAmelCase    :   str = None    ,			__UpperCAmelCase    :   str = None    ,			**__UpperCAmelCase    :   str    ,			):
      import pyspark

      a						:		List[str]											=      pyspark.sql.SparkSession.builder.getOrCreate()
      a						:		Tuple											=      df
      a						:		List[Any]											=      working_dir

      super().__init__(
          cache_dir=__UpperCAmelCase    ,			config_name=str(self.df.semanticHash())    ,			**__UpperCAmelCase    ,			)






    def      __snake_case							( self    :   Any):
      # Returns the path of the created file.
      def create_cache_and_write_probe(__UpperCAmelCase    :   Optional[Any]):
        # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
        # already exist.
        os.makedirs(self._cache_dir    ,			exist_ok=__UpperCAmelCase)
        a						:		Optional[int]											=      os.path.join(self._cache_dir    ,			"fs_test" + uuid.uuida().hex)
        # Opening the file in append mode will create a new file unless it already exists, in which case it will not
        # change the file contents.
        open(__UpperCAmelCase    ,			"a")
        return [probe_file]

      if self._spark.conf.get("spark.master"    ,			"").startswith("local"):
        return

      # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
      # accessible to the driver.
      # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
      if self._cache_dir:
        a						:		Any											=      (
            self._spark.sparkContext.parallelize(range(1)    ,			1).mapPartitions(__UpperCAmelCase).collect()
        )
        if os.path.isfile(probe[0]):
          return

      raise ValueError(
          "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir")






    def      __snake_case							( self    :   Optional[int]):
      return datasets.DatasetInfo(features=self.config.features)






    def      __snake_case							( self    :   Optional[int]    ,			__UpperCAmelCase    :   datasets.download.download_manager.DownloadManager):
      return [datasets.SplitGenerator(name=datasets.Split.TRAIN)]






    def      __snake_case							( self    :   Tuple    ,			__UpperCAmelCase    :   Tuple):
      import pyspark

      def get_arrow_batch_size(__UpperCAmelCase    :   Dict):
        for batch in it:
          yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]})

      a						:		List[Any]											=      self.df.count()
      a						:		Tuple											=      df_num_rows if df_num_rows <= 100 else 100
      # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
      a						:		Union[str, Any]											=      (
          self.df.limit(__UpperCAmelCase)
          .repartition(1)
          .mapInArrow(__UpperCAmelCase    ,			"batch_bytes: long")
          .agg(pyspark.sql.functions.sum("batch_bytes").alias("sample_bytes"))
          .collect()[0]
          .sample_bytes
          / sample_num_rows
      )
      a						:		int											=      approx_bytes_per_row * df_num_rows
      if approx_total_size > max_shard_size:
        # Make sure there is at least one row per partition.
        a						:		int											=      min(__UpperCAmelCase    ,			int(approx_total_size / max_shard_size))
        a						:		List[Any]											=      self.df.repartition(__UpperCAmelCase)






    def      __snake_case							( self    :   int    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   int    ,			):
      import pyspark

      a						:		str											=      ParquetWriter if file_format == "parquet" else ArrowWriter
      a						:		Dict											=      os.path.join(self._working_dir    ,			os.path.basename(__UpperCAmelCase)) if self._working_dir else fpath
      a						:		List[Any]											=      file_format == "parquet"

      # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
      # pickling the SparkContext.
      a						:		str											=      self.config.features
      a						:		Union[str, Any]											=      self._writer_batch_size
      a						:		List[str]											=      self._fs.storage_options

      def write_arrow(__UpperCAmelCase    :   Tuple):
        # Within the same SparkContext, no two task attempts will share the same attempt ID.
        a						:		Any											=      pyspark.TaskContext().taskAttemptId()
        a						:		Dict											=      next(__UpperCAmelCase    ,			__UpperCAmelCase)
        if first_batch is None:
          # Some partitions might not receive any data.
          return pa.RecordBatch.from_arrays(
              [[task_id], [0], [0]]    ,			names=["task_id", "num_examples", "num_bytes"]    ,			)
        a						:		List[Any]											=      0
        a						:		Optional[int]											=      writer_class(
            features=__UpperCAmelCase    ,			path=working_fpath.replace("SSSSS"    ,			f'''{shard_id:05d}''').replace("TTTTT"    ,			f'''{task_id:05d}''')    ,			writer_batch_size=__UpperCAmelCase    ,			storage_options=__UpperCAmelCase    ,			embed_local_files=__UpperCAmelCase    ,			)
        a						:		str											=      pa.Table.from_batches([first_batch])
        writer.write_table(__UpperCAmelCase)
        for batch in it:
          if max_shard_size is not None and writer._num_bytes >= max_shard_size:
            a							,		a						:		Union[str, Any]											=      writer.finalize()
            writer.close()
            yield pa.RecordBatch.from_arrays(
                [[task_id], [num_examples], [num_bytes]]    ,			names=["task_id", "num_examples", "num_bytes"]    ,			)
            shard_id += 1
            a						:		str											=      writer_class(
                features=writer._features    ,			path=working_fpath.replace("SSSSS"    ,			f'''{shard_id:05d}''').replace("TTTTT"    ,			f'''{task_id:05d}''')    ,			writer_batch_size=__UpperCAmelCase    ,			storage_options=__UpperCAmelCase    ,			embed_local_files=__UpperCAmelCase    ,			)
          a						:		Union[str, Any]											=      pa.Table.from_batches([batch])
          writer.write_table(__UpperCAmelCase)

        if writer._num_bytes > 0:
          a							,		a						:		List[str]											=      writer.finalize()
          writer.close()
          yield pa.RecordBatch.from_arrays(
              [[task_id], [num_examples], [num_bytes]]    ,			names=["task_id", "num_examples", "num_bytes"]    ,			)

        if working_fpath != fpath:
          for file in os.listdir(os.path.dirname(__UpperCAmelCase)):
            a						:		int											=      os.path.join(os.path.dirname(__UpperCAmelCase)    ,			os.path.basename(__UpperCAmelCase))
            shutil.move(__UpperCAmelCase    ,			__UpperCAmelCase)

      a						:		str											=      (
          self.df.mapInArrow(__UpperCAmelCase    ,			"task_id: long, num_examples: long, num_bytes: long")
          .groupBy("task_id")
          .agg(
              pyspark.sql.functions.sum("num_examples").alias("total_num_examples")    ,			pyspark.sql.functions.sum("num_bytes").alias("total_num_bytes")    ,			pyspark.sql.functions.count("num_bytes").alias("num_shards")    ,			pyspark.sql.functions.collect_list("num_examples").alias("shard_lengths")    ,			)
          .collect()
      )
      for row in stats:
        yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)






    def      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   "datasets.SplitGenerator"    ,			__UpperCAmelCase    :   str = "arrow"    ,			__UpperCAmelCase    :   Optional[Union[str, int]] = None    ,			__UpperCAmelCase    :   Optional[int] = None    ,			**__UpperCAmelCase    :   str    ,			):
      self._validate_cache_dir()

      a						:		Union[str, Any]											=      convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE)
      self._repartition_df_if_needed(__UpperCAmelCase)
      a						:		Any											=      not is_remote_filesystem(self._fs)
      a						:		str											=      os.path.join if is_local else posixpath.join

      a						:		Dict											=      "-TTTTT-SSSSS-of-NNNNN"
      a						:		Optional[int]											=      f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}'''
      a						:		Dict											=      path_join(self._output_dir    ,			__UpperCAmelCase)

      a						:		Optional[int]											=      0
      a						:		Dict											=      0
      a						:		Dict											=      0
      a						:		List[str]											=      []
      a						:		List[Any]											=      []

      for task_id, content in self._prepare_split_single(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase):
        (
            (
            a
        )							,		(
            a
        )							,		(
            a
        )							,		(
            a
        )							,		
        )						:		Optional[int]											=      content
        if num_bytes > 0:
          total_num_examples += num_examples
          total_num_bytes += num_bytes
          total_shards += num_shards
          task_id_and_num_shards.append((task_id, num_shards))
          all_shard_lengths.extend(__UpperCAmelCase)

      a						:		int											=      total_num_examples
      a						:		Union[str, Any]											=      total_num_bytes

      # should rename everything at the end
      logger.debug(f'''Renaming {total_shards} shards.''')
      if total_shards > 1:
        a						:		Union[str, Any]											=      all_shard_lengths

        # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
        # pickling error due to pickling the SparkContext.
        a						:		List[Any]											=      self._fs

        # use the -SSSSS-of-NNNNN pattern
        def _rename_shard(
            __UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   int    ,			):
          rename(
              __UpperCAmelCase    ,			fpath.replace("SSSSS"    ,			f'''{shard_id:05d}''').replace("TTTTT"    ,			f'''{task_id:05d}''')    ,			fpath.replace("TTTTT-SSSSS"    ,			f'''{global_shard_id:05d}''').replace("NNNNN"    ,			f'''{total_shards:05d}''')    ,			)

        a						:		Optional[Any]											=      []
        a						:		Any											=      0
        for i in range(len(__UpperCAmelCase)):
          a							,		a						:		int											=      task_id_and_num_shards[i]
          for shard_id in range(__UpperCAmelCase):
            args.append([task_id, shard_id, global_shard_id])
            global_shard_id += 1
        self._spark.sparkContext.parallelize(__UpperCAmelCase    ,			len(__UpperCAmelCase)).map(lambda __UpperCAmelCase: _rename_shard(*__UpperCAmelCase)).collect()
      else:
        # don't use any pattern
        a						:		Any											=      0
        a						:		Dict											=      task_id_and_num_shards[0][0]
        self._rename(
            fpath.replace("SSSSS"    ,			f'''{shard_id:05d}''').replace("TTTTT"    ,			f'''{task_id:05d}''')    ,			fpath.replace(__UpperCAmelCase    ,			"")    ,			)






    def      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   "datasets.SplitGenerator"    ,			):
      return SparkExamplesIterable(self.df)










"""simple docstring"""







from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
 from ...onnx.config import PatchingSpec
 from ...tokenization_utils_base import PreTrainedTokenizerBase


__lowercase    =				logging.get_logger(__name__)

__lowercase    =				{
    """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096-finetuned-triviaqa""": (
        """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"""
    ),
    """allenai/longformer-base-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
    """allenai/longformer-large-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
}






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Optional[Any]     =	"""longformer"""






    def __init__( self    :   List[Any]    ,			__UpperCAmelCase    :   Union[List[int], int] = 512    ,			__UpperCAmelCase    :   int = 2    ,			__UpperCAmelCase    :   int = 1    ,			__UpperCAmelCase    :   int = 0    ,			__UpperCAmelCase    :   int = 2    ,			__UpperCAmelCase    :   int = 30522    ,			__UpperCAmelCase    :   int = 768    ,			__UpperCAmelCase    :   int = 12    ,			__UpperCAmelCase    :   int = 12    ,			__UpperCAmelCase    :   int = 3072    ,			__UpperCAmelCase    :   str = "gelu"    ,			__UpperCAmelCase    :   float = 0.1    ,			__UpperCAmelCase    :   float = 0.1    ,			__UpperCAmelCase    :   int = 512    ,			__UpperCAmelCase    :   int = 2    ,			__UpperCAmelCase    :   float = 0.02    ,			__UpperCAmelCase    :   float = 1e-12    ,			__UpperCAmelCase    :   bool = False    ,			**__UpperCAmelCase    :   int    ,			):
      super().__init__(pad_token_id=__UpperCAmelCase    ,			**__UpperCAmelCase)

      a						:		int											=      attention_window
      a						:		List[str]											=      sep_token_id
      a						:		List[Any]											=      bos_token_id
      a						:		int											=      eos_token_id
      a						:		Union[str, Any]											=      vocab_size
      a						:		Dict											=      hidden_size
      a						:		int											=      num_hidden_layers
      a						:		int											=      num_attention_heads
      a						:		Optional[int]											=      hidden_act
      a						:		Union[str, Any]											=      intermediate_size
      a						:		Tuple											=      hidden_dropout_prob
      a						:		Union[str, Any]											=      attention_probs_dropout_prob
      a						:		str											=      max_position_embeddings
      a						:		Dict											=      type_vocab_size
      a						:		Optional[Any]											=      initializer_range
      a						:		List[Any]											=      layer_norm_eps
      a						:		List[str]											=      onnx_export






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   Tuple    ,			__UpperCAmelCase    :   "PretrainedConfig"    ,			__UpperCAmelCase    :   str = "default"    ,			__UpperCAmelCase    :   "List[PatchingSpec]" = None):
      super().__init__(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)
      a						:		Optional[Any]											=      True






    @property
    def      __snake_case							( self    :   int):
      if self.task == "multiple-choice":
        a						:		List[Any]											=      {0: "batch", 1: "choice", 2: "sequence"}
      else:
        a						:		int											=      {0: "batch", 1: "sequence"}
      return OrderedDict(
          [
              ("input_ids", dynamic_axis),
              ("attention_mask", dynamic_axis),
              ("global_attention_mask", dynamic_axis),
          ])






    @property
    def      __snake_case							( self    :   Union[str, Any]):
      a						:		str											=      super().outputs
      if self.task == "default":
        a						:		Tuple											=      {0: "batch"}
      return outputs






    @property
    def      __snake_case							( self    :   Optional[int]):
      return 1e-4






    @property
    def      __snake_case							( self    :   str):
      # needs to be >= 14 to support tril operator
      return max(super().default_onnx_opset    ,			14)






    def      __snake_case							( self    :   List[str]    ,			__UpperCAmelCase    :   "PreTrainedTokenizerBase"    ,			__UpperCAmelCase    :   int = -1    ,			__UpperCAmelCase    :   int = -1    ,			__UpperCAmelCase    :   bool = False    ,			__UpperCAmelCase    :   Optional[TensorType] = None    ,			):
      a						:		str											=      super().generate_dummy_inputs(
          preprocessor=__UpperCAmelCase    ,			batch_size=__UpperCAmelCase    ,			seq_length=__UpperCAmelCase    ,			is_pair=__UpperCAmelCase    ,			framework=__UpperCAmelCase)
      import torch

      # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
      # makes the export fail randomly
      a						:		Union[str, Any]											=      torch.zeros_like(inputs["input_ids"])
      # make every second token global
      a						:		Dict											=      1

      return inputs






