
'''simple docstring'''
import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


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






@dataclass
class    UpperCAmelCase_				(	datasets.BuilderConfig					):
 UpperCAmelCase_		    =						1_0_0_0_0
 UpperCAmelCase_		    =						None
 UpperCAmelCase_		    =						None






class    UpperCAmelCase_				(	datasets.ArrowBasedBuilder					):
 UpperCAmelCase_		    =						ParquetConfig





 def        snake_case__		(    self):
     return datasets.DatasetInfo(features=self.config.features)





 def        snake_case__		(    self ,       lowercase_):
     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}')
     snake_case_ :    List[Any]     			=						dl_manager.download_and_extract(self.config.data_files)
     if isinstance(lowercase_ ,       (str, list, tuple)):
         snake_case_ :    List[Any]     			=						data_files
         if isinstance(lowercase_ ,       lowercase_):
             snake_case_ :    Tuple     			=						[files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         snake_case_ :    Optional[Any]     			=						[dl_manager.iter_files(lowercase_) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,       gen_kwargs={"files": files})]
     snake_case_ :    List[str]     			=						[]
     for split_name, files in data_files.items():
         if isinstance(lowercase_ ,       lowercase_):
             snake_case_ :    Union[str, Any]     			=						[files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         snake_case_ :    Optional[Any]     			=						[dl_manager.iter_files(lowercase_) for file in files]
         # Infer features is they are stoed in the arrow schema
         if self.info.features is None:
             for file in itertools.chain.from_iterable(lowercase_):
                 with open(lowercase_ ,       "rb") as f:
                     snake_case_ :    str     			=						datasets.Features.from_arrow_schema(pq.read_schema(lowercase_))
                 break
         splits.append(datasets.SplitGenerator(name=lowercase_ ,       gen_kwargs={"files": files}))
     return splits





 def        snake_case__		(    self ,       lowercase_):
     if self.info.features is not None:
         # more expensive cast to support nested features with keys in a different order
         # allows str <-> int/float or str to Audio for example
         snake_case_ :    List[Any]     			=						table_cast(lowercase_ ,       self.info.features.arrow_schema)
     return pa_table





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    List[Any]     			=						self.info.features.arrow_schema if self.info.features is not None else None
     if self.info.features is not None and self.config.columns is not None:
         if sorted(field.name for field in schema) != sorted(self.config.columns):
             raise ValueError(
                 F'Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'')
     for file_idx, file in enumerate(itertools.chain.from_iterable(lowercase_)):
         with open(lowercase_ ,       "rb") as f:
             snake_case_ :    Any     			=						pq.ParquetFile(lowercase_)
             try:
                 for batch_idx, record_batch in enumerate(
                     parquet_file.iter_batches(batch_size=self.config.batch_size ,       columns=self.config.columns)):
                     snake_case_ :    Union[str, Any]     			=						pa.Table.from_batches([record_batch])
                     # 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 F'{file_idx}_{batch_idx}', self._cast_table(lowercase_)
             except ValueError as e:
                 logger.error(F'Failed to read file \'{file}\' with error {type(lowercase_)}: {e}')
                 raise






'''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


a_											=						logging.get_logger(__name__)

a_											=						{
    "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    UpperCAmelCase_				(	snake_case__					):
 UpperCAmelCase_		    =						"""longformer"""





 def __init__(    self ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 1 ,       lowercase_ = 0 ,       lowercase_ = 2 ,       lowercase_ = 3_05_22 ,       lowercase_ = 7_68 ,       lowercase_ = 12 ,       lowercase_ = 12 ,       lowercase_ = 30_72 ,       lowercase_ = "gelu" ,       lowercase_ = 0.1 ,       lowercase_ = 0.1 ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 0.02 ,       lowercase_ = 1E-12 ,       lowercase_ = False ,       **lowercase_ ,       ):
     super().__init__(pad_token_id=lowercase_ ,       **lowercase_)

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






class    UpperCAmelCase_				(	snake_case__					):





 def __init__(    self ,       lowercase_ ,       lowercase_ = "default" ,       lowercase_ = None):
     super().__init__(lowercase_ ,       lowercase_ ,       lowercase_)
     snake_case_ :    Dict     			=						True





 @property
 def        snake_case__		(    self):
     if self.task == "multiple-choice":
         snake_case_ :    Tuple     			=						{0: "batch", 1: "choice", 2: "sequence"}
     else:
         snake_case_ :    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):
     snake_case_ :    Union[str, Any]     			=						super().outputs
     if self.task == "default":
         snake_case_ :    str     			=						{0: "batch"}
     return outputs





 @property
 def        snake_case__		(    self):
     return 1E-4





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





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ = -1 ,       lowercase_ = -1 ,       lowercase_ = False ,       lowercase_ = None ,       ):
     snake_case_ :    Optional[Any]     			=						super().generate_dummy_inputs(
         preprocessor=lowercase_ ,       batch_size=lowercase_ ,       seq_length=lowercase_ ,       is_pair=lowercase_ ,       framework=lowercase_)
     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
     snake_case_ :    Any     			=						torch.zeros_like(inputs["input_ids"])
     # make every second token global
     snake_case_ :    Tuple     			=						1

     return inputs




